tests/tcg: target/mips: Amend tests for MSA pack instructions
[qemu/ar7.git] / gdbstub.c
blob8618e3431107354f5dda48298e8d19b01dad165f
1 /*
2 * gdb server stub
4 * Copyright (c) 2003-2005 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20 #include "qemu/osdep.h"
21 #include "qemu-common.h"
22 #include "qapi/error.h"
23 #include "qemu/error-report.h"
24 #include "qemu/ctype.h"
25 #include "qemu/cutils.h"
26 #include "qemu/module.h"
27 #include "trace-root.h"
28 #ifdef CONFIG_USER_ONLY
29 #include "qemu.h"
30 #else
31 #include "monitor/monitor.h"
32 #include "chardev/char.h"
33 #include "chardev/char-fe.h"
34 #include "sysemu/sysemu.h"
35 #include "exec/gdbstub.h"
36 #include "hw/cpu/cluster.h"
37 #endif
39 #define MAX_PACKET_LENGTH 4096
41 #include "qemu/sockets.h"
42 #include "sysemu/hw_accel.h"
43 #include "sysemu/kvm.h"
44 #include "hw/semihosting/semihost.h"
45 #include "exec/exec-all.h"
47 #ifdef CONFIG_USER_ONLY
48 #define GDB_ATTACHED "0"
49 #else
50 #define GDB_ATTACHED "1"
51 #endif
53 #ifndef CONFIG_USER_ONLY
54 static int phy_memory_mode;
55 #endif
57 static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
58 uint8_t *buf, int len, bool is_write)
60 CPUClass *cc;
62 #ifndef CONFIG_USER_ONLY
63 if (phy_memory_mode) {
64 if (is_write) {
65 cpu_physical_memory_write(addr, buf, len);
66 } else {
67 cpu_physical_memory_read(addr, buf, len);
69 return 0;
71 #endif
73 cc = CPU_GET_CLASS(cpu);
74 if (cc->memory_rw_debug) {
75 return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
77 return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
80 /* Return the GDB index for a given vCPU state.
82 * For user mode this is simply the thread id. In system mode GDB
83 * numbers CPUs from 1 as 0 is reserved as an "any cpu" index.
85 static inline int cpu_gdb_index(CPUState *cpu)
87 #if defined(CONFIG_USER_ONLY)
88 TaskState *ts = (TaskState *) cpu->opaque;
89 return ts->ts_tid;
90 #else
91 return cpu->cpu_index + 1;
92 #endif
95 enum {
96 GDB_SIGNAL_0 = 0,
97 GDB_SIGNAL_INT = 2,
98 GDB_SIGNAL_QUIT = 3,
99 GDB_SIGNAL_TRAP = 5,
100 GDB_SIGNAL_ABRT = 6,
101 GDB_SIGNAL_ALRM = 14,
102 GDB_SIGNAL_IO = 23,
103 GDB_SIGNAL_XCPU = 24,
104 GDB_SIGNAL_UNKNOWN = 143
107 #ifdef CONFIG_USER_ONLY
109 /* Map target signal numbers to GDB protocol signal numbers and vice
110 * versa. For user emulation's currently supported systems, we can
111 * assume most signals are defined.
114 static int gdb_signal_table[] = {
116 TARGET_SIGHUP,
117 TARGET_SIGINT,
118 TARGET_SIGQUIT,
119 TARGET_SIGILL,
120 TARGET_SIGTRAP,
121 TARGET_SIGABRT,
122 -1, /* SIGEMT */
123 TARGET_SIGFPE,
124 TARGET_SIGKILL,
125 TARGET_SIGBUS,
126 TARGET_SIGSEGV,
127 TARGET_SIGSYS,
128 TARGET_SIGPIPE,
129 TARGET_SIGALRM,
130 TARGET_SIGTERM,
131 TARGET_SIGURG,
132 TARGET_SIGSTOP,
133 TARGET_SIGTSTP,
134 TARGET_SIGCONT,
135 TARGET_SIGCHLD,
136 TARGET_SIGTTIN,
137 TARGET_SIGTTOU,
138 TARGET_SIGIO,
139 TARGET_SIGXCPU,
140 TARGET_SIGXFSZ,
141 TARGET_SIGVTALRM,
142 TARGET_SIGPROF,
143 TARGET_SIGWINCH,
144 -1, /* SIGLOST */
145 TARGET_SIGUSR1,
146 TARGET_SIGUSR2,
147 #ifdef TARGET_SIGPWR
148 TARGET_SIGPWR,
149 #else
151 #endif
152 -1, /* SIGPOLL */
164 #ifdef __SIGRTMIN
165 __SIGRTMIN + 1,
166 __SIGRTMIN + 2,
167 __SIGRTMIN + 3,
168 __SIGRTMIN + 4,
169 __SIGRTMIN + 5,
170 __SIGRTMIN + 6,
171 __SIGRTMIN + 7,
172 __SIGRTMIN + 8,
173 __SIGRTMIN + 9,
174 __SIGRTMIN + 10,
175 __SIGRTMIN + 11,
176 __SIGRTMIN + 12,
177 __SIGRTMIN + 13,
178 __SIGRTMIN + 14,
179 __SIGRTMIN + 15,
180 __SIGRTMIN + 16,
181 __SIGRTMIN + 17,
182 __SIGRTMIN + 18,
183 __SIGRTMIN + 19,
184 __SIGRTMIN + 20,
185 __SIGRTMIN + 21,
186 __SIGRTMIN + 22,
187 __SIGRTMIN + 23,
188 __SIGRTMIN + 24,
189 __SIGRTMIN + 25,
190 __SIGRTMIN + 26,
191 __SIGRTMIN + 27,
192 __SIGRTMIN + 28,
193 __SIGRTMIN + 29,
194 __SIGRTMIN + 30,
195 __SIGRTMIN + 31,
196 -1, /* SIGCANCEL */
197 __SIGRTMIN,
198 __SIGRTMIN + 32,
199 __SIGRTMIN + 33,
200 __SIGRTMIN + 34,
201 __SIGRTMIN + 35,
202 __SIGRTMIN + 36,
203 __SIGRTMIN + 37,
204 __SIGRTMIN + 38,
205 __SIGRTMIN + 39,
206 __SIGRTMIN + 40,
207 __SIGRTMIN + 41,
208 __SIGRTMIN + 42,
209 __SIGRTMIN + 43,
210 __SIGRTMIN + 44,
211 __SIGRTMIN + 45,
212 __SIGRTMIN + 46,
213 __SIGRTMIN + 47,
214 __SIGRTMIN + 48,
215 __SIGRTMIN + 49,
216 __SIGRTMIN + 50,
217 __SIGRTMIN + 51,
218 __SIGRTMIN + 52,
219 __SIGRTMIN + 53,
220 __SIGRTMIN + 54,
221 __SIGRTMIN + 55,
222 __SIGRTMIN + 56,
223 __SIGRTMIN + 57,
224 __SIGRTMIN + 58,
225 __SIGRTMIN + 59,
226 __SIGRTMIN + 60,
227 __SIGRTMIN + 61,
228 __SIGRTMIN + 62,
229 __SIGRTMIN + 63,
230 __SIGRTMIN + 64,
231 __SIGRTMIN + 65,
232 __SIGRTMIN + 66,
233 __SIGRTMIN + 67,
234 __SIGRTMIN + 68,
235 __SIGRTMIN + 69,
236 __SIGRTMIN + 70,
237 __SIGRTMIN + 71,
238 __SIGRTMIN + 72,
239 __SIGRTMIN + 73,
240 __SIGRTMIN + 74,
241 __SIGRTMIN + 75,
242 __SIGRTMIN + 76,
243 __SIGRTMIN + 77,
244 __SIGRTMIN + 78,
245 __SIGRTMIN + 79,
246 __SIGRTMIN + 80,
247 __SIGRTMIN + 81,
248 __SIGRTMIN + 82,
249 __SIGRTMIN + 83,
250 __SIGRTMIN + 84,
251 __SIGRTMIN + 85,
252 __SIGRTMIN + 86,
253 __SIGRTMIN + 87,
254 __SIGRTMIN + 88,
255 __SIGRTMIN + 89,
256 __SIGRTMIN + 90,
257 __SIGRTMIN + 91,
258 __SIGRTMIN + 92,
259 __SIGRTMIN + 93,
260 __SIGRTMIN + 94,
261 __SIGRTMIN + 95,
262 -1, /* SIGINFO */
263 -1, /* UNKNOWN */
264 -1, /* DEFAULT */
271 #endif
273 #else
274 /* In system mode we only need SIGINT and SIGTRAP; other signals
275 are not yet supported. */
277 enum {
278 TARGET_SIGINT = 2,
279 TARGET_SIGTRAP = 5
282 static int gdb_signal_table[] = {
285 TARGET_SIGINT,
288 TARGET_SIGTRAP
290 #endif
292 #ifdef CONFIG_USER_ONLY
293 static int target_signal_to_gdb (int sig)
295 int i;
296 for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
297 if (gdb_signal_table[i] == sig)
298 return i;
299 return GDB_SIGNAL_UNKNOWN;
301 #endif
303 static int gdb_signal_to_target (int sig)
305 if (sig < ARRAY_SIZE (gdb_signal_table))
306 return gdb_signal_table[sig];
307 else
308 return -1;
311 typedef struct GDBRegisterState {
312 int base_reg;
313 int num_regs;
314 gdb_reg_cb get_reg;
315 gdb_reg_cb set_reg;
316 const char *xml;
317 struct GDBRegisterState *next;
318 } GDBRegisterState;
320 typedef struct GDBProcess {
321 uint32_t pid;
322 bool attached;
324 char target_xml[1024];
325 } GDBProcess;
327 enum RSState {
328 RS_INACTIVE,
329 RS_IDLE,
330 RS_GETLINE,
331 RS_GETLINE_ESC,
332 RS_GETLINE_RLE,
333 RS_CHKSUM1,
334 RS_CHKSUM2,
336 typedef struct GDBState {
337 CPUState *c_cpu; /* current CPU for step/continue ops */
338 CPUState *g_cpu; /* current CPU for other ops */
339 CPUState *query_cpu; /* for q{f|s}ThreadInfo */
340 enum RSState state; /* parsing state */
341 char line_buf[MAX_PACKET_LENGTH];
342 int line_buf_index;
343 int line_sum; /* running checksum */
344 int line_csum; /* checksum at the end of the packet */
345 uint8_t last_packet[MAX_PACKET_LENGTH + 4];
346 int last_packet_len;
347 int signal;
348 #ifdef CONFIG_USER_ONLY
349 int fd;
350 int running_state;
351 #else
352 CharBackend chr;
353 Chardev *mon_chr;
354 #endif
355 bool multiprocess;
356 GDBProcess *processes;
357 int process_num;
358 char syscall_buf[256];
359 gdb_syscall_complete_cb current_syscall_cb;
360 } GDBState;
362 /* By default use no IRQs and no timers while single stepping so as to
363 * make single stepping like an ICE HW step.
365 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
367 static GDBState *gdbserver_state;
369 bool gdb_has_xml;
371 #ifdef CONFIG_USER_ONLY
372 /* XXX: This is not thread safe. Do we care? */
373 static int gdbserver_fd = -1;
375 static int get_char(GDBState *s)
377 uint8_t ch;
378 int ret;
380 for(;;) {
381 ret = qemu_recv(s->fd, &ch, 1, 0);
382 if (ret < 0) {
383 if (errno == ECONNRESET)
384 s->fd = -1;
385 if (errno != EINTR)
386 return -1;
387 } else if (ret == 0) {
388 close(s->fd);
389 s->fd = -1;
390 return -1;
391 } else {
392 break;
395 return ch;
397 #endif
399 static enum {
400 GDB_SYS_UNKNOWN,
401 GDB_SYS_ENABLED,
402 GDB_SYS_DISABLED,
403 } gdb_syscall_mode;
405 /* Decide if either remote gdb syscalls or native file IO should be used. */
406 int use_gdb_syscalls(void)
408 SemihostingTarget target = semihosting_get_target();
409 if (target == SEMIHOSTING_TARGET_NATIVE) {
410 /* -semihosting-config target=native */
411 return false;
412 } else if (target == SEMIHOSTING_TARGET_GDB) {
413 /* -semihosting-config target=gdb */
414 return true;
417 /* -semihosting-config target=auto */
418 /* On the first call check if gdb is connected and remember. */
419 if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
420 gdb_syscall_mode = (gdbserver_state ? GDB_SYS_ENABLED
421 : GDB_SYS_DISABLED);
423 return gdb_syscall_mode == GDB_SYS_ENABLED;
426 /* Resume execution. */
427 static inline void gdb_continue(GDBState *s)
430 #ifdef CONFIG_USER_ONLY
431 s->running_state = 1;
432 trace_gdbstub_op_continue();
433 #else
434 if (!runstate_needs_reset()) {
435 trace_gdbstub_op_continue();
436 vm_start();
438 #endif
442 * Resume execution, per CPU actions. For user-mode emulation it's
443 * equivalent to gdb_continue.
445 static int gdb_continue_partial(GDBState *s, char *newstates)
447 CPUState *cpu;
448 int res = 0;
449 #ifdef CONFIG_USER_ONLY
451 * This is not exactly accurate, but it's an improvement compared to the
452 * previous situation, where only one CPU would be single-stepped.
454 CPU_FOREACH(cpu) {
455 if (newstates[cpu->cpu_index] == 's') {
456 trace_gdbstub_op_stepping(cpu->cpu_index);
457 cpu_single_step(cpu, sstep_flags);
460 s->running_state = 1;
461 #else
462 int flag = 0;
464 if (!runstate_needs_reset()) {
465 if (vm_prepare_start()) {
466 return 0;
469 CPU_FOREACH(cpu) {
470 switch (newstates[cpu->cpu_index]) {
471 case 0:
472 case 1:
473 break; /* nothing to do here */
474 case 's':
475 trace_gdbstub_op_stepping(cpu->cpu_index);
476 cpu_single_step(cpu, sstep_flags);
477 cpu_resume(cpu);
478 flag = 1;
479 break;
480 case 'c':
481 trace_gdbstub_op_continue_cpu(cpu->cpu_index);
482 cpu_resume(cpu);
483 flag = 1;
484 break;
485 default:
486 res = -1;
487 break;
491 if (flag) {
492 qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
494 #endif
495 return res;
498 static void put_buffer(GDBState *s, const uint8_t *buf, int len)
500 #ifdef CONFIG_USER_ONLY
501 int ret;
503 while (len > 0) {
504 ret = send(s->fd, buf, len, 0);
505 if (ret < 0) {
506 if (errno != EINTR)
507 return;
508 } else {
509 buf += ret;
510 len -= ret;
513 #else
514 /* XXX this blocks entire thread. Rewrite to use
515 * qemu_chr_fe_write and background I/O callbacks */
516 qemu_chr_fe_write_all(&s->chr, buf, len);
517 #endif
520 static inline int fromhex(int v)
522 if (v >= '0' && v <= '9')
523 return v - '0';
524 else if (v >= 'A' && v <= 'F')
525 return v - 'A' + 10;
526 else if (v >= 'a' && v <= 'f')
527 return v - 'a' + 10;
528 else
529 return 0;
532 static inline int tohex(int v)
534 if (v < 10)
535 return v + '0';
536 else
537 return v - 10 + 'a';
540 /* writes 2*len+1 bytes in buf */
541 static void memtohex(char *buf, const uint8_t *mem, int len)
543 int i, c;
544 char *q;
545 q = buf;
546 for(i = 0; i < len; i++) {
547 c = mem[i];
548 *q++ = tohex(c >> 4);
549 *q++ = tohex(c & 0xf);
551 *q = '\0';
554 static void hextomem(uint8_t *mem, const char *buf, int len)
556 int i;
558 for(i = 0; i < len; i++) {
559 mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
560 buf += 2;
564 static void hexdump(const char *buf, int len,
565 void (*trace_fn)(size_t ofs, char const *text))
567 char line_buffer[3 * 16 + 4 + 16 + 1];
569 size_t i;
570 for (i = 0; i < len || (i & 0xF); ++i) {
571 size_t byte_ofs = i & 15;
573 if (byte_ofs == 0) {
574 memset(line_buffer, ' ', 3 * 16 + 4 + 16);
575 line_buffer[3 * 16 + 4 + 16] = 0;
578 size_t col_group = (i >> 2) & 3;
579 size_t hex_col = byte_ofs * 3 + col_group;
580 size_t txt_col = 3 * 16 + 4 + byte_ofs;
582 if (i < len) {
583 char value = buf[i];
585 line_buffer[hex_col + 0] = tohex((value >> 4) & 0xF);
586 line_buffer[hex_col + 1] = tohex((value >> 0) & 0xF);
587 line_buffer[txt_col + 0] = (value >= ' ' && value < 127)
588 ? value
589 : '.';
592 if (byte_ofs == 0xF)
593 trace_fn(i & -16, line_buffer);
597 /* return -1 if error, 0 if OK */
598 static int put_packet_binary(GDBState *s, const char *buf, int len, bool dump)
600 int csum, i;
601 uint8_t *p;
603 if (dump && trace_event_get_state_backends(TRACE_GDBSTUB_IO_BINARYREPLY)) {
604 hexdump(buf, len, trace_gdbstub_io_binaryreply);
607 for(;;) {
608 p = s->last_packet;
609 *(p++) = '$';
610 memcpy(p, buf, len);
611 p += len;
612 csum = 0;
613 for(i = 0; i < len; i++) {
614 csum += buf[i];
616 *(p++) = '#';
617 *(p++) = tohex((csum >> 4) & 0xf);
618 *(p++) = tohex((csum) & 0xf);
620 s->last_packet_len = p - s->last_packet;
621 put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
623 #ifdef CONFIG_USER_ONLY
624 i = get_char(s);
625 if (i < 0)
626 return -1;
627 if (i == '+')
628 break;
629 #else
630 break;
631 #endif
633 return 0;
636 /* return -1 if error, 0 if OK */
637 static int put_packet(GDBState *s, const char *buf)
639 trace_gdbstub_io_reply(buf);
641 return put_packet_binary(s, buf, strlen(buf), false);
644 /* Encode data using the encoding for 'x' packets. */
645 static int memtox(char *buf, const char *mem, int len)
647 char *p = buf;
648 char c;
650 while (len--) {
651 c = *(mem++);
652 switch (c) {
653 case '#': case '$': case '*': case '}':
654 *(p++) = '}';
655 *(p++) = c ^ 0x20;
656 break;
657 default:
658 *(p++) = c;
659 break;
662 return p - buf;
665 static uint32_t gdb_get_cpu_pid(const GDBState *s, CPUState *cpu)
667 /* TODO: In user mode, we should use the task state PID */
668 if (cpu->cluster_index == UNASSIGNED_CLUSTER_INDEX) {
669 /* Return the default process' PID */
670 return s->processes[s->process_num - 1].pid;
672 return cpu->cluster_index + 1;
675 static GDBProcess *gdb_get_process(const GDBState *s, uint32_t pid)
677 int i;
679 if (!pid) {
680 /* 0 means any process, we take the first one */
681 return &s->processes[0];
684 for (i = 0; i < s->process_num; i++) {
685 if (s->processes[i].pid == pid) {
686 return &s->processes[i];
690 return NULL;
693 static GDBProcess *gdb_get_cpu_process(const GDBState *s, CPUState *cpu)
695 return gdb_get_process(s, gdb_get_cpu_pid(s, cpu));
698 static CPUState *find_cpu(uint32_t thread_id)
700 CPUState *cpu;
702 CPU_FOREACH(cpu) {
703 if (cpu_gdb_index(cpu) == thread_id) {
704 return cpu;
708 return NULL;
711 static CPUState *get_first_cpu_in_process(const GDBState *s,
712 GDBProcess *process)
714 CPUState *cpu;
716 CPU_FOREACH(cpu) {
717 if (gdb_get_cpu_pid(s, cpu) == process->pid) {
718 return cpu;
722 return NULL;
725 static CPUState *gdb_next_cpu_in_process(const GDBState *s, CPUState *cpu)
727 uint32_t pid = gdb_get_cpu_pid(s, cpu);
728 cpu = CPU_NEXT(cpu);
730 while (cpu) {
731 if (gdb_get_cpu_pid(s, cpu) == pid) {
732 break;
735 cpu = CPU_NEXT(cpu);
738 return cpu;
741 /* Return the cpu following @cpu, while ignoring unattached processes. */
742 static CPUState *gdb_next_attached_cpu(const GDBState *s, CPUState *cpu)
744 cpu = CPU_NEXT(cpu);
746 while (cpu) {
747 if (gdb_get_cpu_process(s, cpu)->attached) {
748 break;
751 cpu = CPU_NEXT(cpu);
754 return cpu;
757 /* Return the first attached cpu */
758 static CPUState *gdb_first_attached_cpu(const GDBState *s)
760 CPUState *cpu = first_cpu;
761 GDBProcess *process = gdb_get_cpu_process(s, cpu);
763 if (!process->attached) {
764 return gdb_next_attached_cpu(s, cpu);
767 return cpu;
770 static CPUState *gdb_get_cpu(const GDBState *s, uint32_t pid, uint32_t tid)
772 GDBProcess *process;
773 CPUState *cpu;
775 if (!pid && !tid) {
776 /* 0 means any process/thread, we take the first attached one */
777 return gdb_first_attached_cpu(s);
778 } else if (pid && !tid) {
779 /* any thread in a specific process */
780 process = gdb_get_process(s, pid);
782 if (process == NULL) {
783 return NULL;
786 if (!process->attached) {
787 return NULL;
790 return get_first_cpu_in_process(s, process);
791 } else {
792 /* a specific thread */
793 cpu = find_cpu(tid);
795 if (cpu == NULL) {
796 return NULL;
799 process = gdb_get_cpu_process(s, cpu);
801 if (pid && process->pid != pid) {
802 return NULL;
805 if (!process->attached) {
806 return NULL;
809 return cpu;
813 static const char *get_feature_xml(const GDBState *s, const char *p,
814 const char **newp, GDBProcess *process)
816 size_t len;
817 int i;
818 const char *name;
819 CPUState *cpu = get_first_cpu_in_process(s, process);
820 CPUClass *cc = CPU_GET_CLASS(cpu);
822 len = 0;
823 while (p[len] && p[len] != ':')
824 len++;
825 *newp = p + len;
827 name = NULL;
828 if (strncmp(p, "target.xml", len) == 0) {
829 char *buf = process->target_xml;
830 const size_t buf_sz = sizeof(process->target_xml);
832 /* Generate the XML description for this CPU. */
833 if (!buf[0]) {
834 GDBRegisterState *r;
836 pstrcat(buf, buf_sz,
837 "<?xml version=\"1.0\"?>"
838 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
839 "<target>");
840 if (cc->gdb_arch_name) {
841 gchar *arch = cc->gdb_arch_name(cpu);
842 pstrcat(buf, buf_sz, "<architecture>");
843 pstrcat(buf, buf_sz, arch);
844 pstrcat(buf, buf_sz, "</architecture>");
845 g_free(arch);
847 pstrcat(buf, buf_sz, "<xi:include href=\"");
848 pstrcat(buf, buf_sz, cc->gdb_core_xml_file);
849 pstrcat(buf, buf_sz, "\"/>");
850 for (r = cpu->gdb_regs; r; r = r->next) {
851 pstrcat(buf, buf_sz, "<xi:include href=\"");
852 pstrcat(buf, buf_sz, r->xml);
853 pstrcat(buf, buf_sz, "\"/>");
855 pstrcat(buf, buf_sz, "</target>");
857 return buf;
859 if (cc->gdb_get_dynamic_xml) {
860 char *xmlname = g_strndup(p, len);
861 const char *xml = cc->gdb_get_dynamic_xml(cpu, xmlname);
863 g_free(xmlname);
864 if (xml) {
865 return xml;
868 for (i = 0; ; i++) {
869 name = xml_builtin[i][0];
870 if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
871 break;
873 return name ? xml_builtin[i][1] : NULL;
876 static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
878 CPUClass *cc = CPU_GET_CLASS(cpu);
879 CPUArchState *env = cpu->env_ptr;
880 GDBRegisterState *r;
882 if (reg < cc->gdb_num_core_regs) {
883 return cc->gdb_read_register(cpu, mem_buf, reg);
886 for (r = cpu->gdb_regs; r; r = r->next) {
887 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
888 return r->get_reg(env, mem_buf, reg - r->base_reg);
891 return 0;
894 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
896 CPUClass *cc = CPU_GET_CLASS(cpu);
897 CPUArchState *env = cpu->env_ptr;
898 GDBRegisterState *r;
900 if (reg < cc->gdb_num_core_regs) {
901 return cc->gdb_write_register(cpu, mem_buf, reg);
904 for (r = cpu->gdb_regs; r; r = r->next) {
905 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
906 return r->set_reg(env, mem_buf, reg - r->base_reg);
909 return 0;
912 /* Register a supplemental set of CPU registers. If g_pos is nonzero it
913 specifies the first register number and these registers are included in
914 a standard "g" packet. Direction is relative to gdb, i.e. get_reg is
915 gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
918 void gdb_register_coprocessor(CPUState *cpu,
919 gdb_reg_cb get_reg, gdb_reg_cb set_reg,
920 int num_regs, const char *xml, int g_pos)
922 GDBRegisterState *s;
923 GDBRegisterState **p;
925 p = &cpu->gdb_regs;
926 while (*p) {
927 /* Check for duplicates. */
928 if (strcmp((*p)->xml, xml) == 0)
929 return;
930 p = &(*p)->next;
933 s = g_new0(GDBRegisterState, 1);
934 s->base_reg = cpu->gdb_num_regs;
935 s->num_regs = num_regs;
936 s->get_reg = get_reg;
937 s->set_reg = set_reg;
938 s->xml = xml;
940 /* Add to end of list. */
941 cpu->gdb_num_regs += num_regs;
942 *p = s;
943 if (g_pos) {
944 if (g_pos != s->base_reg) {
945 error_report("Error: Bad gdb register numbering for '%s', "
946 "expected %d got %d", xml, g_pos, s->base_reg);
947 } else {
948 cpu->gdb_num_g_regs = cpu->gdb_num_regs;
953 #ifndef CONFIG_USER_ONLY
954 /* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
955 static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
957 static const int xlat[] = {
958 [GDB_WATCHPOINT_WRITE] = BP_GDB | BP_MEM_WRITE,
959 [GDB_WATCHPOINT_READ] = BP_GDB | BP_MEM_READ,
960 [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
963 CPUClass *cc = CPU_GET_CLASS(cpu);
964 int cputype = xlat[gdbtype];
966 if (cc->gdb_stop_before_watchpoint) {
967 cputype |= BP_STOP_BEFORE_ACCESS;
969 return cputype;
971 #endif
973 static int gdb_breakpoint_insert(int type, target_ulong addr, target_ulong len)
975 CPUState *cpu;
976 int err = 0;
978 if (kvm_enabled()) {
979 return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
982 switch (type) {
983 case GDB_BREAKPOINT_SW:
984 case GDB_BREAKPOINT_HW:
985 CPU_FOREACH(cpu) {
986 err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
987 if (err) {
988 break;
991 return err;
992 #ifndef CONFIG_USER_ONLY
993 case GDB_WATCHPOINT_WRITE:
994 case GDB_WATCHPOINT_READ:
995 case GDB_WATCHPOINT_ACCESS:
996 CPU_FOREACH(cpu) {
997 err = cpu_watchpoint_insert(cpu, addr, len,
998 xlat_gdb_type(cpu, type), NULL);
999 if (err) {
1000 break;
1003 return err;
1004 #endif
1005 default:
1006 return -ENOSYS;
1010 static int gdb_breakpoint_remove(int type, target_ulong addr, target_ulong len)
1012 CPUState *cpu;
1013 int err = 0;
1015 if (kvm_enabled()) {
1016 return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
1019 switch (type) {
1020 case GDB_BREAKPOINT_SW:
1021 case GDB_BREAKPOINT_HW:
1022 CPU_FOREACH(cpu) {
1023 err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
1024 if (err) {
1025 break;
1028 return err;
1029 #ifndef CONFIG_USER_ONLY
1030 case GDB_WATCHPOINT_WRITE:
1031 case GDB_WATCHPOINT_READ:
1032 case GDB_WATCHPOINT_ACCESS:
1033 CPU_FOREACH(cpu) {
1034 err = cpu_watchpoint_remove(cpu, addr, len,
1035 xlat_gdb_type(cpu, type));
1036 if (err)
1037 break;
1039 return err;
1040 #endif
1041 default:
1042 return -ENOSYS;
1046 static inline void gdb_cpu_breakpoint_remove_all(CPUState *cpu)
1048 cpu_breakpoint_remove_all(cpu, BP_GDB);
1049 #ifndef CONFIG_USER_ONLY
1050 cpu_watchpoint_remove_all(cpu, BP_GDB);
1051 #endif
1054 static void gdb_process_breakpoint_remove_all(const GDBState *s, GDBProcess *p)
1056 CPUState *cpu = get_first_cpu_in_process(s, p);
1058 while (cpu) {
1059 gdb_cpu_breakpoint_remove_all(cpu);
1060 cpu = gdb_next_cpu_in_process(s, cpu);
1064 static void gdb_breakpoint_remove_all(void)
1066 CPUState *cpu;
1068 if (kvm_enabled()) {
1069 kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
1070 return;
1073 CPU_FOREACH(cpu) {
1074 gdb_cpu_breakpoint_remove_all(cpu);
1078 static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
1080 CPUState *cpu = s->c_cpu;
1082 cpu_synchronize_state(cpu);
1083 cpu_set_pc(cpu, pc);
1086 static char *gdb_fmt_thread_id(const GDBState *s, CPUState *cpu,
1087 char *buf, size_t buf_size)
1089 if (s->multiprocess) {
1090 snprintf(buf, buf_size, "p%02x.%02x",
1091 gdb_get_cpu_pid(s, cpu), cpu_gdb_index(cpu));
1092 } else {
1093 snprintf(buf, buf_size, "%02x", cpu_gdb_index(cpu));
1096 return buf;
1099 typedef enum GDBThreadIdKind {
1100 GDB_ONE_THREAD = 0,
1101 GDB_ALL_THREADS, /* One process, all threads */
1102 GDB_ALL_PROCESSES,
1103 GDB_READ_THREAD_ERR
1104 } GDBThreadIdKind;
1106 static GDBThreadIdKind read_thread_id(const char *buf, const char **end_buf,
1107 uint32_t *pid, uint32_t *tid)
1109 unsigned long p, t;
1110 int ret;
1112 if (*buf == 'p') {
1113 buf++;
1114 ret = qemu_strtoul(buf, &buf, 16, &p);
1116 if (ret) {
1117 return GDB_READ_THREAD_ERR;
1120 /* Skip '.' */
1121 buf++;
1122 } else {
1123 p = 1;
1126 ret = qemu_strtoul(buf, &buf, 16, &t);
1128 if (ret) {
1129 return GDB_READ_THREAD_ERR;
1132 *end_buf = buf;
1134 if (p == -1) {
1135 return GDB_ALL_PROCESSES;
1138 if (pid) {
1139 *pid = p;
1142 if (t == -1) {
1143 return GDB_ALL_THREADS;
1146 if (tid) {
1147 *tid = t;
1150 return GDB_ONE_THREAD;
1154 * gdb_handle_vcont - Parses and handles a vCont packet.
1155 * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
1156 * a format error, 0 on success.
1158 static int gdb_handle_vcont(GDBState *s, const char *p)
1160 int res, signal = 0;
1161 char cur_action;
1162 char *newstates;
1163 unsigned long tmp;
1164 uint32_t pid, tid;
1165 GDBProcess *process;
1166 CPUState *cpu;
1167 GDBThreadIdKind kind;
1168 #ifdef CONFIG_USER_ONLY
1169 int max_cpus = 1; /* global variable max_cpus exists only in system mode */
1171 CPU_FOREACH(cpu) {
1172 max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
1174 #endif
1175 /* uninitialised CPUs stay 0 */
1176 newstates = g_new0(char, max_cpus);
1178 /* mark valid CPUs with 1 */
1179 CPU_FOREACH(cpu) {
1180 newstates[cpu->cpu_index] = 1;
1184 * res keeps track of what error we are returning, with -ENOTSUP meaning
1185 * that the command is unknown or unsupported, thus returning an empty
1186 * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
1187 * or incorrect parameters passed.
1189 res = 0;
1190 while (*p) {
1191 if (*p++ != ';') {
1192 res = -ENOTSUP;
1193 goto out;
1196 cur_action = *p++;
1197 if (cur_action == 'C' || cur_action == 'S') {
1198 cur_action = qemu_tolower(cur_action);
1199 res = qemu_strtoul(p + 1, &p, 16, &tmp);
1200 if (res) {
1201 goto out;
1203 signal = gdb_signal_to_target(tmp);
1204 } else if (cur_action != 'c' && cur_action != 's') {
1205 /* unknown/invalid/unsupported command */
1206 res = -ENOTSUP;
1207 goto out;
1210 if (*p == '\0' || *p == ';') {
1212 * No thread specifier, action is on "all threads". The
1213 * specification is unclear regarding the process to act on. We
1214 * choose all processes.
1216 kind = GDB_ALL_PROCESSES;
1217 } else if (*p++ == ':') {
1218 kind = read_thread_id(p, &p, &pid, &tid);
1219 } else {
1220 res = -ENOTSUP;
1221 goto out;
1224 switch (kind) {
1225 case GDB_READ_THREAD_ERR:
1226 res = -EINVAL;
1227 goto out;
1229 case GDB_ALL_PROCESSES:
1230 cpu = gdb_first_attached_cpu(s);
1231 while (cpu) {
1232 if (newstates[cpu->cpu_index] == 1) {
1233 newstates[cpu->cpu_index] = cur_action;
1236 cpu = gdb_next_attached_cpu(s, cpu);
1238 break;
1240 case GDB_ALL_THREADS:
1241 process = gdb_get_process(s, pid);
1243 if (!process->attached) {
1244 res = -EINVAL;
1245 goto out;
1248 cpu = get_first_cpu_in_process(s, process);
1249 while (cpu) {
1250 if (newstates[cpu->cpu_index] == 1) {
1251 newstates[cpu->cpu_index] = cur_action;
1254 cpu = gdb_next_cpu_in_process(s, cpu);
1256 break;
1258 case GDB_ONE_THREAD:
1259 cpu = gdb_get_cpu(s, pid, tid);
1261 /* invalid CPU/thread specified */
1262 if (!cpu) {
1263 res = -EINVAL;
1264 goto out;
1267 /* only use if no previous match occourred */
1268 if (newstates[cpu->cpu_index] == 1) {
1269 newstates[cpu->cpu_index] = cur_action;
1271 break;
1274 s->signal = signal;
1275 gdb_continue_partial(s, newstates);
1277 out:
1278 g_free(newstates);
1280 return res;
1283 typedef union GdbCmdVariant {
1284 const char *data;
1285 uint8_t opcode;
1286 unsigned long val_ul;
1287 unsigned long long val_ull;
1288 struct {
1289 GDBThreadIdKind kind;
1290 uint32_t pid;
1291 uint32_t tid;
1292 } thread_id;
1293 } GdbCmdVariant;
1295 static const char *cmd_next_param(const char *param, const char delimiter)
1297 static const char all_delimiters[] = ",;:=";
1298 char curr_delimiters[2] = {0};
1299 const char *delimiters;
1301 if (delimiter == '?') {
1302 delimiters = all_delimiters;
1303 } else if (delimiter == '0') {
1304 return strchr(param, '\0');
1305 } else if (delimiter == '.' && *param) {
1306 return param + 1;
1307 } else {
1308 curr_delimiters[0] = delimiter;
1309 delimiters = curr_delimiters;
1312 param += strcspn(param, delimiters);
1313 if (*param) {
1314 param++;
1316 return param;
1319 static int cmd_parse_params(const char *data, const char *schema,
1320 GdbCmdVariant *params, int *num_params)
1322 int curr_param;
1323 const char *curr_schema, *curr_data;
1325 *num_params = 0;
1327 if (!schema) {
1328 return 0;
1331 curr_schema = schema;
1332 curr_param = 0;
1333 curr_data = data;
1334 while (curr_schema[0] && curr_schema[1] && *curr_data) {
1335 switch (curr_schema[0]) {
1336 case 'l':
1337 if (qemu_strtoul(curr_data, &curr_data, 16,
1338 &params[curr_param].val_ul)) {
1339 return -EINVAL;
1341 curr_param++;
1342 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1343 break;
1344 case 'L':
1345 if (qemu_strtou64(curr_data, &curr_data, 16,
1346 (uint64_t *)&params[curr_param].val_ull)) {
1347 return -EINVAL;
1349 curr_param++;
1350 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1351 break;
1352 case 's':
1353 params[curr_param].data = curr_data;
1354 curr_param++;
1355 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1356 break;
1357 case 'o':
1358 params[curr_param].opcode = *(uint8_t *)curr_data;
1359 curr_param++;
1360 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1361 break;
1362 case 't':
1363 params[curr_param].thread_id.kind =
1364 read_thread_id(curr_data, &curr_data,
1365 &params[curr_param].thread_id.pid,
1366 &params[curr_param].thread_id.tid);
1367 curr_param++;
1368 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1369 break;
1370 case '?':
1371 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1372 break;
1373 default:
1374 return -EINVAL;
1376 curr_schema += 2;
1379 *num_params = curr_param;
1380 return 0;
1383 typedef struct GdbCmdContext {
1384 GDBState *s;
1385 GdbCmdVariant *params;
1386 int num_params;
1387 uint8_t mem_buf[MAX_PACKET_LENGTH];
1388 char str_buf[MAX_PACKET_LENGTH + 1];
1389 } GdbCmdContext;
1391 typedef void (*GdbCmdHandler)(GdbCmdContext *gdb_ctx, void *user_ctx);
1394 * cmd_startswith -> cmd is compared using startswith
1397 * schema definitions:
1398 * Each schema parameter entry consists of 2 chars,
1399 * the first char represents the parameter type handling
1400 * the second char represents the delimiter for the next parameter
1402 * Currently supported schema types:
1403 * 'l' -> unsigned long (stored in .val_ul)
1404 * 'L' -> unsigned long long (stored in .val_ull)
1405 * 's' -> string (stored in .data)
1406 * 'o' -> single char (stored in .opcode)
1407 * 't' -> thread id (stored in .thread_id)
1408 * '?' -> skip according to delimiter
1410 * Currently supported delimiters:
1411 * '?' -> Stop at any delimiter (",;:=\0")
1412 * '0' -> Stop at "\0"
1413 * '.' -> Skip 1 char unless reached "\0"
1414 * Any other value is treated as the delimiter value itself
1416 typedef struct GdbCmdParseEntry {
1417 GdbCmdHandler handler;
1418 const char *cmd;
1419 bool cmd_startswith;
1420 const char *schema;
1421 } GdbCmdParseEntry;
1423 static inline int startswith(const char *string, const char *pattern)
1425 return !strncmp(string, pattern, strlen(pattern));
1428 static int process_string_cmd(GDBState *s, void *user_ctx, const char *data,
1429 const GdbCmdParseEntry *cmds, int num_cmds)
1431 int i, schema_len, max_num_params = 0;
1432 GdbCmdContext gdb_ctx;
1434 if (!cmds) {
1435 return -1;
1438 for (i = 0; i < num_cmds; i++) {
1439 const GdbCmdParseEntry *cmd = &cmds[i];
1440 g_assert(cmd->handler && cmd->cmd);
1442 if ((cmd->cmd_startswith && !startswith(data, cmd->cmd)) ||
1443 (!cmd->cmd_startswith && strcmp(cmd->cmd, data))) {
1444 continue;
1447 if (cmd->schema) {
1448 schema_len = strlen(cmd->schema);
1449 if (schema_len % 2) {
1450 return -2;
1453 max_num_params = schema_len / 2;
1456 gdb_ctx.params =
1457 (GdbCmdVariant *)alloca(sizeof(*gdb_ctx.params) * max_num_params);
1458 memset(gdb_ctx.params, 0, sizeof(*gdb_ctx.params) * max_num_params);
1460 if (cmd_parse_params(&data[strlen(cmd->cmd)], cmd->schema,
1461 gdb_ctx.params, &gdb_ctx.num_params)) {
1462 return -1;
1465 gdb_ctx.s = s;
1466 cmd->handler(&gdb_ctx, user_ctx);
1467 return 0;
1470 return -1;
1473 static void run_cmd_parser(GDBState *s, const char *data,
1474 const GdbCmdParseEntry *cmd)
1476 if (!data) {
1477 return;
1480 /* In case there was an error during the command parsing we must
1481 * send a NULL packet to indicate the command is not supported */
1482 if (process_string_cmd(s, NULL, data, cmd, 1)) {
1483 put_packet(s, "");
1487 static void handle_detach(GdbCmdContext *gdb_ctx, void *user_ctx)
1489 GDBProcess *process;
1490 GDBState *s = gdb_ctx->s;
1491 uint32_t pid = 1;
1493 if (s->multiprocess) {
1494 if (!gdb_ctx->num_params) {
1495 put_packet(s, "E22");
1496 return;
1499 pid = gdb_ctx->params[0].val_ul;
1502 process = gdb_get_process(s, pid);
1503 gdb_process_breakpoint_remove_all(s, process);
1504 process->attached = false;
1506 if (pid == gdb_get_cpu_pid(s, s->c_cpu)) {
1507 s->c_cpu = gdb_first_attached_cpu(s);
1510 if (pid == gdb_get_cpu_pid(s, s->g_cpu)) {
1511 s->g_cpu = gdb_first_attached_cpu(s);
1514 if (!s->c_cpu) {
1515 /* No more process attached */
1516 gdb_syscall_mode = GDB_SYS_DISABLED;
1517 gdb_continue(s);
1519 put_packet(s, "OK");
1522 static void handle_thread_alive(GdbCmdContext *gdb_ctx, void *user_ctx)
1524 CPUState *cpu;
1526 if (!gdb_ctx->num_params) {
1527 put_packet(gdb_ctx->s, "E22");
1528 return;
1531 if (gdb_ctx->params[0].thread_id.kind == GDB_READ_THREAD_ERR) {
1532 put_packet(gdb_ctx->s, "E22");
1533 return;
1536 cpu = gdb_get_cpu(gdb_ctx->s, gdb_ctx->params[0].thread_id.pid,
1537 gdb_ctx->params[0].thread_id.tid);
1538 if (!cpu) {
1539 put_packet(gdb_ctx->s, "E22");
1540 return;
1543 put_packet(gdb_ctx->s, "OK");
1546 static void handle_continue(GdbCmdContext *gdb_ctx, void *user_ctx)
1548 if (gdb_ctx->num_params) {
1549 gdb_set_cpu_pc(gdb_ctx->s, gdb_ctx->params[0].val_ull);
1552 gdb_ctx->s->signal = 0;
1553 gdb_continue(gdb_ctx->s);
1556 static void handle_cont_with_sig(GdbCmdContext *gdb_ctx, void *user_ctx)
1558 unsigned long signal = 0;
1561 * Note: C sig;[addr] is currently unsupported and we simply
1562 * omit the addr parameter
1564 if (gdb_ctx->num_params) {
1565 signal = gdb_ctx->params[0].val_ul;
1568 gdb_ctx->s->signal = gdb_signal_to_target(signal);
1569 if (gdb_ctx->s->signal == -1) {
1570 gdb_ctx->s->signal = 0;
1572 gdb_continue(gdb_ctx->s);
1575 static void handle_set_thread(GdbCmdContext *gdb_ctx, void *user_ctx)
1577 CPUState *cpu;
1579 if (gdb_ctx->num_params != 2) {
1580 put_packet(gdb_ctx->s, "E22");
1581 return;
1584 if (gdb_ctx->params[1].thread_id.kind == GDB_READ_THREAD_ERR) {
1585 put_packet(gdb_ctx->s, "E22");
1586 return;
1589 if (gdb_ctx->params[1].thread_id.kind != GDB_ONE_THREAD) {
1590 put_packet(gdb_ctx->s, "OK");
1591 return;
1594 cpu = gdb_get_cpu(gdb_ctx->s, gdb_ctx->params[1].thread_id.pid,
1595 gdb_ctx->params[1].thread_id.tid);
1596 if (!cpu) {
1597 put_packet(gdb_ctx->s, "E22");
1598 return;
1602 * Note: This command is deprecated and modern gdb's will be using the
1603 * vCont command instead.
1605 switch (gdb_ctx->params[0].opcode) {
1606 case 'c':
1607 gdb_ctx->s->c_cpu = cpu;
1608 put_packet(gdb_ctx->s, "OK");
1609 break;
1610 case 'g':
1611 gdb_ctx->s->g_cpu = cpu;
1612 put_packet(gdb_ctx->s, "OK");
1613 break;
1614 default:
1615 put_packet(gdb_ctx->s, "E22");
1616 break;
1620 static void handle_insert_bp(GdbCmdContext *gdb_ctx, void *user_ctx)
1622 int res;
1624 if (gdb_ctx->num_params != 3) {
1625 put_packet(gdb_ctx->s, "E22");
1626 return;
1629 res = gdb_breakpoint_insert(gdb_ctx->params[0].val_ul,
1630 gdb_ctx->params[1].val_ull,
1631 gdb_ctx->params[2].val_ull);
1632 if (res >= 0) {
1633 put_packet(gdb_ctx->s, "OK");
1634 return;
1635 } else if (res == -ENOSYS) {
1636 put_packet(gdb_ctx->s, "");
1637 return;
1640 put_packet(gdb_ctx->s, "E22");
1643 static void handle_remove_bp(GdbCmdContext *gdb_ctx, void *user_ctx)
1645 int res;
1647 if (gdb_ctx->num_params != 3) {
1648 put_packet(gdb_ctx->s, "E22");
1649 return;
1652 res = gdb_breakpoint_remove(gdb_ctx->params[0].val_ul,
1653 gdb_ctx->params[1].val_ull,
1654 gdb_ctx->params[2].val_ull);
1655 if (res >= 0) {
1656 put_packet(gdb_ctx->s, "OK");
1657 return;
1658 } else if (res == -ENOSYS) {
1659 put_packet(gdb_ctx->s, "");
1660 return;
1663 put_packet(gdb_ctx->s, "E22");
1666 static void handle_set_reg(GdbCmdContext *gdb_ctx, void *user_ctx)
1668 int reg_size;
1670 if (!gdb_has_xml) {
1671 put_packet(gdb_ctx->s, "E00");
1672 return;
1675 if (gdb_ctx->num_params != 2) {
1676 put_packet(gdb_ctx->s, "E22");
1677 return;
1680 reg_size = strlen(gdb_ctx->params[1].data) / 2;
1681 hextomem(gdb_ctx->mem_buf, gdb_ctx->params[1].data, reg_size);
1682 gdb_write_register(gdb_ctx->s->g_cpu, gdb_ctx->mem_buf,
1683 gdb_ctx->params[0].val_ull);
1684 put_packet(gdb_ctx->s, "OK");
1687 static void handle_get_reg(GdbCmdContext *gdb_ctx, void *user_ctx)
1689 int reg_size;
1692 * Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
1693 * This works, but can be very slow. Anything new enough to
1694 * understand XML also knows how to use this properly.
1696 if (!gdb_has_xml) {
1697 put_packet(gdb_ctx->s, "");
1698 return;
1701 if (!gdb_ctx->num_params) {
1702 put_packet(gdb_ctx->s, "E14");
1703 return;
1706 reg_size = gdb_read_register(gdb_ctx->s->g_cpu, gdb_ctx->mem_buf,
1707 gdb_ctx->params[0].val_ull);
1708 if (!reg_size) {
1709 put_packet(gdb_ctx->s, "E14");
1710 return;
1713 memtohex(gdb_ctx->str_buf, gdb_ctx->mem_buf, reg_size);
1714 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
1717 static void handle_write_mem(GdbCmdContext *gdb_ctx, void *user_ctx)
1719 if (gdb_ctx->num_params != 3) {
1720 put_packet(gdb_ctx->s, "E22");
1721 return;
1724 /* hextomem() reads 2*len bytes */
1725 if (gdb_ctx->params[1].val_ull > strlen(gdb_ctx->params[2].data) / 2) {
1726 put_packet(gdb_ctx->s, "E22");
1727 return;
1730 hextomem(gdb_ctx->mem_buf, gdb_ctx->params[2].data,
1731 gdb_ctx->params[1].val_ull);
1732 if (target_memory_rw_debug(gdb_ctx->s->g_cpu, gdb_ctx->params[0].val_ull,
1733 gdb_ctx->mem_buf,
1734 gdb_ctx->params[1].val_ull, true)) {
1735 put_packet(gdb_ctx->s, "E14");
1736 return;
1739 put_packet(gdb_ctx->s, "OK");
1742 static void handle_read_mem(GdbCmdContext *gdb_ctx, void *user_ctx)
1744 if (gdb_ctx->num_params != 2) {
1745 put_packet(gdb_ctx->s, "E22");
1746 return;
1749 /* memtohex() doubles the required space */
1750 if (gdb_ctx->params[1].val_ull > MAX_PACKET_LENGTH / 2) {
1751 put_packet(gdb_ctx->s, "E22");
1752 return;
1755 if (target_memory_rw_debug(gdb_ctx->s->g_cpu, gdb_ctx->params[0].val_ull,
1756 gdb_ctx->mem_buf,
1757 gdb_ctx->params[1].val_ull, false)) {
1758 put_packet(gdb_ctx->s, "E14");
1759 return;
1762 memtohex(gdb_ctx->str_buf, gdb_ctx->mem_buf, gdb_ctx->params[1].val_ull);
1763 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
1766 static void handle_write_all_regs(GdbCmdContext *gdb_ctx, void *user_ctx)
1768 target_ulong addr, len;
1769 uint8_t *registers;
1770 int reg_size;
1772 if (!gdb_ctx->num_params) {
1773 return;
1776 cpu_synchronize_state(gdb_ctx->s->g_cpu);
1777 registers = gdb_ctx->mem_buf;
1778 len = strlen(gdb_ctx->params[0].data) / 2;
1779 hextomem(registers, gdb_ctx->params[0].data, len);
1780 for (addr = 0; addr < gdb_ctx->s->g_cpu->gdb_num_g_regs && len > 0;
1781 addr++) {
1782 reg_size = gdb_write_register(gdb_ctx->s->g_cpu, registers, addr);
1783 len -= reg_size;
1784 registers += reg_size;
1786 put_packet(gdb_ctx->s, "OK");
1789 static void handle_read_all_regs(GdbCmdContext *gdb_ctx, void *user_ctx)
1791 target_ulong addr, len;
1793 cpu_synchronize_state(gdb_ctx->s->g_cpu);
1794 len = 0;
1795 for (addr = 0; addr < gdb_ctx->s->g_cpu->gdb_num_g_regs; addr++) {
1796 len += gdb_read_register(gdb_ctx->s->g_cpu, gdb_ctx->mem_buf + len,
1797 addr);
1800 memtohex(gdb_ctx->str_buf, gdb_ctx->mem_buf, len);
1801 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
1804 static void handle_file_io(GdbCmdContext *gdb_ctx, void *user_ctx)
1806 if (gdb_ctx->num_params >= 2 && gdb_ctx->s->current_syscall_cb) {
1807 target_ulong ret, err;
1809 ret = (target_ulong)gdb_ctx->params[0].val_ull;
1810 err = (target_ulong)gdb_ctx->params[1].val_ull;
1811 gdb_ctx->s->current_syscall_cb(gdb_ctx->s->c_cpu, ret, err);
1812 gdb_ctx->s->current_syscall_cb = NULL;
1815 if (gdb_ctx->num_params >= 3 && gdb_ctx->params[2].opcode == (uint8_t)'C') {
1816 put_packet(gdb_ctx->s, "T02");
1817 return;
1820 gdb_continue(gdb_ctx->s);
1823 static void handle_step(GdbCmdContext *gdb_ctx, void *user_ctx)
1825 if (gdb_ctx->num_params) {
1826 gdb_set_cpu_pc(gdb_ctx->s, (target_ulong)gdb_ctx->params[0].val_ull);
1829 cpu_single_step(gdb_ctx->s->c_cpu, sstep_flags);
1830 gdb_continue(gdb_ctx->s);
1833 static void handle_v_cont_query(GdbCmdContext *gdb_ctx, void *user_ctx)
1835 put_packet(gdb_ctx->s, "vCont;c;C;s;S");
1838 static void handle_v_cont(GdbCmdContext *gdb_ctx, void *user_ctx)
1840 int res;
1842 if (!gdb_ctx->num_params) {
1843 return;
1846 res = gdb_handle_vcont(gdb_ctx->s, gdb_ctx->params[0].data);
1847 if ((res == -EINVAL) || (res == -ERANGE)) {
1848 put_packet(gdb_ctx->s, "E22");
1849 } else if (res) {
1850 put_packet(gdb_ctx->s, "");
1854 static void handle_v_attach(GdbCmdContext *gdb_ctx, void *user_ctx)
1856 GDBProcess *process;
1857 CPUState *cpu;
1858 char thread_id[16];
1860 pstrcpy(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "E22");
1861 if (!gdb_ctx->num_params) {
1862 goto cleanup;
1865 process = gdb_get_process(gdb_ctx->s, gdb_ctx->params[0].val_ul);
1866 if (!process) {
1867 goto cleanup;
1870 cpu = get_first_cpu_in_process(gdb_ctx->s, process);
1871 if (!cpu) {
1872 goto cleanup;
1875 process->attached = true;
1876 gdb_ctx->s->g_cpu = cpu;
1877 gdb_ctx->s->c_cpu = cpu;
1879 gdb_fmt_thread_id(gdb_ctx->s, cpu, thread_id, sizeof(thread_id));
1880 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "T%02xthread:%s;",
1881 GDB_SIGNAL_TRAP, thread_id);
1882 cleanup:
1883 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
1886 static void handle_v_kill(GdbCmdContext *gdb_ctx, void *user_ctx)
1888 /* Kill the target */
1889 put_packet(gdb_ctx->s, "OK");
1890 error_report("QEMU: Terminated via GDBstub");
1891 exit(0);
1894 static GdbCmdParseEntry gdb_v_commands_table[] = {
1895 /* Order is important if has same prefix */
1897 .handler = handle_v_cont_query,
1898 .cmd = "Cont?",
1899 .cmd_startswith = 1
1902 .handler = handle_v_cont,
1903 .cmd = "Cont",
1904 .cmd_startswith = 1,
1905 .schema = "s0"
1908 .handler = handle_v_attach,
1909 .cmd = "Attach;",
1910 .cmd_startswith = 1,
1911 .schema = "l0"
1914 .handler = handle_v_kill,
1915 .cmd = "Kill;",
1916 .cmd_startswith = 1
1920 static void handle_v_commands(GdbCmdContext *gdb_ctx, void *user_ctx)
1922 if (!gdb_ctx->num_params) {
1923 return;
1926 if (process_string_cmd(gdb_ctx->s, NULL, gdb_ctx->params[0].data,
1927 gdb_v_commands_table,
1928 ARRAY_SIZE(gdb_v_commands_table))) {
1929 put_packet(gdb_ctx->s, "");
1933 static void handle_query_qemu_sstepbits(GdbCmdContext *gdb_ctx, void *user_ctx)
1935 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf),
1936 "ENABLE=%x,NOIRQ=%x,NOTIMER=%x", SSTEP_ENABLE,
1937 SSTEP_NOIRQ, SSTEP_NOTIMER);
1938 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
1941 static void handle_set_qemu_sstep(GdbCmdContext *gdb_ctx, void *user_ctx)
1943 if (!gdb_ctx->num_params) {
1944 return;
1947 sstep_flags = gdb_ctx->params[0].val_ul;
1948 put_packet(gdb_ctx->s, "OK");
1951 static void handle_query_qemu_sstep(GdbCmdContext *gdb_ctx, void *user_ctx)
1953 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "0x%x", sstep_flags);
1954 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
1957 static void handle_query_curr_tid(GdbCmdContext *gdb_ctx, void *user_ctx)
1959 CPUState *cpu;
1960 GDBProcess *process;
1961 char thread_id[16];
1964 * "Current thread" remains vague in the spec, so always return
1965 * the first thread of the current process (gdb returns the
1966 * first thread).
1968 process = gdb_get_cpu_process(gdb_ctx->s, gdb_ctx->s->g_cpu);
1969 cpu = get_first_cpu_in_process(gdb_ctx->s, process);
1970 gdb_fmt_thread_id(gdb_ctx->s, cpu, thread_id, sizeof(thread_id));
1971 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "QC%s", thread_id);
1972 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
1975 static void handle_query_threads(GdbCmdContext *gdb_ctx, void *user_ctx)
1977 char thread_id[16];
1979 if (!gdb_ctx->s->query_cpu) {
1980 put_packet(gdb_ctx->s, "l");
1981 return;
1984 gdb_fmt_thread_id(gdb_ctx->s, gdb_ctx->s->query_cpu, thread_id,
1985 sizeof(thread_id));
1986 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "m%s", thread_id);
1987 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
1988 gdb_ctx->s->query_cpu =
1989 gdb_next_attached_cpu(gdb_ctx->s, gdb_ctx->s->query_cpu);
1992 static void handle_query_first_threads(GdbCmdContext *gdb_ctx, void *user_ctx)
1994 gdb_ctx->s->query_cpu = gdb_first_attached_cpu(gdb_ctx->s);
1995 handle_query_threads(gdb_ctx, user_ctx);
1998 static void handle_query_thread_extra(GdbCmdContext *gdb_ctx, void *user_ctx)
2000 CPUState *cpu;
2001 int len;
2003 if (!gdb_ctx->num_params ||
2004 gdb_ctx->params[0].thread_id.kind == GDB_READ_THREAD_ERR) {
2005 put_packet(gdb_ctx->s, "E22");
2006 return;
2009 cpu = gdb_get_cpu(gdb_ctx->s, gdb_ctx->params[0].thread_id.pid,
2010 gdb_ctx->params[0].thread_id.tid);
2011 if (!cpu) {
2012 return;
2015 cpu_synchronize_state(cpu);
2017 if (gdb_ctx->s->multiprocess && (gdb_ctx->s->process_num > 1)) {
2018 /* Print the CPU model and name in multiprocess mode */
2019 ObjectClass *oc = object_get_class(OBJECT(cpu));
2020 const char *cpu_model = object_class_get_name(oc);
2021 char *cpu_name = object_get_canonical_path_component(OBJECT(cpu));
2022 len = snprintf((char *)gdb_ctx->mem_buf, sizeof(gdb_ctx->str_buf) / 2,
2023 "%s %s [%s]", cpu_model, cpu_name,
2024 cpu->halted ? "halted " : "running");
2025 g_free(cpu_name);
2026 } else {
2027 /* memtohex() doubles the required space */
2028 len = snprintf((char *)gdb_ctx->mem_buf, sizeof(gdb_ctx->str_buf) / 2,
2029 "CPU#%d [%s]", cpu->cpu_index,
2030 cpu->halted ? "halted " : "running");
2032 trace_gdbstub_op_extra_info((char *)gdb_ctx->mem_buf);
2033 memtohex(gdb_ctx->str_buf, gdb_ctx->mem_buf, len);
2034 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
2037 #ifdef CONFIG_USER_ONLY
2038 static void handle_query_offsets(GdbCmdContext *gdb_ctx, void *user_ctx)
2040 TaskState *ts;
2042 ts = gdb_ctx->s->c_cpu->opaque;
2043 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf),
2044 "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
2045 ";Bss=" TARGET_ABI_FMT_lx,
2046 ts->info->code_offset,
2047 ts->info->data_offset,
2048 ts->info->data_offset);
2049 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
2051 #else
2052 static void handle_query_rcmd(GdbCmdContext *gdb_ctx, void *user_ctx)
2054 int len;
2056 if (!gdb_ctx->num_params) {
2057 put_packet(gdb_ctx->s, "E22");
2058 return;
2061 len = strlen(gdb_ctx->params[0].data);
2062 if (len % 2) {
2063 put_packet(gdb_ctx->s, "E01");
2064 return;
2067 len = len / 2;
2068 hextomem(gdb_ctx->mem_buf, gdb_ctx->params[0].data, len);
2069 gdb_ctx->mem_buf[len++] = 0;
2070 qemu_chr_be_write(gdb_ctx->s->mon_chr, gdb_ctx->mem_buf, len);
2071 put_packet(gdb_ctx->s, "OK");
2074 #endif
2076 static void handle_query_supported(GdbCmdContext *gdb_ctx, void *user_ctx)
2078 CPUClass *cc;
2080 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "PacketSize=%x",
2081 MAX_PACKET_LENGTH);
2082 cc = CPU_GET_CLASS(first_cpu);
2083 if (cc->gdb_core_xml_file) {
2084 pstrcat(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf),
2085 ";qXfer:features:read+");
2088 if (gdb_ctx->num_params &&
2089 strstr(gdb_ctx->params[0].data, "multiprocess+")) {
2090 gdb_ctx->s->multiprocess = true;
2093 pstrcat(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), ";multiprocess+");
2094 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
2097 static void handle_query_xfer_features(GdbCmdContext *gdb_ctx, void *user_ctx)
2099 GDBProcess *process;
2100 CPUClass *cc;
2101 unsigned long len, total_len, addr;
2102 const char *xml;
2103 const char *p;
2105 if (gdb_ctx->num_params < 3) {
2106 put_packet(gdb_ctx->s, "E22");
2107 return;
2110 process = gdb_get_cpu_process(gdb_ctx->s, gdb_ctx->s->g_cpu);
2111 cc = CPU_GET_CLASS(gdb_ctx->s->g_cpu);
2112 if (!cc->gdb_core_xml_file) {
2113 put_packet(gdb_ctx->s, "");
2114 return;
2117 gdb_has_xml = true;
2118 p = gdb_ctx->params[0].data;
2119 xml = get_feature_xml(gdb_ctx->s, p, &p, process);
2120 if (!xml) {
2121 put_packet(gdb_ctx->s, "E00");
2122 return;
2125 addr = gdb_ctx->params[1].val_ul;
2126 len = gdb_ctx->params[2].val_ul;
2127 total_len = strlen(xml);
2128 if (addr > total_len) {
2129 put_packet(gdb_ctx->s, "E00");
2130 return;
2133 if (len > (MAX_PACKET_LENGTH - 5) / 2) {
2134 len = (MAX_PACKET_LENGTH - 5) / 2;
2137 if (len < total_len - addr) {
2138 gdb_ctx->str_buf[0] = 'm';
2139 len = memtox(gdb_ctx->str_buf + 1, xml + addr, len);
2140 } else {
2141 gdb_ctx->str_buf[0] = 'l';
2142 len = memtox(gdb_ctx->str_buf + 1, xml + addr, total_len - addr);
2145 put_packet_binary(gdb_ctx->s, gdb_ctx->str_buf, len + 1, true);
2148 static void handle_query_attached(GdbCmdContext *gdb_ctx, void *user_ctx)
2150 put_packet(gdb_ctx->s, GDB_ATTACHED);
2153 static void handle_query_qemu_supported(GdbCmdContext *gdb_ctx, void *user_ctx)
2155 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "sstepbits;sstep");
2156 #ifndef CONFIG_USER_ONLY
2157 pstrcat(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), ";PhyMemMode");
2158 #endif
2159 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
2162 #ifndef CONFIG_USER_ONLY
2163 static void handle_query_qemu_phy_mem_mode(GdbCmdContext *gdb_ctx,
2164 void *user_ctx)
2166 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "%d", phy_memory_mode);
2167 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
2170 static void handle_set_qemu_phy_mem_mode(GdbCmdContext *gdb_ctx, void *user_ctx)
2172 if (!gdb_ctx->num_params) {
2173 put_packet(gdb_ctx->s, "E22");
2174 return;
2177 if (!gdb_ctx->params[0].val_ul) {
2178 phy_memory_mode = 0;
2179 } else {
2180 phy_memory_mode = 1;
2182 put_packet(gdb_ctx->s, "OK");
2184 #endif
2186 static GdbCmdParseEntry gdb_gen_query_set_common_table[] = {
2187 /* Order is important if has same prefix */
2189 .handler = handle_query_qemu_sstepbits,
2190 .cmd = "qemu.sstepbits",
2193 .handler = handle_query_qemu_sstep,
2194 .cmd = "qemu.sstep",
2197 .handler = handle_set_qemu_sstep,
2198 .cmd = "qemu.sstep=",
2199 .cmd_startswith = 1,
2200 .schema = "l0"
2204 static GdbCmdParseEntry gdb_gen_query_table[] = {
2206 .handler = handle_query_curr_tid,
2207 .cmd = "C",
2210 .handler = handle_query_threads,
2211 .cmd = "sThreadInfo",
2214 .handler = handle_query_first_threads,
2215 .cmd = "fThreadInfo",
2218 .handler = handle_query_thread_extra,
2219 .cmd = "ThreadExtraInfo,",
2220 .cmd_startswith = 1,
2221 .schema = "t0"
2223 #ifdef CONFIG_USER_ONLY
2225 .handler = handle_query_offsets,
2226 .cmd = "Offsets",
2228 #else
2230 .handler = handle_query_rcmd,
2231 .cmd = "Rcmd,",
2232 .cmd_startswith = 1,
2233 .schema = "s0"
2235 #endif
2237 .handler = handle_query_supported,
2238 .cmd = "Supported:",
2239 .cmd_startswith = 1,
2240 .schema = "s0"
2243 .handler = handle_query_supported,
2244 .cmd = "Supported",
2245 .schema = "s0"
2248 .handler = handle_query_xfer_features,
2249 .cmd = "Xfer:features:read:",
2250 .cmd_startswith = 1,
2251 .schema = "s:l,l0"
2254 .handler = handle_query_attached,
2255 .cmd = "Attached:",
2256 .cmd_startswith = 1
2259 .handler = handle_query_attached,
2260 .cmd = "Attached",
2263 .handler = handle_query_qemu_supported,
2264 .cmd = "qemu.Supported",
2266 #ifndef CONFIG_USER_ONLY
2268 .handler = handle_query_qemu_phy_mem_mode,
2269 .cmd = "qemu.PhyMemMode",
2271 #endif
2274 static GdbCmdParseEntry gdb_gen_set_table[] = {
2275 /* Order is important if has same prefix */
2277 .handler = handle_set_qemu_sstep,
2278 .cmd = "qemu.sstep:",
2279 .cmd_startswith = 1,
2280 .schema = "l0"
2282 #ifndef CONFIG_USER_ONLY
2284 .handler = handle_set_qemu_phy_mem_mode,
2285 .cmd = "qemu.PhyMemMode:",
2286 .cmd_startswith = 1,
2287 .schema = "l0"
2289 #endif
2292 static void handle_gen_query(GdbCmdContext *gdb_ctx, void *user_ctx)
2294 if (!gdb_ctx->num_params) {
2295 return;
2298 if (!process_string_cmd(gdb_ctx->s, NULL, gdb_ctx->params[0].data,
2299 gdb_gen_query_set_common_table,
2300 ARRAY_SIZE(gdb_gen_query_set_common_table))) {
2301 return;
2304 if (process_string_cmd(gdb_ctx->s, NULL, gdb_ctx->params[0].data,
2305 gdb_gen_query_table,
2306 ARRAY_SIZE(gdb_gen_query_table))) {
2307 put_packet(gdb_ctx->s, "");
2311 static void handle_gen_set(GdbCmdContext *gdb_ctx, void *user_ctx)
2313 if (!gdb_ctx->num_params) {
2314 return;
2317 if (!process_string_cmd(gdb_ctx->s, NULL, gdb_ctx->params[0].data,
2318 gdb_gen_query_set_common_table,
2319 ARRAY_SIZE(gdb_gen_query_set_common_table))) {
2320 return;
2323 if (process_string_cmd(gdb_ctx->s, NULL, gdb_ctx->params[0].data,
2324 gdb_gen_set_table,
2325 ARRAY_SIZE(gdb_gen_set_table))) {
2326 put_packet(gdb_ctx->s, "");
2330 static void handle_target_halt(GdbCmdContext *gdb_ctx, void *user_ctx)
2332 char thread_id[16];
2334 gdb_fmt_thread_id(gdb_ctx->s, gdb_ctx->s->c_cpu, thread_id,
2335 sizeof(thread_id));
2336 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "T%02xthread:%s;",
2337 GDB_SIGNAL_TRAP, thread_id);
2338 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
2340 * Remove all the breakpoints when this query is issued,
2341 * because gdb is doing an initial connect and the state
2342 * should be cleaned up.
2344 gdb_breakpoint_remove_all();
2347 static int gdb_handle_packet(GDBState *s, const char *line_buf)
2349 const GdbCmdParseEntry *cmd_parser = NULL;
2351 trace_gdbstub_io_command(line_buf);
2353 switch (line_buf[0]) {
2354 case '!':
2355 put_packet(s, "OK");
2356 break;
2357 case '?':
2359 static const GdbCmdParseEntry target_halted_cmd_desc = {
2360 .handler = handle_target_halt,
2361 .cmd = "?",
2362 .cmd_startswith = 1
2364 cmd_parser = &target_halted_cmd_desc;
2366 break;
2367 case 'c':
2369 static const GdbCmdParseEntry continue_cmd_desc = {
2370 .handler = handle_continue,
2371 .cmd = "c",
2372 .cmd_startswith = 1,
2373 .schema = "L0"
2375 cmd_parser = &continue_cmd_desc;
2377 break;
2378 case 'C':
2380 static const GdbCmdParseEntry cont_with_sig_cmd_desc = {
2381 .handler = handle_cont_with_sig,
2382 .cmd = "C",
2383 .cmd_startswith = 1,
2384 .schema = "l0"
2386 cmd_parser = &cont_with_sig_cmd_desc;
2388 break;
2389 case 'v':
2391 static const GdbCmdParseEntry v_cmd_desc = {
2392 .handler = handle_v_commands,
2393 .cmd = "v",
2394 .cmd_startswith = 1,
2395 .schema = "s0"
2397 cmd_parser = &v_cmd_desc;
2399 break;
2400 case 'k':
2401 /* Kill the target */
2402 error_report("QEMU: Terminated via GDBstub");
2403 exit(0);
2404 case 'D':
2406 static const GdbCmdParseEntry detach_cmd_desc = {
2407 .handler = handle_detach,
2408 .cmd = "D",
2409 .cmd_startswith = 1,
2410 .schema = "?.l0"
2412 cmd_parser = &detach_cmd_desc;
2414 break;
2415 case 's':
2417 static const GdbCmdParseEntry step_cmd_desc = {
2418 .handler = handle_step,
2419 .cmd = "s",
2420 .cmd_startswith = 1,
2421 .schema = "L0"
2423 cmd_parser = &step_cmd_desc;
2425 break;
2426 case 'F':
2428 static const GdbCmdParseEntry file_io_cmd_desc = {
2429 .handler = handle_file_io,
2430 .cmd = "F",
2431 .cmd_startswith = 1,
2432 .schema = "L,L,o0"
2434 cmd_parser = &file_io_cmd_desc;
2436 break;
2437 case 'g':
2439 static const GdbCmdParseEntry read_all_regs_cmd_desc = {
2440 .handler = handle_read_all_regs,
2441 .cmd = "g",
2442 .cmd_startswith = 1
2444 cmd_parser = &read_all_regs_cmd_desc;
2446 break;
2447 case 'G':
2449 static const GdbCmdParseEntry write_all_regs_cmd_desc = {
2450 .handler = handle_write_all_regs,
2451 .cmd = "G",
2452 .cmd_startswith = 1,
2453 .schema = "s0"
2455 cmd_parser = &write_all_regs_cmd_desc;
2457 break;
2458 case 'm':
2460 static const GdbCmdParseEntry read_mem_cmd_desc = {
2461 .handler = handle_read_mem,
2462 .cmd = "m",
2463 .cmd_startswith = 1,
2464 .schema = "L,L0"
2466 cmd_parser = &read_mem_cmd_desc;
2468 break;
2469 case 'M':
2471 static const GdbCmdParseEntry write_mem_cmd_desc = {
2472 .handler = handle_write_mem,
2473 .cmd = "M",
2474 .cmd_startswith = 1,
2475 .schema = "L,L:s0"
2477 cmd_parser = &write_mem_cmd_desc;
2479 break;
2480 case 'p':
2482 static const GdbCmdParseEntry get_reg_cmd_desc = {
2483 .handler = handle_get_reg,
2484 .cmd = "p",
2485 .cmd_startswith = 1,
2486 .schema = "L0"
2488 cmd_parser = &get_reg_cmd_desc;
2490 break;
2491 case 'P':
2493 static const GdbCmdParseEntry set_reg_cmd_desc = {
2494 .handler = handle_set_reg,
2495 .cmd = "P",
2496 .cmd_startswith = 1,
2497 .schema = "L?s0"
2499 cmd_parser = &set_reg_cmd_desc;
2501 break;
2502 case 'Z':
2504 static const GdbCmdParseEntry insert_bp_cmd_desc = {
2505 .handler = handle_insert_bp,
2506 .cmd = "Z",
2507 .cmd_startswith = 1,
2508 .schema = "l?L?L0"
2510 cmd_parser = &insert_bp_cmd_desc;
2512 break;
2513 case 'z':
2515 static const GdbCmdParseEntry remove_bp_cmd_desc = {
2516 .handler = handle_remove_bp,
2517 .cmd = "z",
2518 .cmd_startswith = 1,
2519 .schema = "l?L?L0"
2521 cmd_parser = &remove_bp_cmd_desc;
2523 break;
2524 case 'H':
2526 static const GdbCmdParseEntry set_thread_cmd_desc = {
2527 .handler = handle_set_thread,
2528 .cmd = "H",
2529 .cmd_startswith = 1,
2530 .schema = "o.t0"
2532 cmd_parser = &set_thread_cmd_desc;
2534 break;
2535 case 'T':
2537 static const GdbCmdParseEntry thread_alive_cmd_desc = {
2538 .handler = handle_thread_alive,
2539 .cmd = "T",
2540 .cmd_startswith = 1,
2541 .schema = "t0"
2543 cmd_parser = &thread_alive_cmd_desc;
2545 break;
2546 case 'q':
2548 static const GdbCmdParseEntry gen_query_cmd_desc = {
2549 .handler = handle_gen_query,
2550 .cmd = "q",
2551 .cmd_startswith = 1,
2552 .schema = "s0"
2554 cmd_parser = &gen_query_cmd_desc;
2556 break;
2557 case 'Q':
2559 static const GdbCmdParseEntry gen_set_cmd_desc = {
2560 .handler = handle_gen_set,
2561 .cmd = "Q",
2562 .cmd_startswith = 1,
2563 .schema = "s0"
2565 cmd_parser = &gen_set_cmd_desc;
2567 break;
2568 default:
2569 /* put empty packet */
2570 put_packet(s, "");
2571 break;
2574 run_cmd_parser(s, line_buf, cmd_parser);
2576 return RS_IDLE;
2579 void gdb_set_stop_cpu(CPUState *cpu)
2581 GDBProcess *p = gdb_get_cpu_process(gdbserver_state, cpu);
2583 if (!p->attached) {
2585 * Having a stop CPU corresponding to a process that is not attached
2586 * confuses GDB. So we ignore the request.
2588 return;
2591 gdbserver_state->c_cpu = cpu;
2592 gdbserver_state->g_cpu = cpu;
2595 #ifndef CONFIG_USER_ONLY
2596 static void gdb_vm_state_change(void *opaque, int running, RunState state)
2598 GDBState *s = gdbserver_state;
2599 CPUState *cpu = s->c_cpu;
2600 char buf[256];
2601 char thread_id[16];
2602 const char *type;
2603 int ret;
2605 if (running || s->state == RS_INACTIVE) {
2606 return;
2608 /* Is there a GDB syscall waiting to be sent? */
2609 if (s->current_syscall_cb) {
2610 put_packet(s, s->syscall_buf);
2611 return;
2614 if (cpu == NULL) {
2615 /* No process attached */
2616 return;
2619 gdb_fmt_thread_id(s, cpu, thread_id, sizeof(thread_id));
2621 switch (state) {
2622 case RUN_STATE_DEBUG:
2623 if (cpu->watchpoint_hit) {
2624 switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
2625 case BP_MEM_READ:
2626 type = "r";
2627 break;
2628 case BP_MEM_ACCESS:
2629 type = "a";
2630 break;
2631 default:
2632 type = "";
2633 break;
2635 trace_gdbstub_hit_watchpoint(type, cpu_gdb_index(cpu),
2636 (target_ulong)cpu->watchpoint_hit->vaddr);
2637 snprintf(buf, sizeof(buf),
2638 "T%02xthread:%s;%swatch:" TARGET_FMT_lx ";",
2639 GDB_SIGNAL_TRAP, thread_id, type,
2640 (target_ulong)cpu->watchpoint_hit->vaddr);
2641 cpu->watchpoint_hit = NULL;
2642 goto send_packet;
2643 } else {
2644 trace_gdbstub_hit_break();
2646 tb_flush(cpu);
2647 ret = GDB_SIGNAL_TRAP;
2648 break;
2649 case RUN_STATE_PAUSED:
2650 trace_gdbstub_hit_paused();
2651 ret = GDB_SIGNAL_INT;
2652 break;
2653 case RUN_STATE_SHUTDOWN:
2654 trace_gdbstub_hit_shutdown();
2655 ret = GDB_SIGNAL_QUIT;
2656 break;
2657 case RUN_STATE_IO_ERROR:
2658 trace_gdbstub_hit_io_error();
2659 ret = GDB_SIGNAL_IO;
2660 break;
2661 case RUN_STATE_WATCHDOG:
2662 trace_gdbstub_hit_watchdog();
2663 ret = GDB_SIGNAL_ALRM;
2664 break;
2665 case RUN_STATE_INTERNAL_ERROR:
2666 trace_gdbstub_hit_internal_error();
2667 ret = GDB_SIGNAL_ABRT;
2668 break;
2669 case RUN_STATE_SAVE_VM:
2670 case RUN_STATE_RESTORE_VM:
2671 return;
2672 case RUN_STATE_FINISH_MIGRATE:
2673 ret = GDB_SIGNAL_XCPU;
2674 break;
2675 default:
2676 trace_gdbstub_hit_unknown(state);
2677 ret = GDB_SIGNAL_UNKNOWN;
2678 break;
2680 gdb_set_stop_cpu(cpu);
2681 snprintf(buf, sizeof(buf), "T%02xthread:%s;", ret, thread_id);
2683 send_packet:
2684 put_packet(s, buf);
2686 /* disable single step if it was enabled */
2687 cpu_single_step(cpu, 0);
2689 #endif
2691 /* Send a gdb syscall request.
2692 This accepts limited printf-style format specifiers, specifically:
2693 %x - target_ulong argument printed in hex.
2694 %lx - 64-bit argument printed in hex.
2695 %s - string pointer (target_ulong) and length (int) pair. */
2696 void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
2698 char *p;
2699 char *p_end;
2700 target_ulong addr;
2701 uint64_t i64;
2702 GDBState *s;
2704 s = gdbserver_state;
2705 if (!s)
2706 return;
2707 s->current_syscall_cb = cb;
2708 #ifndef CONFIG_USER_ONLY
2709 vm_stop(RUN_STATE_DEBUG);
2710 #endif
2711 p = s->syscall_buf;
2712 p_end = &s->syscall_buf[sizeof(s->syscall_buf)];
2713 *(p++) = 'F';
2714 while (*fmt) {
2715 if (*fmt == '%') {
2716 fmt++;
2717 switch (*fmt++) {
2718 case 'x':
2719 addr = va_arg(va, target_ulong);
2720 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
2721 break;
2722 case 'l':
2723 if (*(fmt++) != 'x')
2724 goto bad_format;
2725 i64 = va_arg(va, uint64_t);
2726 p += snprintf(p, p_end - p, "%" PRIx64, i64);
2727 break;
2728 case 's':
2729 addr = va_arg(va, target_ulong);
2730 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
2731 addr, va_arg(va, int));
2732 break;
2733 default:
2734 bad_format:
2735 error_report("gdbstub: Bad syscall format string '%s'",
2736 fmt - 1);
2737 break;
2739 } else {
2740 *(p++) = *(fmt++);
2743 *p = 0;
2744 #ifdef CONFIG_USER_ONLY
2745 put_packet(s, s->syscall_buf);
2746 /* Return control to gdb for it to process the syscall request.
2747 * Since the protocol requires that gdb hands control back to us
2748 * using a "here are the results" F packet, we don't need to check
2749 * gdb_handlesig's return value (which is the signal to deliver if
2750 * execution was resumed via a continue packet).
2752 gdb_handlesig(s->c_cpu, 0);
2753 #else
2754 /* In this case wait to send the syscall packet until notification that
2755 the CPU has stopped. This must be done because if the packet is sent
2756 now the reply from the syscall request could be received while the CPU
2757 is still in the running state, which can cause packets to be dropped
2758 and state transition 'T' packets to be sent while the syscall is still
2759 being processed. */
2760 qemu_cpu_kick(s->c_cpu);
2761 #endif
2764 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
2766 va_list va;
2768 va_start(va, fmt);
2769 gdb_do_syscallv(cb, fmt, va);
2770 va_end(va);
2773 static void gdb_read_byte(GDBState *s, uint8_t ch)
2775 uint8_t reply;
2777 #ifndef CONFIG_USER_ONLY
2778 if (s->last_packet_len) {
2779 /* Waiting for a response to the last packet. If we see the start
2780 of a new command then abandon the previous response. */
2781 if (ch == '-') {
2782 trace_gdbstub_err_got_nack();
2783 put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
2784 } else if (ch == '+') {
2785 trace_gdbstub_io_got_ack();
2786 } else {
2787 trace_gdbstub_io_got_unexpected(ch);
2790 if (ch == '+' || ch == '$')
2791 s->last_packet_len = 0;
2792 if (ch != '$')
2793 return;
2795 if (runstate_is_running()) {
2796 /* when the CPU is running, we cannot do anything except stop
2797 it when receiving a char */
2798 vm_stop(RUN_STATE_PAUSED);
2799 } else
2800 #endif
2802 switch(s->state) {
2803 case RS_IDLE:
2804 if (ch == '$') {
2805 /* start of command packet */
2806 s->line_buf_index = 0;
2807 s->line_sum = 0;
2808 s->state = RS_GETLINE;
2809 } else {
2810 trace_gdbstub_err_garbage(ch);
2812 break;
2813 case RS_GETLINE:
2814 if (ch == '}') {
2815 /* start escape sequence */
2816 s->state = RS_GETLINE_ESC;
2817 s->line_sum += ch;
2818 } else if (ch == '*') {
2819 /* start run length encoding sequence */
2820 s->state = RS_GETLINE_RLE;
2821 s->line_sum += ch;
2822 } else if (ch == '#') {
2823 /* end of command, start of checksum*/
2824 s->state = RS_CHKSUM1;
2825 } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
2826 trace_gdbstub_err_overrun();
2827 s->state = RS_IDLE;
2828 } else {
2829 /* unescaped command character */
2830 s->line_buf[s->line_buf_index++] = ch;
2831 s->line_sum += ch;
2833 break;
2834 case RS_GETLINE_ESC:
2835 if (ch == '#') {
2836 /* unexpected end of command in escape sequence */
2837 s->state = RS_CHKSUM1;
2838 } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
2839 /* command buffer overrun */
2840 trace_gdbstub_err_overrun();
2841 s->state = RS_IDLE;
2842 } else {
2843 /* parse escaped character and leave escape state */
2844 s->line_buf[s->line_buf_index++] = ch ^ 0x20;
2845 s->line_sum += ch;
2846 s->state = RS_GETLINE;
2848 break;
2849 case RS_GETLINE_RLE:
2851 * Run-length encoding is explained in "Debugging with GDB /
2852 * Appendix E GDB Remote Serial Protocol / Overview".
2854 if (ch < ' ' || ch == '#' || ch == '$' || ch > 126) {
2855 /* invalid RLE count encoding */
2856 trace_gdbstub_err_invalid_repeat(ch);
2857 s->state = RS_GETLINE;
2858 } else {
2859 /* decode repeat length */
2860 int repeat = ch - ' ' + 3;
2861 if (s->line_buf_index + repeat >= sizeof(s->line_buf) - 1) {
2862 /* that many repeats would overrun the command buffer */
2863 trace_gdbstub_err_overrun();
2864 s->state = RS_IDLE;
2865 } else if (s->line_buf_index < 1) {
2866 /* got a repeat but we have nothing to repeat */
2867 trace_gdbstub_err_invalid_rle();
2868 s->state = RS_GETLINE;
2869 } else {
2870 /* repeat the last character */
2871 memset(s->line_buf + s->line_buf_index,
2872 s->line_buf[s->line_buf_index - 1], repeat);
2873 s->line_buf_index += repeat;
2874 s->line_sum += ch;
2875 s->state = RS_GETLINE;
2878 break;
2879 case RS_CHKSUM1:
2880 /* get high hex digit of checksum */
2881 if (!isxdigit(ch)) {
2882 trace_gdbstub_err_checksum_invalid(ch);
2883 s->state = RS_GETLINE;
2884 break;
2886 s->line_buf[s->line_buf_index] = '\0';
2887 s->line_csum = fromhex(ch) << 4;
2888 s->state = RS_CHKSUM2;
2889 break;
2890 case RS_CHKSUM2:
2891 /* get low hex digit of checksum */
2892 if (!isxdigit(ch)) {
2893 trace_gdbstub_err_checksum_invalid(ch);
2894 s->state = RS_GETLINE;
2895 break;
2897 s->line_csum |= fromhex(ch);
2899 if (s->line_csum != (s->line_sum & 0xff)) {
2900 trace_gdbstub_err_checksum_incorrect(s->line_sum, s->line_csum);
2901 /* send NAK reply */
2902 reply = '-';
2903 put_buffer(s, &reply, 1);
2904 s->state = RS_IDLE;
2905 } else {
2906 /* send ACK reply */
2907 reply = '+';
2908 put_buffer(s, &reply, 1);
2909 s->state = gdb_handle_packet(s, s->line_buf);
2911 break;
2912 default:
2913 abort();
2918 /* Tell the remote gdb that the process has exited. */
2919 void gdb_exit(CPUArchState *env, int code)
2921 GDBState *s;
2922 char buf[4];
2924 s = gdbserver_state;
2925 if (!s) {
2926 return;
2928 #ifdef CONFIG_USER_ONLY
2929 if (gdbserver_fd < 0 || s->fd < 0) {
2930 return;
2932 #endif
2934 trace_gdbstub_op_exiting((uint8_t)code);
2936 snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
2937 put_packet(s, buf);
2939 #ifndef CONFIG_USER_ONLY
2940 qemu_chr_fe_deinit(&s->chr, true);
2941 #endif
2945 * Create the process that will contain all the "orphan" CPUs (that are not
2946 * part of a CPU cluster). Note that if this process contains no CPUs, it won't
2947 * be attachable and thus will be invisible to the user.
2949 static void create_default_process(GDBState *s)
2951 GDBProcess *process;
2952 int max_pid = 0;
2954 if (s->process_num) {
2955 max_pid = s->processes[s->process_num - 1].pid;
2958 s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
2959 process = &s->processes[s->process_num - 1];
2961 /* We need an available PID slot for this process */
2962 assert(max_pid < UINT32_MAX);
2964 process->pid = max_pid + 1;
2965 process->attached = false;
2966 process->target_xml[0] = '\0';
2969 #ifdef CONFIG_USER_ONLY
2971 gdb_handlesig(CPUState *cpu, int sig)
2973 GDBState *s;
2974 char buf[256];
2975 int n;
2977 s = gdbserver_state;
2978 if (gdbserver_fd < 0 || s->fd < 0) {
2979 return sig;
2982 /* disable single step if it was enabled */
2983 cpu_single_step(cpu, 0);
2984 tb_flush(cpu);
2986 if (sig != 0) {
2987 snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
2988 put_packet(s, buf);
2990 /* put_packet() might have detected that the peer terminated the
2991 connection. */
2992 if (s->fd < 0) {
2993 return sig;
2996 sig = 0;
2997 s->state = RS_IDLE;
2998 s->running_state = 0;
2999 while (s->running_state == 0) {
3000 n = read(s->fd, buf, 256);
3001 if (n > 0) {
3002 int i;
3004 for (i = 0; i < n; i++) {
3005 gdb_read_byte(s, buf[i]);
3007 } else {
3008 /* XXX: Connection closed. Should probably wait for another
3009 connection before continuing. */
3010 if (n == 0) {
3011 close(s->fd);
3013 s->fd = -1;
3014 return sig;
3017 sig = s->signal;
3018 s->signal = 0;
3019 return sig;
3022 /* Tell the remote gdb that the process has exited due to SIG. */
3023 void gdb_signalled(CPUArchState *env, int sig)
3025 GDBState *s;
3026 char buf[4];
3028 s = gdbserver_state;
3029 if (gdbserver_fd < 0 || s->fd < 0) {
3030 return;
3033 snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
3034 put_packet(s, buf);
3037 static bool gdb_accept(void)
3039 GDBState *s;
3040 struct sockaddr_in sockaddr;
3041 socklen_t len;
3042 int fd;
3044 for(;;) {
3045 len = sizeof(sockaddr);
3046 fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
3047 if (fd < 0 && errno != EINTR) {
3048 perror("accept");
3049 return false;
3050 } else if (fd >= 0) {
3051 qemu_set_cloexec(fd);
3052 break;
3056 /* set short latency */
3057 if (socket_set_nodelay(fd)) {
3058 perror("setsockopt");
3059 close(fd);
3060 return false;
3063 s = g_malloc0(sizeof(GDBState));
3064 create_default_process(s);
3065 s->processes[0].attached = true;
3066 s->c_cpu = gdb_first_attached_cpu(s);
3067 s->g_cpu = s->c_cpu;
3068 s->fd = fd;
3069 gdb_has_xml = false;
3071 gdbserver_state = s;
3072 return true;
3075 static int gdbserver_open(int port)
3077 struct sockaddr_in sockaddr;
3078 int fd, ret;
3080 fd = socket(PF_INET, SOCK_STREAM, 0);
3081 if (fd < 0) {
3082 perror("socket");
3083 return -1;
3085 qemu_set_cloexec(fd);
3087 socket_set_fast_reuse(fd);
3089 sockaddr.sin_family = AF_INET;
3090 sockaddr.sin_port = htons(port);
3091 sockaddr.sin_addr.s_addr = 0;
3092 ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
3093 if (ret < 0) {
3094 perror("bind");
3095 close(fd);
3096 return -1;
3098 ret = listen(fd, 1);
3099 if (ret < 0) {
3100 perror("listen");
3101 close(fd);
3102 return -1;
3104 return fd;
3107 int gdbserver_start(int port)
3109 gdbserver_fd = gdbserver_open(port);
3110 if (gdbserver_fd < 0)
3111 return -1;
3112 /* accept connections */
3113 if (!gdb_accept()) {
3114 close(gdbserver_fd);
3115 gdbserver_fd = -1;
3116 return -1;
3118 return 0;
3121 /* Disable gdb stub for child processes. */
3122 void gdbserver_fork(CPUState *cpu)
3124 GDBState *s = gdbserver_state;
3126 if (gdbserver_fd < 0 || s->fd < 0) {
3127 return;
3129 close(s->fd);
3130 s->fd = -1;
3131 cpu_breakpoint_remove_all(cpu, BP_GDB);
3132 cpu_watchpoint_remove_all(cpu, BP_GDB);
3134 #else
3135 static int gdb_chr_can_receive(void *opaque)
3137 /* We can handle an arbitrarily large amount of data.
3138 Pick the maximum packet size, which is as good as anything. */
3139 return MAX_PACKET_LENGTH;
3142 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
3144 int i;
3146 for (i = 0; i < size; i++) {
3147 gdb_read_byte(gdbserver_state, buf[i]);
3151 static void gdb_chr_event(void *opaque, int event)
3153 int i;
3154 GDBState *s = (GDBState *) opaque;
3156 switch (event) {
3157 case CHR_EVENT_OPENED:
3158 /* Start with first process attached, others detached */
3159 for (i = 0; i < s->process_num; i++) {
3160 s->processes[i].attached = !i;
3163 s->c_cpu = gdb_first_attached_cpu(s);
3164 s->g_cpu = s->c_cpu;
3166 vm_stop(RUN_STATE_PAUSED);
3167 gdb_has_xml = false;
3168 break;
3169 default:
3170 break;
3174 static void gdb_monitor_output(GDBState *s, const char *msg, int len)
3176 char buf[MAX_PACKET_LENGTH];
3178 buf[0] = 'O';
3179 if (len > (MAX_PACKET_LENGTH/2) - 1)
3180 len = (MAX_PACKET_LENGTH/2) - 1;
3181 memtohex(buf + 1, (uint8_t *)msg, len);
3182 put_packet(s, buf);
3185 static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
3187 const char *p = (const char *)buf;
3188 int max_sz;
3190 max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
3191 for (;;) {
3192 if (len <= max_sz) {
3193 gdb_monitor_output(gdbserver_state, p, len);
3194 break;
3196 gdb_monitor_output(gdbserver_state, p, max_sz);
3197 p += max_sz;
3198 len -= max_sz;
3200 return len;
3203 #ifndef _WIN32
3204 static void gdb_sigterm_handler(int signal)
3206 if (runstate_is_running()) {
3207 vm_stop(RUN_STATE_PAUSED);
3210 #endif
3212 static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
3213 bool *be_opened, Error **errp)
3215 *be_opened = false;
3218 static void char_gdb_class_init(ObjectClass *oc, void *data)
3220 ChardevClass *cc = CHARDEV_CLASS(oc);
3222 cc->internal = true;
3223 cc->open = gdb_monitor_open;
3224 cc->chr_write = gdb_monitor_write;
3227 #define TYPE_CHARDEV_GDB "chardev-gdb"
3229 static const TypeInfo char_gdb_type_info = {
3230 .name = TYPE_CHARDEV_GDB,
3231 .parent = TYPE_CHARDEV,
3232 .class_init = char_gdb_class_init,
3235 static int find_cpu_clusters(Object *child, void *opaque)
3237 if (object_dynamic_cast(child, TYPE_CPU_CLUSTER)) {
3238 GDBState *s = (GDBState *) opaque;
3239 CPUClusterState *cluster = CPU_CLUSTER(child);
3240 GDBProcess *process;
3242 s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
3244 process = &s->processes[s->process_num - 1];
3247 * GDB process IDs -1 and 0 are reserved. To avoid subtle errors at
3248 * runtime, we enforce here that the machine does not use a cluster ID
3249 * that would lead to PID 0.
3251 assert(cluster->cluster_id != UINT32_MAX);
3252 process->pid = cluster->cluster_id + 1;
3253 process->attached = false;
3254 process->target_xml[0] = '\0';
3256 return 0;
3259 return object_child_foreach(child, find_cpu_clusters, opaque);
3262 static int pid_order(const void *a, const void *b)
3264 GDBProcess *pa = (GDBProcess *) a;
3265 GDBProcess *pb = (GDBProcess *) b;
3267 if (pa->pid < pb->pid) {
3268 return -1;
3269 } else if (pa->pid > pb->pid) {
3270 return 1;
3271 } else {
3272 return 0;
3276 static void create_processes(GDBState *s)
3278 object_child_foreach(object_get_root(), find_cpu_clusters, s);
3280 if (s->processes) {
3281 /* Sort by PID */
3282 qsort(s->processes, s->process_num, sizeof(s->processes[0]), pid_order);
3285 create_default_process(s);
3288 static void cleanup_processes(GDBState *s)
3290 g_free(s->processes);
3291 s->process_num = 0;
3292 s->processes = NULL;
3295 int gdbserver_start(const char *device)
3297 trace_gdbstub_op_start(device);
3299 GDBState *s;
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 s = gdbserver_state;
3338 if (!s) {
3339 s = g_malloc0(sizeof(GDBState));
3340 gdbserver_state = s;
3342 qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
3344 /* Initialize a monitor terminal for gdb */
3345 mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
3346 NULL, NULL, &error_abort);
3347 monitor_init_hmp(mon_chr, false);
3348 } else {
3349 qemu_chr_fe_deinit(&s->chr, true);
3350 mon_chr = s->mon_chr;
3351 cleanup_processes(s);
3352 memset(s, 0, sizeof(GDBState));
3353 s->mon_chr = mon_chr;
3356 create_processes(s);
3358 if (chr) {
3359 qemu_chr_fe_init(&s->chr, chr, &error_abort);
3360 qemu_chr_fe_set_handlers(&s->chr, gdb_chr_can_receive, gdb_chr_receive,
3361 gdb_chr_event, NULL, s, NULL, true);
3363 s->state = chr ? RS_IDLE : RS_INACTIVE;
3364 s->mon_chr = mon_chr;
3365 s->current_syscall_cb = NULL;
3367 return 0;
3370 void gdbserver_cleanup(void)
3372 if (gdbserver_state) {
3373 put_packet(gdbserver_state, "W00");
3377 static void register_types(void)
3379 type_register_static(&char_gdb_type_info);
3382 type_init(register_types);
3383 #endif