gdbstub: Implement read memory (m pkt) with new infra
[qemu/ar7.git] / gdbstub.c
blob291349854a8c61a33273084235335ebccc354476
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 static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
54 uint8_t *buf, int len, bool is_write)
56 CPUClass *cc = CPU_GET_CLASS(cpu);
58 if (cc->memory_rw_debug) {
59 return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
61 return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
64 /* Return the GDB index for a given vCPU state.
66 * For user mode this is simply the thread id. In system mode GDB
67 * numbers CPUs from 1 as 0 is reserved as an "any cpu" index.
69 static inline int cpu_gdb_index(CPUState *cpu)
71 #if defined(CONFIG_USER_ONLY)
72 TaskState *ts = (TaskState *) cpu->opaque;
73 return ts->ts_tid;
74 #else
75 return cpu->cpu_index + 1;
76 #endif
79 enum {
80 GDB_SIGNAL_0 = 0,
81 GDB_SIGNAL_INT = 2,
82 GDB_SIGNAL_QUIT = 3,
83 GDB_SIGNAL_TRAP = 5,
84 GDB_SIGNAL_ABRT = 6,
85 GDB_SIGNAL_ALRM = 14,
86 GDB_SIGNAL_IO = 23,
87 GDB_SIGNAL_XCPU = 24,
88 GDB_SIGNAL_UNKNOWN = 143
91 #ifdef CONFIG_USER_ONLY
93 /* Map target signal numbers to GDB protocol signal numbers and vice
94 * versa. For user emulation's currently supported systems, we can
95 * assume most signals are defined.
98 static int gdb_signal_table[] = {
100 TARGET_SIGHUP,
101 TARGET_SIGINT,
102 TARGET_SIGQUIT,
103 TARGET_SIGILL,
104 TARGET_SIGTRAP,
105 TARGET_SIGABRT,
106 -1, /* SIGEMT */
107 TARGET_SIGFPE,
108 TARGET_SIGKILL,
109 TARGET_SIGBUS,
110 TARGET_SIGSEGV,
111 TARGET_SIGSYS,
112 TARGET_SIGPIPE,
113 TARGET_SIGALRM,
114 TARGET_SIGTERM,
115 TARGET_SIGURG,
116 TARGET_SIGSTOP,
117 TARGET_SIGTSTP,
118 TARGET_SIGCONT,
119 TARGET_SIGCHLD,
120 TARGET_SIGTTIN,
121 TARGET_SIGTTOU,
122 TARGET_SIGIO,
123 TARGET_SIGXCPU,
124 TARGET_SIGXFSZ,
125 TARGET_SIGVTALRM,
126 TARGET_SIGPROF,
127 TARGET_SIGWINCH,
128 -1, /* SIGLOST */
129 TARGET_SIGUSR1,
130 TARGET_SIGUSR2,
131 #ifdef TARGET_SIGPWR
132 TARGET_SIGPWR,
133 #else
135 #endif
136 -1, /* SIGPOLL */
148 #ifdef __SIGRTMIN
149 __SIGRTMIN + 1,
150 __SIGRTMIN + 2,
151 __SIGRTMIN + 3,
152 __SIGRTMIN + 4,
153 __SIGRTMIN + 5,
154 __SIGRTMIN + 6,
155 __SIGRTMIN + 7,
156 __SIGRTMIN + 8,
157 __SIGRTMIN + 9,
158 __SIGRTMIN + 10,
159 __SIGRTMIN + 11,
160 __SIGRTMIN + 12,
161 __SIGRTMIN + 13,
162 __SIGRTMIN + 14,
163 __SIGRTMIN + 15,
164 __SIGRTMIN + 16,
165 __SIGRTMIN + 17,
166 __SIGRTMIN + 18,
167 __SIGRTMIN + 19,
168 __SIGRTMIN + 20,
169 __SIGRTMIN + 21,
170 __SIGRTMIN + 22,
171 __SIGRTMIN + 23,
172 __SIGRTMIN + 24,
173 __SIGRTMIN + 25,
174 __SIGRTMIN + 26,
175 __SIGRTMIN + 27,
176 __SIGRTMIN + 28,
177 __SIGRTMIN + 29,
178 __SIGRTMIN + 30,
179 __SIGRTMIN + 31,
180 -1, /* SIGCANCEL */
181 __SIGRTMIN,
182 __SIGRTMIN + 32,
183 __SIGRTMIN + 33,
184 __SIGRTMIN + 34,
185 __SIGRTMIN + 35,
186 __SIGRTMIN + 36,
187 __SIGRTMIN + 37,
188 __SIGRTMIN + 38,
189 __SIGRTMIN + 39,
190 __SIGRTMIN + 40,
191 __SIGRTMIN + 41,
192 __SIGRTMIN + 42,
193 __SIGRTMIN + 43,
194 __SIGRTMIN + 44,
195 __SIGRTMIN + 45,
196 __SIGRTMIN + 46,
197 __SIGRTMIN + 47,
198 __SIGRTMIN + 48,
199 __SIGRTMIN + 49,
200 __SIGRTMIN + 50,
201 __SIGRTMIN + 51,
202 __SIGRTMIN + 52,
203 __SIGRTMIN + 53,
204 __SIGRTMIN + 54,
205 __SIGRTMIN + 55,
206 __SIGRTMIN + 56,
207 __SIGRTMIN + 57,
208 __SIGRTMIN + 58,
209 __SIGRTMIN + 59,
210 __SIGRTMIN + 60,
211 __SIGRTMIN + 61,
212 __SIGRTMIN + 62,
213 __SIGRTMIN + 63,
214 __SIGRTMIN + 64,
215 __SIGRTMIN + 65,
216 __SIGRTMIN + 66,
217 __SIGRTMIN + 67,
218 __SIGRTMIN + 68,
219 __SIGRTMIN + 69,
220 __SIGRTMIN + 70,
221 __SIGRTMIN + 71,
222 __SIGRTMIN + 72,
223 __SIGRTMIN + 73,
224 __SIGRTMIN + 74,
225 __SIGRTMIN + 75,
226 __SIGRTMIN + 76,
227 __SIGRTMIN + 77,
228 __SIGRTMIN + 78,
229 __SIGRTMIN + 79,
230 __SIGRTMIN + 80,
231 __SIGRTMIN + 81,
232 __SIGRTMIN + 82,
233 __SIGRTMIN + 83,
234 __SIGRTMIN + 84,
235 __SIGRTMIN + 85,
236 __SIGRTMIN + 86,
237 __SIGRTMIN + 87,
238 __SIGRTMIN + 88,
239 __SIGRTMIN + 89,
240 __SIGRTMIN + 90,
241 __SIGRTMIN + 91,
242 __SIGRTMIN + 92,
243 __SIGRTMIN + 93,
244 __SIGRTMIN + 94,
245 __SIGRTMIN + 95,
246 -1, /* SIGINFO */
247 -1, /* UNKNOWN */
248 -1, /* DEFAULT */
255 #endif
257 #else
258 /* In system mode we only need SIGINT and SIGTRAP; other signals
259 are not yet supported. */
261 enum {
262 TARGET_SIGINT = 2,
263 TARGET_SIGTRAP = 5
266 static int gdb_signal_table[] = {
269 TARGET_SIGINT,
272 TARGET_SIGTRAP
274 #endif
276 #ifdef CONFIG_USER_ONLY
277 static int target_signal_to_gdb (int sig)
279 int i;
280 for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
281 if (gdb_signal_table[i] == sig)
282 return i;
283 return GDB_SIGNAL_UNKNOWN;
285 #endif
287 static int gdb_signal_to_target (int sig)
289 if (sig < ARRAY_SIZE (gdb_signal_table))
290 return gdb_signal_table[sig];
291 else
292 return -1;
295 typedef struct GDBRegisterState {
296 int base_reg;
297 int num_regs;
298 gdb_reg_cb get_reg;
299 gdb_reg_cb set_reg;
300 const char *xml;
301 struct GDBRegisterState *next;
302 } GDBRegisterState;
304 typedef struct GDBProcess {
305 uint32_t pid;
306 bool attached;
308 char target_xml[1024];
309 } GDBProcess;
311 enum RSState {
312 RS_INACTIVE,
313 RS_IDLE,
314 RS_GETLINE,
315 RS_GETLINE_ESC,
316 RS_GETLINE_RLE,
317 RS_CHKSUM1,
318 RS_CHKSUM2,
320 typedef struct GDBState {
321 CPUState *c_cpu; /* current CPU for step/continue ops */
322 CPUState *g_cpu; /* current CPU for other ops */
323 CPUState *query_cpu; /* for q{f|s}ThreadInfo */
324 enum RSState state; /* parsing state */
325 char line_buf[MAX_PACKET_LENGTH];
326 int line_buf_index;
327 int line_sum; /* running checksum */
328 int line_csum; /* checksum at the end of the packet */
329 uint8_t last_packet[MAX_PACKET_LENGTH + 4];
330 int last_packet_len;
331 int signal;
332 #ifdef CONFIG_USER_ONLY
333 int fd;
334 int running_state;
335 #else
336 CharBackend chr;
337 Chardev *mon_chr;
338 #endif
339 bool multiprocess;
340 GDBProcess *processes;
341 int process_num;
342 char syscall_buf[256];
343 gdb_syscall_complete_cb current_syscall_cb;
344 } GDBState;
346 /* By default use no IRQs and no timers while single stepping so as to
347 * make single stepping like an ICE HW step.
349 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
351 static GDBState *gdbserver_state;
353 bool gdb_has_xml;
355 #ifdef CONFIG_USER_ONLY
356 /* XXX: This is not thread safe. Do we care? */
357 static int gdbserver_fd = -1;
359 static int get_char(GDBState *s)
361 uint8_t ch;
362 int ret;
364 for(;;) {
365 ret = qemu_recv(s->fd, &ch, 1, 0);
366 if (ret < 0) {
367 if (errno == ECONNRESET)
368 s->fd = -1;
369 if (errno != EINTR)
370 return -1;
371 } else if (ret == 0) {
372 close(s->fd);
373 s->fd = -1;
374 return -1;
375 } else {
376 break;
379 return ch;
381 #endif
383 static enum {
384 GDB_SYS_UNKNOWN,
385 GDB_SYS_ENABLED,
386 GDB_SYS_DISABLED,
387 } gdb_syscall_mode;
389 /* Decide if either remote gdb syscalls or native file IO should be used. */
390 int use_gdb_syscalls(void)
392 SemihostingTarget target = semihosting_get_target();
393 if (target == SEMIHOSTING_TARGET_NATIVE) {
394 /* -semihosting-config target=native */
395 return false;
396 } else if (target == SEMIHOSTING_TARGET_GDB) {
397 /* -semihosting-config target=gdb */
398 return true;
401 /* -semihosting-config target=auto */
402 /* On the first call check if gdb is connected and remember. */
403 if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
404 gdb_syscall_mode = (gdbserver_state ? GDB_SYS_ENABLED
405 : GDB_SYS_DISABLED);
407 return gdb_syscall_mode == GDB_SYS_ENABLED;
410 /* Resume execution. */
411 static inline void gdb_continue(GDBState *s)
414 #ifdef CONFIG_USER_ONLY
415 s->running_state = 1;
416 trace_gdbstub_op_continue();
417 #else
418 if (!runstate_needs_reset()) {
419 trace_gdbstub_op_continue();
420 vm_start();
422 #endif
426 * Resume execution, per CPU actions. For user-mode emulation it's
427 * equivalent to gdb_continue.
429 static int gdb_continue_partial(GDBState *s, char *newstates)
431 CPUState *cpu;
432 int res = 0;
433 #ifdef CONFIG_USER_ONLY
435 * This is not exactly accurate, but it's an improvement compared to the
436 * previous situation, where only one CPU would be single-stepped.
438 CPU_FOREACH(cpu) {
439 if (newstates[cpu->cpu_index] == 's') {
440 trace_gdbstub_op_stepping(cpu->cpu_index);
441 cpu_single_step(cpu, sstep_flags);
444 s->running_state = 1;
445 #else
446 int flag = 0;
448 if (!runstate_needs_reset()) {
449 if (vm_prepare_start()) {
450 return 0;
453 CPU_FOREACH(cpu) {
454 switch (newstates[cpu->cpu_index]) {
455 case 0:
456 case 1:
457 break; /* nothing to do here */
458 case 's':
459 trace_gdbstub_op_stepping(cpu->cpu_index);
460 cpu_single_step(cpu, sstep_flags);
461 cpu_resume(cpu);
462 flag = 1;
463 break;
464 case 'c':
465 trace_gdbstub_op_continue_cpu(cpu->cpu_index);
466 cpu_resume(cpu);
467 flag = 1;
468 break;
469 default:
470 res = -1;
471 break;
475 if (flag) {
476 qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
478 #endif
479 return res;
482 static void put_buffer(GDBState *s, const uint8_t *buf, int len)
484 #ifdef CONFIG_USER_ONLY
485 int ret;
487 while (len > 0) {
488 ret = send(s->fd, buf, len, 0);
489 if (ret < 0) {
490 if (errno != EINTR)
491 return;
492 } else {
493 buf += ret;
494 len -= ret;
497 #else
498 /* XXX this blocks entire thread. Rewrite to use
499 * qemu_chr_fe_write and background I/O callbacks */
500 qemu_chr_fe_write_all(&s->chr, buf, len);
501 #endif
504 static inline int fromhex(int v)
506 if (v >= '0' && v <= '9')
507 return v - '0';
508 else if (v >= 'A' && v <= 'F')
509 return v - 'A' + 10;
510 else if (v >= 'a' && v <= 'f')
511 return v - 'a' + 10;
512 else
513 return 0;
516 static inline int tohex(int v)
518 if (v < 10)
519 return v + '0';
520 else
521 return v - 10 + 'a';
524 /* writes 2*len+1 bytes in buf */
525 static void memtohex(char *buf, const uint8_t *mem, int len)
527 int i, c;
528 char *q;
529 q = buf;
530 for(i = 0; i < len; i++) {
531 c = mem[i];
532 *q++ = tohex(c >> 4);
533 *q++ = tohex(c & 0xf);
535 *q = '\0';
538 static void hextomem(uint8_t *mem, const char *buf, int len)
540 int i;
542 for(i = 0; i < len; i++) {
543 mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
544 buf += 2;
548 static void hexdump(const char *buf, int len,
549 void (*trace_fn)(size_t ofs, char const *text))
551 char line_buffer[3 * 16 + 4 + 16 + 1];
553 size_t i;
554 for (i = 0; i < len || (i & 0xF); ++i) {
555 size_t byte_ofs = i & 15;
557 if (byte_ofs == 0) {
558 memset(line_buffer, ' ', 3 * 16 + 4 + 16);
559 line_buffer[3 * 16 + 4 + 16] = 0;
562 size_t col_group = (i >> 2) & 3;
563 size_t hex_col = byte_ofs * 3 + col_group;
564 size_t txt_col = 3 * 16 + 4 + byte_ofs;
566 if (i < len) {
567 char value = buf[i];
569 line_buffer[hex_col + 0] = tohex((value >> 4) & 0xF);
570 line_buffer[hex_col + 1] = tohex((value >> 0) & 0xF);
571 line_buffer[txt_col + 0] = (value >= ' ' && value < 127)
572 ? value
573 : '.';
576 if (byte_ofs == 0xF)
577 trace_fn(i & -16, line_buffer);
581 /* return -1 if error, 0 if OK */
582 static int put_packet_binary(GDBState *s, const char *buf, int len, bool dump)
584 int csum, i;
585 uint8_t *p;
587 if (dump && trace_event_get_state_backends(TRACE_GDBSTUB_IO_BINARYREPLY)) {
588 hexdump(buf, len, trace_gdbstub_io_binaryreply);
591 for(;;) {
592 p = s->last_packet;
593 *(p++) = '$';
594 memcpy(p, buf, len);
595 p += len;
596 csum = 0;
597 for(i = 0; i < len; i++) {
598 csum += buf[i];
600 *(p++) = '#';
601 *(p++) = tohex((csum >> 4) & 0xf);
602 *(p++) = tohex((csum) & 0xf);
604 s->last_packet_len = p - s->last_packet;
605 put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
607 #ifdef CONFIG_USER_ONLY
608 i = get_char(s);
609 if (i < 0)
610 return -1;
611 if (i == '+')
612 break;
613 #else
614 break;
615 #endif
617 return 0;
620 /* return -1 if error, 0 if OK */
621 static int put_packet(GDBState *s, const char *buf)
623 trace_gdbstub_io_reply(buf);
625 return put_packet_binary(s, buf, strlen(buf), false);
628 /* Encode data using the encoding for 'x' packets. */
629 static int memtox(char *buf, const char *mem, int len)
631 char *p = buf;
632 char c;
634 while (len--) {
635 c = *(mem++);
636 switch (c) {
637 case '#': case '$': case '*': case '}':
638 *(p++) = '}';
639 *(p++) = c ^ 0x20;
640 break;
641 default:
642 *(p++) = c;
643 break;
646 return p - buf;
649 static uint32_t gdb_get_cpu_pid(const GDBState *s, CPUState *cpu)
651 /* TODO: In user mode, we should use the task state PID */
652 if (cpu->cluster_index == UNASSIGNED_CLUSTER_INDEX) {
653 /* Return the default process' PID */
654 return s->processes[s->process_num - 1].pid;
656 return cpu->cluster_index + 1;
659 static GDBProcess *gdb_get_process(const GDBState *s, uint32_t pid)
661 int i;
663 if (!pid) {
664 /* 0 means any process, we take the first one */
665 return &s->processes[0];
668 for (i = 0; i < s->process_num; i++) {
669 if (s->processes[i].pid == pid) {
670 return &s->processes[i];
674 return NULL;
677 static GDBProcess *gdb_get_cpu_process(const GDBState *s, CPUState *cpu)
679 return gdb_get_process(s, gdb_get_cpu_pid(s, cpu));
682 static CPUState *find_cpu(uint32_t thread_id)
684 CPUState *cpu;
686 CPU_FOREACH(cpu) {
687 if (cpu_gdb_index(cpu) == thread_id) {
688 return cpu;
692 return NULL;
695 static CPUState *get_first_cpu_in_process(const GDBState *s,
696 GDBProcess *process)
698 CPUState *cpu;
700 CPU_FOREACH(cpu) {
701 if (gdb_get_cpu_pid(s, cpu) == process->pid) {
702 return cpu;
706 return NULL;
709 static CPUState *gdb_next_cpu_in_process(const GDBState *s, CPUState *cpu)
711 uint32_t pid = gdb_get_cpu_pid(s, cpu);
712 cpu = CPU_NEXT(cpu);
714 while (cpu) {
715 if (gdb_get_cpu_pid(s, cpu) == pid) {
716 break;
719 cpu = CPU_NEXT(cpu);
722 return cpu;
725 /* Return the cpu following @cpu, while ignoring unattached processes. */
726 static CPUState *gdb_next_attached_cpu(const GDBState *s, CPUState *cpu)
728 cpu = CPU_NEXT(cpu);
730 while (cpu) {
731 if (gdb_get_cpu_process(s, cpu)->attached) {
732 break;
735 cpu = CPU_NEXT(cpu);
738 return cpu;
741 /* Return the first attached cpu */
742 static CPUState *gdb_first_attached_cpu(const GDBState *s)
744 CPUState *cpu = first_cpu;
745 GDBProcess *process = gdb_get_cpu_process(s, cpu);
747 if (!process->attached) {
748 return gdb_next_attached_cpu(s, cpu);
751 return cpu;
754 static CPUState *gdb_get_cpu(const GDBState *s, uint32_t pid, uint32_t tid)
756 GDBProcess *process;
757 CPUState *cpu;
759 if (!pid && !tid) {
760 /* 0 means any process/thread, we take the first attached one */
761 return gdb_first_attached_cpu(s);
762 } else if (pid && !tid) {
763 /* any thread in a specific process */
764 process = gdb_get_process(s, pid);
766 if (process == NULL) {
767 return NULL;
770 if (!process->attached) {
771 return NULL;
774 return get_first_cpu_in_process(s, process);
775 } else {
776 /* a specific thread */
777 cpu = find_cpu(tid);
779 if (cpu == NULL) {
780 return NULL;
783 process = gdb_get_cpu_process(s, cpu);
785 if (pid && process->pid != pid) {
786 return NULL;
789 if (!process->attached) {
790 return NULL;
793 return cpu;
797 static const char *get_feature_xml(const GDBState *s, const char *p,
798 const char **newp, GDBProcess *process)
800 size_t len;
801 int i;
802 const char *name;
803 CPUState *cpu = get_first_cpu_in_process(s, process);
804 CPUClass *cc = CPU_GET_CLASS(cpu);
806 len = 0;
807 while (p[len] && p[len] != ':')
808 len++;
809 *newp = p + len;
811 name = NULL;
812 if (strncmp(p, "target.xml", len) == 0) {
813 char *buf = process->target_xml;
814 const size_t buf_sz = sizeof(process->target_xml);
816 /* Generate the XML description for this CPU. */
817 if (!buf[0]) {
818 GDBRegisterState *r;
820 pstrcat(buf, buf_sz,
821 "<?xml version=\"1.0\"?>"
822 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
823 "<target>");
824 if (cc->gdb_arch_name) {
825 gchar *arch = cc->gdb_arch_name(cpu);
826 pstrcat(buf, buf_sz, "<architecture>");
827 pstrcat(buf, buf_sz, arch);
828 pstrcat(buf, buf_sz, "</architecture>");
829 g_free(arch);
831 pstrcat(buf, buf_sz, "<xi:include href=\"");
832 pstrcat(buf, buf_sz, cc->gdb_core_xml_file);
833 pstrcat(buf, buf_sz, "\"/>");
834 for (r = cpu->gdb_regs; r; r = r->next) {
835 pstrcat(buf, buf_sz, "<xi:include href=\"");
836 pstrcat(buf, buf_sz, r->xml);
837 pstrcat(buf, buf_sz, "\"/>");
839 pstrcat(buf, buf_sz, "</target>");
841 return buf;
843 if (cc->gdb_get_dynamic_xml) {
844 char *xmlname = g_strndup(p, len);
845 const char *xml = cc->gdb_get_dynamic_xml(cpu, xmlname);
847 g_free(xmlname);
848 if (xml) {
849 return xml;
852 for (i = 0; ; i++) {
853 name = xml_builtin[i][0];
854 if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
855 break;
857 return name ? xml_builtin[i][1] : NULL;
860 static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
862 CPUClass *cc = CPU_GET_CLASS(cpu);
863 CPUArchState *env = cpu->env_ptr;
864 GDBRegisterState *r;
866 if (reg < cc->gdb_num_core_regs) {
867 return cc->gdb_read_register(cpu, mem_buf, reg);
870 for (r = cpu->gdb_regs; r; r = r->next) {
871 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
872 return r->get_reg(env, mem_buf, reg - r->base_reg);
875 return 0;
878 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
880 CPUClass *cc = CPU_GET_CLASS(cpu);
881 CPUArchState *env = cpu->env_ptr;
882 GDBRegisterState *r;
884 if (reg < cc->gdb_num_core_regs) {
885 return cc->gdb_write_register(cpu, mem_buf, reg);
888 for (r = cpu->gdb_regs; r; r = r->next) {
889 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
890 return r->set_reg(env, mem_buf, reg - r->base_reg);
893 return 0;
896 /* Register a supplemental set of CPU registers. If g_pos is nonzero it
897 specifies the first register number and these registers are included in
898 a standard "g" packet. Direction is relative to gdb, i.e. get_reg is
899 gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
902 void gdb_register_coprocessor(CPUState *cpu,
903 gdb_reg_cb get_reg, gdb_reg_cb set_reg,
904 int num_regs, const char *xml, int g_pos)
906 GDBRegisterState *s;
907 GDBRegisterState **p;
909 p = &cpu->gdb_regs;
910 while (*p) {
911 /* Check for duplicates. */
912 if (strcmp((*p)->xml, xml) == 0)
913 return;
914 p = &(*p)->next;
917 s = g_new0(GDBRegisterState, 1);
918 s->base_reg = cpu->gdb_num_regs;
919 s->num_regs = num_regs;
920 s->get_reg = get_reg;
921 s->set_reg = set_reg;
922 s->xml = xml;
924 /* Add to end of list. */
925 cpu->gdb_num_regs += num_regs;
926 *p = s;
927 if (g_pos) {
928 if (g_pos != s->base_reg) {
929 error_report("Error: Bad gdb register numbering for '%s', "
930 "expected %d got %d", xml, g_pos, s->base_reg);
931 } else {
932 cpu->gdb_num_g_regs = cpu->gdb_num_regs;
937 #ifndef CONFIG_USER_ONLY
938 /* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
939 static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
941 static const int xlat[] = {
942 [GDB_WATCHPOINT_WRITE] = BP_GDB | BP_MEM_WRITE,
943 [GDB_WATCHPOINT_READ] = BP_GDB | BP_MEM_READ,
944 [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
947 CPUClass *cc = CPU_GET_CLASS(cpu);
948 int cputype = xlat[gdbtype];
950 if (cc->gdb_stop_before_watchpoint) {
951 cputype |= BP_STOP_BEFORE_ACCESS;
953 return cputype;
955 #endif
957 static int gdb_breakpoint_insert(int type, target_ulong addr, target_ulong len)
959 CPUState *cpu;
960 int err = 0;
962 if (kvm_enabled()) {
963 return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
966 switch (type) {
967 case GDB_BREAKPOINT_SW:
968 case GDB_BREAKPOINT_HW:
969 CPU_FOREACH(cpu) {
970 err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
971 if (err) {
972 break;
975 return err;
976 #ifndef CONFIG_USER_ONLY
977 case GDB_WATCHPOINT_WRITE:
978 case GDB_WATCHPOINT_READ:
979 case GDB_WATCHPOINT_ACCESS:
980 CPU_FOREACH(cpu) {
981 err = cpu_watchpoint_insert(cpu, addr, len,
982 xlat_gdb_type(cpu, type), NULL);
983 if (err) {
984 break;
987 return err;
988 #endif
989 default:
990 return -ENOSYS;
994 static int gdb_breakpoint_remove(int type, target_ulong addr, target_ulong len)
996 CPUState *cpu;
997 int err = 0;
999 if (kvm_enabled()) {
1000 return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
1003 switch (type) {
1004 case GDB_BREAKPOINT_SW:
1005 case GDB_BREAKPOINT_HW:
1006 CPU_FOREACH(cpu) {
1007 err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
1008 if (err) {
1009 break;
1012 return err;
1013 #ifndef CONFIG_USER_ONLY
1014 case GDB_WATCHPOINT_WRITE:
1015 case GDB_WATCHPOINT_READ:
1016 case GDB_WATCHPOINT_ACCESS:
1017 CPU_FOREACH(cpu) {
1018 err = cpu_watchpoint_remove(cpu, addr, len,
1019 xlat_gdb_type(cpu, type));
1020 if (err)
1021 break;
1023 return err;
1024 #endif
1025 default:
1026 return -ENOSYS;
1030 static inline void gdb_cpu_breakpoint_remove_all(CPUState *cpu)
1032 cpu_breakpoint_remove_all(cpu, BP_GDB);
1033 #ifndef CONFIG_USER_ONLY
1034 cpu_watchpoint_remove_all(cpu, BP_GDB);
1035 #endif
1038 static void gdb_process_breakpoint_remove_all(const GDBState *s, GDBProcess *p)
1040 CPUState *cpu = get_first_cpu_in_process(s, p);
1042 while (cpu) {
1043 gdb_cpu_breakpoint_remove_all(cpu);
1044 cpu = gdb_next_cpu_in_process(s, cpu);
1048 static void gdb_breakpoint_remove_all(void)
1050 CPUState *cpu;
1052 if (kvm_enabled()) {
1053 kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
1054 return;
1057 CPU_FOREACH(cpu) {
1058 gdb_cpu_breakpoint_remove_all(cpu);
1062 static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
1064 CPUState *cpu = s->c_cpu;
1066 cpu_synchronize_state(cpu);
1067 cpu_set_pc(cpu, pc);
1070 static char *gdb_fmt_thread_id(const GDBState *s, CPUState *cpu,
1071 char *buf, size_t buf_size)
1073 if (s->multiprocess) {
1074 snprintf(buf, buf_size, "p%02x.%02x",
1075 gdb_get_cpu_pid(s, cpu), cpu_gdb_index(cpu));
1076 } else {
1077 snprintf(buf, buf_size, "%02x", cpu_gdb_index(cpu));
1080 return buf;
1083 typedef enum GDBThreadIdKind {
1084 GDB_ONE_THREAD = 0,
1085 GDB_ALL_THREADS, /* One process, all threads */
1086 GDB_ALL_PROCESSES,
1087 GDB_READ_THREAD_ERR
1088 } GDBThreadIdKind;
1090 static GDBThreadIdKind read_thread_id(const char *buf, const char **end_buf,
1091 uint32_t *pid, uint32_t *tid)
1093 unsigned long p, t;
1094 int ret;
1096 if (*buf == 'p') {
1097 buf++;
1098 ret = qemu_strtoul(buf, &buf, 16, &p);
1100 if (ret) {
1101 return GDB_READ_THREAD_ERR;
1104 /* Skip '.' */
1105 buf++;
1106 } else {
1107 p = 1;
1110 ret = qemu_strtoul(buf, &buf, 16, &t);
1112 if (ret) {
1113 return GDB_READ_THREAD_ERR;
1116 *end_buf = buf;
1118 if (p == -1) {
1119 return GDB_ALL_PROCESSES;
1122 if (pid) {
1123 *pid = p;
1126 if (t == -1) {
1127 return GDB_ALL_THREADS;
1130 if (tid) {
1131 *tid = t;
1134 return GDB_ONE_THREAD;
1137 static int is_query_packet(const char *p, const char *query, char separator)
1139 unsigned int query_len = strlen(query);
1141 return strncmp(p, query, query_len) == 0 &&
1142 (p[query_len] == '\0' || p[query_len] == separator);
1146 * gdb_handle_vcont - Parses and handles a vCont packet.
1147 * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
1148 * a format error, 0 on success.
1150 static int gdb_handle_vcont(GDBState *s, const char *p)
1152 int res, signal = 0;
1153 char cur_action;
1154 char *newstates;
1155 unsigned long tmp;
1156 uint32_t pid, tid;
1157 GDBProcess *process;
1158 CPUState *cpu;
1159 GDBThreadIdKind kind;
1160 #ifdef CONFIG_USER_ONLY
1161 int max_cpus = 1; /* global variable max_cpus exists only in system mode */
1163 CPU_FOREACH(cpu) {
1164 max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
1166 #endif
1167 /* uninitialised CPUs stay 0 */
1168 newstates = g_new0(char, max_cpus);
1170 /* mark valid CPUs with 1 */
1171 CPU_FOREACH(cpu) {
1172 newstates[cpu->cpu_index] = 1;
1176 * res keeps track of what error we are returning, with -ENOTSUP meaning
1177 * that the command is unknown or unsupported, thus returning an empty
1178 * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
1179 * or incorrect parameters passed.
1181 res = 0;
1182 while (*p) {
1183 if (*p++ != ';') {
1184 res = -ENOTSUP;
1185 goto out;
1188 cur_action = *p++;
1189 if (cur_action == 'C' || cur_action == 'S') {
1190 cur_action = qemu_tolower(cur_action);
1191 res = qemu_strtoul(p + 1, &p, 16, &tmp);
1192 if (res) {
1193 goto out;
1195 signal = gdb_signal_to_target(tmp);
1196 } else if (cur_action != 'c' && cur_action != 's') {
1197 /* unknown/invalid/unsupported command */
1198 res = -ENOTSUP;
1199 goto out;
1202 if (*p == '\0' || *p == ';') {
1204 * No thread specifier, action is on "all threads". The
1205 * specification is unclear regarding the process to act on. We
1206 * choose all processes.
1208 kind = GDB_ALL_PROCESSES;
1209 } else if (*p++ == ':') {
1210 kind = read_thread_id(p, &p, &pid, &tid);
1211 } else {
1212 res = -ENOTSUP;
1213 goto out;
1216 switch (kind) {
1217 case GDB_READ_THREAD_ERR:
1218 res = -EINVAL;
1219 goto out;
1221 case GDB_ALL_PROCESSES:
1222 cpu = gdb_first_attached_cpu(s);
1223 while (cpu) {
1224 if (newstates[cpu->cpu_index] == 1) {
1225 newstates[cpu->cpu_index] = cur_action;
1228 cpu = gdb_next_attached_cpu(s, cpu);
1230 break;
1232 case GDB_ALL_THREADS:
1233 process = gdb_get_process(s, pid);
1235 if (!process->attached) {
1236 res = -EINVAL;
1237 goto out;
1240 cpu = get_first_cpu_in_process(s, process);
1241 while (cpu) {
1242 if (newstates[cpu->cpu_index] == 1) {
1243 newstates[cpu->cpu_index] = cur_action;
1246 cpu = gdb_next_cpu_in_process(s, cpu);
1248 break;
1250 case GDB_ONE_THREAD:
1251 cpu = gdb_get_cpu(s, pid, tid);
1253 /* invalid CPU/thread specified */
1254 if (!cpu) {
1255 res = -EINVAL;
1256 goto out;
1259 /* only use if no previous match occourred */
1260 if (newstates[cpu->cpu_index] == 1) {
1261 newstates[cpu->cpu_index] = cur_action;
1263 break;
1266 s->signal = signal;
1267 gdb_continue_partial(s, newstates);
1269 out:
1270 g_free(newstates);
1272 return res;
1275 typedef union GdbCmdVariant {
1276 const char *data;
1277 uint8_t opcode;
1278 unsigned long val_ul;
1279 unsigned long long val_ull;
1280 struct {
1281 GDBThreadIdKind kind;
1282 uint32_t pid;
1283 uint32_t tid;
1284 } thread_id;
1285 } GdbCmdVariant;
1287 static const char *cmd_next_param(const char *param, const char delimiter)
1289 static const char all_delimiters[] = ",;:=";
1290 char curr_delimiters[2] = {0};
1291 const char *delimiters;
1293 if (delimiter == '?') {
1294 delimiters = all_delimiters;
1295 } else if (delimiter == '0') {
1296 return strchr(param, '\0');
1297 } else if (delimiter == '.' && *param) {
1298 return param + 1;
1299 } else {
1300 curr_delimiters[0] = delimiter;
1301 delimiters = curr_delimiters;
1304 param += strcspn(param, delimiters);
1305 if (*param) {
1306 param++;
1308 return param;
1311 static int cmd_parse_params(const char *data, const char *schema,
1312 GdbCmdVariant *params, int *num_params)
1314 int curr_param;
1315 const char *curr_schema, *curr_data;
1317 *num_params = 0;
1319 if (!schema) {
1320 return 0;
1323 curr_schema = schema;
1324 curr_param = 0;
1325 curr_data = data;
1326 while (curr_schema[0] && curr_schema[1] && *curr_data) {
1327 switch (curr_schema[0]) {
1328 case 'l':
1329 if (qemu_strtoul(curr_data, &curr_data, 16,
1330 &params[curr_param].val_ul)) {
1331 return -EINVAL;
1333 curr_param++;
1334 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1335 break;
1336 case 'L':
1337 if (qemu_strtou64(curr_data, &curr_data, 16,
1338 (uint64_t *)&params[curr_param].val_ull)) {
1339 return -EINVAL;
1341 curr_param++;
1342 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1343 break;
1344 case 's':
1345 params[curr_param].data = curr_data;
1346 curr_param++;
1347 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1348 break;
1349 case 'o':
1350 params[curr_param].opcode = *(uint8_t *)curr_data;
1351 curr_param++;
1352 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1353 break;
1354 case 't':
1355 params[curr_param].thread_id.kind =
1356 read_thread_id(curr_data, &curr_data,
1357 &params[curr_param].thread_id.pid,
1358 &params[curr_param].thread_id.tid);
1359 curr_param++;
1360 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1361 break;
1362 case '?':
1363 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1364 break;
1365 default:
1366 return -EINVAL;
1368 curr_schema += 2;
1371 *num_params = curr_param;
1372 return 0;
1375 typedef struct GdbCmdContext {
1376 GDBState *s;
1377 GdbCmdVariant *params;
1378 int num_params;
1379 uint8_t mem_buf[MAX_PACKET_LENGTH];
1380 char str_buf[MAX_PACKET_LENGTH + 1];
1381 } GdbCmdContext;
1383 typedef void (*GdbCmdHandler)(GdbCmdContext *gdb_ctx, void *user_ctx);
1386 * cmd_startswith -> cmd is compared using startswith
1389 * schema definitions:
1390 * Each schema parameter entry consists of 2 chars,
1391 * the first char represents the parameter type handling
1392 * the second char represents the delimiter for the next parameter
1394 * Currently supported schema types:
1395 * 'l' -> unsigned long (stored in .val_ul)
1396 * 'L' -> unsigned long long (stored in .val_ull)
1397 * 's' -> string (stored in .data)
1398 * 'o' -> single char (stored in .opcode)
1399 * 't' -> thread id (stored in .thread_id)
1400 * '?' -> skip according to delimiter
1402 * Currently supported delimiters:
1403 * '?' -> Stop at any delimiter (",;:=\0")
1404 * '0' -> Stop at "\0"
1405 * '.' -> Skip 1 char unless reached "\0"
1406 * Any other value is treated as the delimiter value itself
1408 typedef struct GdbCmdParseEntry {
1409 GdbCmdHandler handler;
1410 const char *cmd;
1411 bool cmd_startswith;
1412 const char *schema;
1413 } GdbCmdParseEntry;
1415 static inline int startswith(const char *string, const char *pattern)
1417 return !strncmp(string, pattern, strlen(pattern));
1420 static int process_string_cmd(GDBState *s, void *user_ctx, const char *data,
1421 const GdbCmdParseEntry *cmds, int num_cmds)
1423 int i, schema_len, max_num_params = 0;
1424 GdbCmdContext gdb_ctx;
1426 if (!cmds) {
1427 return -1;
1430 for (i = 0; i < num_cmds; i++) {
1431 const GdbCmdParseEntry *cmd = &cmds[i];
1432 g_assert(cmd->handler && cmd->cmd);
1434 if ((cmd->cmd_startswith && !startswith(data, cmd->cmd)) ||
1435 (!cmd->cmd_startswith && strcmp(cmd->cmd, data))) {
1436 continue;
1439 if (cmd->schema) {
1440 schema_len = strlen(cmd->schema);
1441 if (schema_len % 2) {
1442 return -2;
1445 max_num_params = schema_len / 2;
1448 gdb_ctx.params =
1449 (GdbCmdVariant *)alloca(sizeof(*gdb_ctx.params) * max_num_params);
1450 memset(gdb_ctx.params, 0, sizeof(*gdb_ctx.params) * max_num_params);
1452 if (cmd_parse_params(&data[strlen(cmd->cmd)], cmd->schema,
1453 gdb_ctx.params, &gdb_ctx.num_params)) {
1454 return -1;
1457 gdb_ctx.s = s;
1458 cmd->handler(&gdb_ctx, user_ctx);
1459 return 0;
1462 return -1;
1465 static void run_cmd_parser(GDBState *s, const char *data,
1466 const GdbCmdParseEntry *cmd)
1468 if (!data) {
1469 return;
1472 /* In case there was an error during the command parsing we must
1473 * send a NULL packet to indicate the command is not supported */
1474 if (process_string_cmd(s, NULL, data, cmd, 1)) {
1475 put_packet(s, "");
1479 static void handle_detach(GdbCmdContext *gdb_ctx, void *user_ctx)
1481 GDBProcess *process;
1482 GDBState *s = gdb_ctx->s;
1483 uint32_t pid = 1;
1485 if (s->multiprocess) {
1486 if (!gdb_ctx->num_params) {
1487 put_packet(s, "E22");
1488 return;
1491 pid = gdb_ctx->params[0].val_ul;
1494 process = gdb_get_process(s, pid);
1495 gdb_process_breakpoint_remove_all(s, process);
1496 process->attached = false;
1498 if (pid == gdb_get_cpu_pid(s, s->c_cpu)) {
1499 s->c_cpu = gdb_first_attached_cpu(s);
1502 if (pid == gdb_get_cpu_pid(s, s->g_cpu)) {
1503 s->g_cpu = gdb_first_attached_cpu(s);
1506 if (!s->c_cpu) {
1507 /* No more process attached */
1508 gdb_syscall_mode = GDB_SYS_DISABLED;
1509 gdb_continue(s);
1511 put_packet(s, "OK");
1514 static void handle_thread_alive(GdbCmdContext *gdb_ctx, void *user_ctx)
1516 CPUState *cpu;
1518 if (!gdb_ctx->num_params) {
1519 put_packet(gdb_ctx->s, "E22");
1520 return;
1523 if (gdb_ctx->params[0].thread_id.kind == GDB_READ_THREAD_ERR) {
1524 put_packet(gdb_ctx->s, "E22");
1525 return;
1528 cpu = gdb_get_cpu(gdb_ctx->s, gdb_ctx->params[0].thread_id.pid,
1529 gdb_ctx->params[0].thread_id.tid);
1530 if (!cpu) {
1531 put_packet(gdb_ctx->s, "E22");
1532 return;
1535 put_packet(gdb_ctx->s, "OK");
1538 static void handle_continue(GdbCmdContext *gdb_ctx, void *user_ctx)
1540 if (gdb_ctx->num_params) {
1541 gdb_set_cpu_pc(gdb_ctx->s, gdb_ctx->params[0].val_ull);
1544 gdb_ctx->s->signal = 0;
1545 gdb_continue(gdb_ctx->s);
1548 static void handle_cont_with_sig(GdbCmdContext *gdb_ctx, void *user_ctx)
1550 unsigned long signal = 0;
1553 * Note: C sig;[addr] is currently unsupported and we simply
1554 * omit the addr parameter
1556 if (gdb_ctx->num_params) {
1557 signal = gdb_ctx->params[0].val_ul;
1560 gdb_ctx->s->signal = gdb_signal_to_target(signal);
1561 if (gdb_ctx->s->signal == -1) {
1562 gdb_ctx->s->signal = 0;
1564 gdb_continue(gdb_ctx->s);
1567 static void handle_set_thread(GdbCmdContext *gdb_ctx, void *user_ctx)
1569 CPUState *cpu;
1571 if (gdb_ctx->num_params != 2) {
1572 put_packet(gdb_ctx->s, "E22");
1573 return;
1576 if (gdb_ctx->params[1].thread_id.kind == GDB_READ_THREAD_ERR) {
1577 put_packet(gdb_ctx->s, "E22");
1578 return;
1581 if (gdb_ctx->params[1].thread_id.kind != GDB_ONE_THREAD) {
1582 put_packet(gdb_ctx->s, "OK");
1583 return;
1586 cpu = gdb_get_cpu(gdb_ctx->s, gdb_ctx->params[1].thread_id.pid,
1587 gdb_ctx->params[1].thread_id.tid);
1588 if (!cpu) {
1589 put_packet(gdb_ctx->s, "E22");
1590 return;
1594 * Note: This command is deprecated and modern gdb's will be using the
1595 * vCont command instead.
1597 switch (gdb_ctx->params[0].opcode) {
1598 case 'c':
1599 gdb_ctx->s->c_cpu = cpu;
1600 put_packet(gdb_ctx->s, "OK");
1601 break;
1602 case 'g':
1603 gdb_ctx->s->g_cpu = cpu;
1604 put_packet(gdb_ctx->s, "OK");
1605 break;
1606 default:
1607 put_packet(gdb_ctx->s, "E22");
1608 break;
1612 static void handle_insert_bp(GdbCmdContext *gdb_ctx, void *user_ctx)
1614 int res;
1616 if (gdb_ctx->num_params != 3) {
1617 put_packet(gdb_ctx->s, "E22");
1618 return;
1621 res = gdb_breakpoint_insert(gdb_ctx->params[0].val_ul,
1622 gdb_ctx->params[1].val_ull,
1623 gdb_ctx->params[2].val_ull);
1624 if (res >= 0) {
1625 put_packet(gdb_ctx->s, "OK");
1626 return;
1627 } else if (res == -ENOSYS) {
1628 put_packet(gdb_ctx->s, "");
1629 return;
1632 put_packet(gdb_ctx->s, "E22");
1635 static void handle_remove_bp(GdbCmdContext *gdb_ctx, void *user_ctx)
1637 int res;
1639 if (gdb_ctx->num_params != 3) {
1640 put_packet(gdb_ctx->s, "E22");
1641 return;
1644 res = gdb_breakpoint_remove(gdb_ctx->params[0].val_ul,
1645 gdb_ctx->params[1].val_ull,
1646 gdb_ctx->params[2].val_ull);
1647 if (res >= 0) {
1648 put_packet(gdb_ctx->s, "OK");
1649 return;
1650 } else if (res == -ENOSYS) {
1651 put_packet(gdb_ctx->s, "");
1652 return;
1655 put_packet(gdb_ctx->s, "E22");
1658 static void handle_set_reg(GdbCmdContext *gdb_ctx, void *user_ctx)
1660 int reg_size;
1662 if (!gdb_has_xml) {
1663 put_packet(gdb_ctx->s, "E00");
1664 return;
1667 if (gdb_ctx->num_params != 2) {
1668 put_packet(gdb_ctx->s, "E22");
1669 return;
1672 reg_size = strlen(gdb_ctx->params[1].data) / 2;
1673 hextomem(gdb_ctx->mem_buf, gdb_ctx->params[1].data, reg_size);
1674 gdb_write_register(gdb_ctx->s->g_cpu, gdb_ctx->mem_buf,
1675 gdb_ctx->params[0].val_ull);
1676 put_packet(gdb_ctx->s, "OK");
1679 static void handle_get_reg(GdbCmdContext *gdb_ctx, void *user_ctx)
1681 int reg_size;
1684 * Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
1685 * This works, but can be very slow. Anything new enough to
1686 * understand XML also knows how to use this properly.
1688 if (!gdb_has_xml) {
1689 put_packet(gdb_ctx->s, "");
1690 return;
1693 if (!gdb_ctx->num_params) {
1694 put_packet(gdb_ctx->s, "E14");
1695 return;
1698 reg_size = gdb_read_register(gdb_ctx->s->g_cpu, gdb_ctx->mem_buf,
1699 gdb_ctx->params[0].val_ull);
1700 if (!reg_size) {
1701 put_packet(gdb_ctx->s, "E14");
1702 return;
1705 memtohex(gdb_ctx->str_buf, gdb_ctx->mem_buf, reg_size);
1706 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
1709 static void handle_write_mem(GdbCmdContext *gdb_ctx, void *user_ctx)
1711 if (gdb_ctx->num_params != 3) {
1712 put_packet(gdb_ctx->s, "E22");
1713 return;
1716 /* hextomem() reads 2*len bytes */
1717 if (gdb_ctx->params[1].val_ull > strlen(gdb_ctx->params[2].data) / 2) {
1718 put_packet(gdb_ctx->s, "E22");
1719 return;
1722 hextomem(gdb_ctx->mem_buf, gdb_ctx->params[2].data,
1723 gdb_ctx->params[1].val_ull);
1724 if (target_memory_rw_debug(gdb_ctx->s->g_cpu, gdb_ctx->params[0].val_ull,
1725 gdb_ctx->mem_buf,
1726 gdb_ctx->params[1].val_ull, true)) {
1727 put_packet(gdb_ctx->s, "E14");
1728 return;
1731 put_packet(gdb_ctx->s, "OK");
1734 static void handle_read_mem(GdbCmdContext *gdb_ctx, void *user_ctx)
1736 if (gdb_ctx->num_params != 2) {
1737 put_packet(gdb_ctx->s, "E22");
1738 return;
1741 /* memtohex() doubles the required space */
1742 if (gdb_ctx->params[1].val_ull > MAX_PACKET_LENGTH / 2) {
1743 put_packet(gdb_ctx->s, "E22");
1744 return;
1747 if (target_memory_rw_debug(gdb_ctx->s->g_cpu, gdb_ctx->params[0].val_ull,
1748 gdb_ctx->mem_buf,
1749 gdb_ctx->params[1].val_ull, false)) {
1750 put_packet(gdb_ctx->s, "E14");
1751 return;
1754 memtohex(gdb_ctx->str_buf, gdb_ctx->mem_buf, gdb_ctx->params[1].val_ull);
1755 put_packet(gdb_ctx->s, gdb_ctx->str_buf);
1758 static int gdb_handle_packet(GDBState *s, const char *line_buf)
1760 CPUState *cpu;
1761 GDBProcess *process;
1762 CPUClass *cc;
1763 const char *p;
1764 uint32_t pid, tid;
1765 int ch, reg_size, type, res;
1766 uint8_t mem_buf[MAX_PACKET_LENGTH];
1767 char buf[sizeof(mem_buf) + 1 /* trailing NUL */];
1768 char thread_id[16];
1769 uint8_t *registers;
1770 target_ulong addr, len;
1771 const GdbCmdParseEntry *cmd_parser = NULL;
1773 trace_gdbstub_io_command(line_buf);
1775 p = line_buf;
1776 ch = *p++;
1777 switch(ch) {
1778 case '!':
1779 put_packet(s, "OK");
1780 break;
1781 case '?':
1782 /* TODO: Make this return the correct value for user-mode. */
1783 snprintf(buf, sizeof(buf), "T%02xthread:%s;", GDB_SIGNAL_TRAP,
1784 gdb_fmt_thread_id(s, s->c_cpu, thread_id, sizeof(thread_id)));
1785 put_packet(s, buf);
1786 /* Remove all the breakpoints when this query is issued,
1787 * because gdb is doing and initial connect and the state
1788 * should be cleaned up.
1790 gdb_breakpoint_remove_all();
1791 break;
1792 case 'c':
1794 static const GdbCmdParseEntry continue_cmd_desc = {
1795 .handler = handle_continue,
1796 .cmd = "c",
1797 .cmd_startswith = 1,
1798 .schema = "L0"
1800 cmd_parser = &continue_cmd_desc;
1802 break;
1803 case 'C':
1805 static const GdbCmdParseEntry cont_with_sig_cmd_desc = {
1806 .handler = handle_cont_with_sig,
1807 .cmd = "C",
1808 .cmd_startswith = 1,
1809 .schema = "l0"
1811 cmd_parser = &cont_with_sig_cmd_desc;
1813 break;
1814 case 'v':
1815 if (strncmp(p, "Cont", 4) == 0) {
1816 p += 4;
1817 if (*p == '?') {
1818 put_packet(s, "vCont;c;C;s;S");
1819 break;
1822 res = gdb_handle_vcont(s, p);
1824 if (res) {
1825 if ((res == -EINVAL) || (res == -ERANGE)) {
1826 put_packet(s, "E22");
1827 break;
1829 goto unknown_command;
1831 break;
1832 } else if (strncmp(p, "Attach;", 7) == 0) {
1833 unsigned long pid;
1835 p += 7;
1837 if (qemu_strtoul(p, &p, 16, &pid)) {
1838 put_packet(s, "E22");
1839 break;
1842 process = gdb_get_process(s, pid);
1844 if (process == NULL) {
1845 put_packet(s, "E22");
1846 break;
1849 cpu = get_first_cpu_in_process(s, process);
1851 if (cpu == NULL) {
1852 /* Refuse to attach an empty process */
1853 put_packet(s, "E22");
1854 break;
1857 process->attached = true;
1859 s->g_cpu = cpu;
1860 s->c_cpu = cpu;
1862 snprintf(buf, sizeof(buf), "T%02xthread:%s;", GDB_SIGNAL_TRAP,
1863 gdb_fmt_thread_id(s, cpu, thread_id, sizeof(thread_id)));
1865 put_packet(s, buf);
1866 break;
1867 } else if (strncmp(p, "Kill;", 5) == 0) {
1868 /* Kill the target */
1869 put_packet(s, "OK");
1870 error_report("QEMU: Terminated via GDBstub");
1871 exit(0);
1872 } else {
1873 goto unknown_command;
1875 case 'k':
1876 /* Kill the target */
1877 error_report("QEMU: Terminated via GDBstub");
1878 exit(0);
1879 case 'D':
1881 static const GdbCmdParseEntry detach_cmd_desc = {
1882 .handler = handle_detach,
1883 .cmd = "D",
1884 .cmd_startswith = 1,
1885 .schema = "?.l0"
1887 cmd_parser = &detach_cmd_desc;
1889 break;
1890 case 's':
1891 if (*p != '\0') {
1892 addr = strtoull(p, (char **)&p, 16);
1893 gdb_set_cpu_pc(s, addr);
1895 cpu_single_step(s->c_cpu, sstep_flags);
1896 gdb_continue(s);
1897 return RS_IDLE;
1898 case 'F':
1900 target_ulong ret;
1901 target_ulong err;
1903 ret = strtoull(p, (char **)&p, 16);
1904 if (*p == ',') {
1905 p++;
1906 err = strtoull(p, (char **)&p, 16);
1907 } else {
1908 err = 0;
1910 if (*p == ',')
1911 p++;
1912 type = *p;
1913 if (s->current_syscall_cb) {
1914 s->current_syscall_cb(s->c_cpu, ret, err);
1915 s->current_syscall_cb = NULL;
1917 if (type == 'C') {
1918 put_packet(s, "T02");
1919 } else {
1920 gdb_continue(s);
1923 break;
1924 case 'g':
1925 cpu_synchronize_state(s->g_cpu);
1926 len = 0;
1927 for (addr = 0; addr < s->g_cpu->gdb_num_g_regs; addr++) {
1928 reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);
1929 len += reg_size;
1931 memtohex(buf, mem_buf, len);
1932 put_packet(s, buf);
1933 break;
1934 case 'G':
1935 cpu_synchronize_state(s->g_cpu);
1936 registers = mem_buf;
1937 len = strlen(p) / 2;
1938 hextomem((uint8_t *)registers, p, len);
1939 for (addr = 0; addr < s->g_cpu->gdb_num_g_regs && len > 0; addr++) {
1940 reg_size = gdb_write_register(s->g_cpu, registers, addr);
1941 len -= reg_size;
1942 registers += reg_size;
1944 put_packet(s, "OK");
1945 break;
1946 case 'm':
1948 static const GdbCmdParseEntry read_mem_cmd_desc = {
1949 .handler = handle_read_mem,
1950 .cmd = "m",
1951 .cmd_startswith = 1,
1952 .schema = "L,L0"
1954 cmd_parser = &read_mem_cmd_desc;
1956 break;
1957 case 'M':
1959 static const GdbCmdParseEntry write_mem_cmd_desc = {
1960 .handler = handle_write_mem,
1961 .cmd = "M",
1962 .cmd_startswith = 1,
1963 .schema = "L,L:s0"
1965 cmd_parser = &write_mem_cmd_desc;
1967 break;
1968 case 'p':
1970 static const GdbCmdParseEntry get_reg_cmd_desc = {
1971 .handler = handle_get_reg,
1972 .cmd = "p",
1973 .cmd_startswith = 1,
1974 .schema = "L0"
1976 cmd_parser = &get_reg_cmd_desc;
1978 break;
1979 case 'P':
1981 static const GdbCmdParseEntry set_reg_cmd_desc = {
1982 .handler = handle_set_reg,
1983 .cmd = "P",
1984 .cmd_startswith = 1,
1985 .schema = "L?s0"
1987 cmd_parser = &set_reg_cmd_desc;
1989 break;
1990 case 'Z':
1992 static const GdbCmdParseEntry insert_bp_cmd_desc = {
1993 .handler = handle_insert_bp,
1994 .cmd = "Z",
1995 .cmd_startswith = 1,
1996 .schema = "l?L?L0"
1998 cmd_parser = &insert_bp_cmd_desc;
2000 break;
2001 case 'z':
2003 static const GdbCmdParseEntry remove_bp_cmd_desc = {
2004 .handler = handle_remove_bp,
2005 .cmd = "z",
2006 .cmd_startswith = 1,
2007 .schema = "l?L?L0"
2009 cmd_parser = &remove_bp_cmd_desc;
2011 break;
2012 case 'H':
2014 static const GdbCmdParseEntry set_thread_cmd_desc = {
2015 .handler = handle_set_thread,
2016 .cmd = "H",
2017 .cmd_startswith = 1,
2018 .schema = "o.t0"
2020 cmd_parser = &set_thread_cmd_desc;
2022 break;
2023 case 'T':
2025 static const GdbCmdParseEntry thread_alive_cmd_desc = {
2026 .handler = handle_thread_alive,
2027 .cmd = "T",
2028 .cmd_startswith = 1,
2029 .schema = "t0"
2031 cmd_parser = &thread_alive_cmd_desc;
2033 break;
2034 case 'q':
2035 case 'Q':
2036 /* parse any 'q' packets here */
2037 if (!strcmp(p,"qemu.sstepbits")) {
2038 /* Query Breakpoint bit definitions */
2039 snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
2040 SSTEP_ENABLE,
2041 SSTEP_NOIRQ,
2042 SSTEP_NOTIMER);
2043 put_packet(s, buf);
2044 break;
2045 } else if (is_query_packet(p, "qemu.sstep", '=')) {
2046 /* Display or change the sstep_flags */
2047 p += 10;
2048 if (*p != '=') {
2049 /* Display current setting */
2050 snprintf(buf, sizeof(buf), "0x%x", sstep_flags);
2051 put_packet(s, buf);
2052 break;
2054 p++;
2055 type = strtoul(p, (char **)&p, 16);
2056 sstep_flags = type;
2057 put_packet(s, "OK");
2058 break;
2059 } else if (strcmp(p,"C") == 0) {
2061 * "Current thread" remains vague in the spec, so always return
2062 * the first thread of the current process (gdb returns the
2063 * first thread).
2065 cpu = get_first_cpu_in_process(s, gdb_get_cpu_process(s, s->g_cpu));
2066 snprintf(buf, sizeof(buf), "QC%s",
2067 gdb_fmt_thread_id(s, cpu, thread_id, sizeof(thread_id)));
2068 put_packet(s, buf);
2069 break;
2070 } else if (strcmp(p,"fThreadInfo") == 0) {
2071 s->query_cpu = gdb_first_attached_cpu(s);
2072 goto report_cpuinfo;
2073 } else if (strcmp(p,"sThreadInfo") == 0) {
2074 report_cpuinfo:
2075 if (s->query_cpu) {
2076 snprintf(buf, sizeof(buf), "m%s",
2077 gdb_fmt_thread_id(s, s->query_cpu,
2078 thread_id, sizeof(thread_id)));
2079 put_packet(s, buf);
2080 s->query_cpu = gdb_next_attached_cpu(s, s->query_cpu);
2081 } else
2082 put_packet(s, "l");
2083 break;
2084 } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {
2085 if (read_thread_id(p + 16, &p, &pid, &tid) == GDB_READ_THREAD_ERR) {
2086 put_packet(s, "E22");
2087 break;
2089 cpu = gdb_get_cpu(s, pid, tid);
2090 if (cpu != NULL) {
2091 cpu_synchronize_state(cpu);
2093 if (s->multiprocess && (s->process_num > 1)) {
2094 /* Print the CPU model and name in multiprocess mode */
2095 ObjectClass *oc = object_get_class(OBJECT(cpu));
2096 const char *cpu_model = object_class_get_name(oc);
2097 char *cpu_name =
2098 object_get_canonical_path_component(OBJECT(cpu));
2099 len = snprintf((char *)mem_buf, sizeof(buf) / 2,
2100 "%s %s [%s]", cpu_model, cpu_name,
2101 cpu->halted ? "halted " : "running");
2102 g_free(cpu_name);
2103 } else {
2104 /* memtohex() doubles the required space */
2105 len = snprintf((char *)mem_buf, sizeof(buf) / 2,
2106 "CPU#%d [%s]", cpu->cpu_index,
2107 cpu->halted ? "halted " : "running");
2109 trace_gdbstub_op_extra_info((char *)mem_buf);
2110 memtohex(buf, mem_buf, len);
2111 put_packet(s, buf);
2113 break;
2115 #ifdef CONFIG_USER_ONLY
2116 else if (strcmp(p, "Offsets") == 0) {
2117 TaskState *ts = s->c_cpu->opaque;
2119 snprintf(buf, sizeof(buf),
2120 "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
2121 ";Bss=" TARGET_ABI_FMT_lx,
2122 ts->info->code_offset,
2123 ts->info->data_offset,
2124 ts->info->data_offset);
2125 put_packet(s, buf);
2126 break;
2128 #else /* !CONFIG_USER_ONLY */
2129 else if (strncmp(p, "Rcmd,", 5) == 0) {
2130 int len = strlen(p + 5);
2132 if ((len % 2) != 0) {
2133 put_packet(s, "E01");
2134 break;
2136 len = len / 2;
2137 hextomem(mem_buf, p + 5, len);
2138 mem_buf[len++] = 0;
2139 qemu_chr_be_write(s->mon_chr, mem_buf, len);
2140 put_packet(s, "OK");
2141 break;
2143 #endif /* !CONFIG_USER_ONLY */
2144 if (is_query_packet(p, "Supported", ':')) {
2145 snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);
2146 cc = CPU_GET_CLASS(first_cpu);
2147 if (cc->gdb_core_xml_file != NULL) {
2148 pstrcat(buf, sizeof(buf), ";qXfer:features:read+");
2151 if (strstr(p, "multiprocess+")) {
2152 s->multiprocess = true;
2154 pstrcat(buf, sizeof(buf), ";multiprocess+");
2156 put_packet(s, buf);
2157 break;
2159 if (strncmp(p, "Xfer:features:read:", 19) == 0) {
2160 const char *xml;
2161 target_ulong total_len;
2163 process = gdb_get_cpu_process(s, s->g_cpu);
2164 cc = CPU_GET_CLASS(s->g_cpu);
2165 if (cc->gdb_core_xml_file == NULL) {
2166 goto unknown_command;
2169 gdb_has_xml = true;
2170 p += 19;
2171 xml = get_feature_xml(s, p, &p, process);
2172 if (!xml) {
2173 snprintf(buf, sizeof(buf), "E00");
2174 put_packet(s, buf);
2175 break;
2178 if (*p == ':')
2179 p++;
2180 addr = strtoul(p, (char **)&p, 16);
2181 if (*p == ',')
2182 p++;
2183 len = strtoul(p, (char **)&p, 16);
2185 total_len = strlen(xml);
2186 if (addr > total_len) {
2187 snprintf(buf, sizeof(buf), "E00");
2188 put_packet(s, buf);
2189 break;
2191 if (len > (MAX_PACKET_LENGTH - 5) / 2)
2192 len = (MAX_PACKET_LENGTH - 5) / 2;
2193 if (len < total_len - addr) {
2194 buf[0] = 'm';
2195 len = memtox(buf + 1, xml + addr, len);
2196 } else {
2197 buf[0] = 'l';
2198 len = memtox(buf + 1, xml + addr, total_len - addr);
2200 put_packet_binary(s, buf, len + 1, true);
2201 break;
2203 if (is_query_packet(p, "Attached", ':')) {
2204 put_packet(s, GDB_ATTACHED);
2205 break;
2207 /* Unrecognised 'q' command. */
2208 goto unknown_command;
2210 default:
2211 unknown_command:
2212 /* put empty packet */
2213 buf[0] = '\0';
2214 put_packet(s, buf);
2215 break;
2218 run_cmd_parser(s, line_buf, cmd_parser);
2220 return RS_IDLE;
2223 void gdb_set_stop_cpu(CPUState *cpu)
2225 GDBProcess *p = gdb_get_cpu_process(gdbserver_state, cpu);
2227 if (!p->attached) {
2229 * Having a stop CPU corresponding to a process that is not attached
2230 * confuses GDB. So we ignore the request.
2232 return;
2235 gdbserver_state->c_cpu = cpu;
2236 gdbserver_state->g_cpu = cpu;
2239 #ifndef CONFIG_USER_ONLY
2240 static void gdb_vm_state_change(void *opaque, int running, RunState state)
2242 GDBState *s = gdbserver_state;
2243 CPUState *cpu = s->c_cpu;
2244 char buf[256];
2245 char thread_id[16];
2246 const char *type;
2247 int ret;
2249 if (running || s->state == RS_INACTIVE) {
2250 return;
2252 /* Is there a GDB syscall waiting to be sent? */
2253 if (s->current_syscall_cb) {
2254 put_packet(s, s->syscall_buf);
2255 return;
2258 if (cpu == NULL) {
2259 /* No process attached */
2260 return;
2263 gdb_fmt_thread_id(s, cpu, thread_id, sizeof(thread_id));
2265 switch (state) {
2266 case RUN_STATE_DEBUG:
2267 if (cpu->watchpoint_hit) {
2268 switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
2269 case BP_MEM_READ:
2270 type = "r";
2271 break;
2272 case BP_MEM_ACCESS:
2273 type = "a";
2274 break;
2275 default:
2276 type = "";
2277 break;
2279 trace_gdbstub_hit_watchpoint(type, cpu_gdb_index(cpu),
2280 (target_ulong)cpu->watchpoint_hit->vaddr);
2281 snprintf(buf, sizeof(buf),
2282 "T%02xthread:%s;%swatch:" TARGET_FMT_lx ";",
2283 GDB_SIGNAL_TRAP, thread_id, type,
2284 (target_ulong)cpu->watchpoint_hit->vaddr);
2285 cpu->watchpoint_hit = NULL;
2286 goto send_packet;
2287 } else {
2288 trace_gdbstub_hit_break();
2290 tb_flush(cpu);
2291 ret = GDB_SIGNAL_TRAP;
2292 break;
2293 case RUN_STATE_PAUSED:
2294 trace_gdbstub_hit_paused();
2295 ret = GDB_SIGNAL_INT;
2296 break;
2297 case RUN_STATE_SHUTDOWN:
2298 trace_gdbstub_hit_shutdown();
2299 ret = GDB_SIGNAL_QUIT;
2300 break;
2301 case RUN_STATE_IO_ERROR:
2302 trace_gdbstub_hit_io_error();
2303 ret = GDB_SIGNAL_IO;
2304 break;
2305 case RUN_STATE_WATCHDOG:
2306 trace_gdbstub_hit_watchdog();
2307 ret = GDB_SIGNAL_ALRM;
2308 break;
2309 case RUN_STATE_INTERNAL_ERROR:
2310 trace_gdbstub_hit_internal_error();
2311 ret = GDB_SIGNAL_ABRT;
2312 break;
2313 case RUN_STATE_SAVE_VM:
2314 case RUN_STATE_RESTORE_VM:
2315 return;
2316 case RUN_STATE_FINISH_MIGRATE:
2317 ret = GDB_SIGNAL_XCPU;
2318 break;
2319 default:
2320 trace_gdbstub_hit_unknown(state);
2321 ret = GDB_SIGNAL_UNKNOWN;
2322 break;
2324 gdb_set_stop_cpu(cpu);
2325 snprintf(buf, sizeof(buf), "T%02xthread:%s;", ret, thread_id);
2327 send_packet:
2328 put_packet(s, buf);
2330 /* disable single step if it was enabled */
2331 cpu_single_step(cpu, 0);
2333 #endif
2335 /* Send a gdb syscall request.
2336 This accepts limited printf-style format specifiers, specifically:
2337 %x - target_ulong argument printed in hex.
2338 %lx - 64-bit argument printed in hex.
2339 %s - string pointer (target_ulong) and length (int) pair. */
2340 void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
2342 char *p;
2343 char *p_end;
2344 target_ulong addr;
2345 uint64_t i64;
2346 GDBState *s;
2348 s = gdbserver_state;
2349 if (!s)
2350 return;
2351 s->current_syscall_cb = cb;
2352 #ifndef CONFIG_USER_ONLY
2353 vm_stop(RUN_STATE_DEBUG);
2354 #endif
2355 p = s->syscall_buf;
2356 p_end = &s->syscall_buf[sizeof(s->syscall_buf)];
2357 *(p++) = 'F';
2358 while (*fmt) {
2359 if (*fmt == '%') {
2360 fmt++;
2361 switch (*fmt++) {
2362 case 'x':
2363 addr = va_arg(va, target_ulong);
2364 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
2365 break;
2366 case 'l':
2367 if (*(fmt++) != 'x')
2368 goto bad_format;
2369 i64 = va_arg(va, uint64_t);
2370 p += snprintf(p, p_end - p, "%" PRIx64, i64);
2371 break;
2372 case 's':
2373 addr = va_arg(va, target_ulong);
2374 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
2375 addr, va_arg(va, int));
2376 break;
2377 default:
2378 bad_format:
2379 error_report("gdbstub: Bad syscall format string '%s'",
2380 fmt - 1);
2381 break;
2383 } else {
2384 *(p++) = *(fmt++);
2387 *p = 0;
2388 #ifdef CONFIG_USER_ONLY
2389 put_packet(s, s->syscall_buf);
2390 /* Return control to gdb for it to process the syscall request.
2391 * Since the protocol requires that gdb hands control back to us
2392 * using a "here are the results" F packet, we don't need to check
2393 * gdb_handlesig's return value (which is the signal to deliver if
2394 * execution was resumed via a continue packet).
2396 gdb_handlesig(s->c_cpu, 0);
2397 #else
2398 /* In this case wait to send the syscall packet until notification that
2399 the CPU has stopped. This must be done because if the packet is sent
2400 now the reply from the syscall request could be received while the CPU
2401 is still in the running state, which can cause packets to be dropped
2402 and state transition 'T' packets to be sent while the syscall is still
2403 being processed. */
2404 qemu_cpu_kick(s->c_cpu);
2405 #endif
2408 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
2410 va_list va;
2412 va_start(va, fmt);
2413 gdb_do_syscallv(cb, fmt, va);
2414 va_end(va);
2417 static void gdb_read_byte(GDBState *s, uint8_t ch)
2419 uint8_t reply;
2421 #ifndef CONFIG_USER_ONLY
2422 if (s->last_packet_len) {
2423 /* Waiting for a response to the last packet. If we see the start
2424 of a new command then abandon the previous response. */
2425 if (ch == '-') {
2426 trace_gdbstub_err_got_nack();
2427 put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
2428 } else if (ch == '+') {
2429 trace_gdbstub_io_got_ack();
2430 } else {
2431 trace_gdbstub_io_got_unexpected(ch);
2434 if (ch == '+' || ch == '$')
2435 s->last_packet_len = 0;
2436 if (ch != '$')
2437 return;
2439 if (runstate_is_running()) {
2440 /* when the CPU is running, we cannot do anything except stop
2441 it when receiving a char */
2442 vm_stop(RUN_STATE_PAUSED);
2443 } else
2444 #endif
2446 switch(s->state) {
2447 case RS_IDLE:
2448 if (ch == '$') {
2449 /* start of command packet */
2450 s->line_buf_index = 0;
2451 s->line_sum = 0;
2452 s->state = RS_GETLINE;
2453 } else {
2454 trace_gdbstub_err_garbage(ch);
2456 break;
2457 case RS_GETLINE:
2458 if (ch == '}') {
2459 /* start escape sequence */
2460 s->state = RS_GETLINE_ESC;
2461 s->line_sum += ch;
2462 } else if (ch == '*') {
2463 /* start run length encoding sequence */
2464 s->state = RS_GETLINE_RLE;
2465 s->line_sum += ch;
2466 } else if (ch == '#') {
2467 /* end of command, start of checksum*/
2468 s->state = RS_CHKSUM1;
2469 } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
2470 trace_gdbstub_err_overrun();
2471 s->state = RS_IDLE;
2472 } else {
2473 /* unescaped command character */
2474 s->line_buf[s->line_buf_index++] = ch;
2475 s->line_sum += ch;
2477 break;
2478 case RS_GETLINE_ESC:
2479 if (ch == '#') {
2480 /* unexpected end of command in escape sequence */
2481 s->state = RS_CHKSUM1;
2482 } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
2483 /* command buffer overrun */
2484 trace_gdbstub_err_overrun();
2485 s->state = RS_IDLE;
2486 } else {
2487 /* parse escaped character and leave escape state */
2488 s->line_buf[s->line_buf_index++] = ch ^ 0x20;
2489 s->line_sum += ch;
2490 s->state = RS_GETLINE;
2492 break;
2493 case RS_GETLINE_RLE:
2495 * Run-length encoding is explained in "Debugging with GDB /
2496 * Appendix E GDB Remote Serial Protocol / Overview".
2498 if (ch < ' ' || ch == '#' || ch == '$' || ch > 126) {
2499 /* invalid RLE count encoding */
2500 trace_gdbstub_err_invalid_repeat(ch);
2501 s->state = RS_GETLINE;
2502 } else {
2503 /* decode repeat length */
2504 int repeat = ch - ' ' + 3;
2505 if (s->line_buf_index + repeat >= sizeof(s->line_buf) - 1) {
2506 /* that many repeats would overrun the command buffer */
2507 trace_gdbstub_err_overrun();
2508 s->state = RS_IDLE;
2509 } else if (s->line_buf_index < 1) {
2510 /* got a repeat but we have nothing to repeat */
2511 trace_gdbstub_err_invalid_rle();
2512 s->state = RS_GETLINE;
2513 } else {
2514 /* repeat the last character */
2515 memset(s->line_buf + s->line_buf_index,
2516 s->line_buf[s->line_buf_index - 1], repeat);
2517 s->line_buf_index += repeat;
2518 s->line_sum += ch;
2519 s->state = RS_GETLINE;
2522 break;
2523 case RS_CHKSUM1:
2524 /* get high hex digit of checksum */
2525 if (!isxdigit(ch)) {
2526 trace_gdbstub_err_checksum_invalid(ch);
2527 s->state = RS_GETLINE;
2528 break;
2530 s->line_buf[s->line_buf_index] = '\0';
2531 s->line_csum = fromhex(ch) << 4;
2532 s->state = RS_CHKSUM2;
2533 break;
2534 case RS_CHKSUM2:
2535 /* get low hex digit of checksum */
2536 if (!isxdigit(ch)) {
2537 trace_gdbstub_err_checksum_invalid(ch);
2538 s->state = RS_GETLINE;
2539 break;
2541 s->line_csum |= fromhex(ch);
2543 if (s->line_csum != (s->line_sum & 0xff)) {
2544 trace_gdbstub_err_checksum_incorrect(s->line_sum, s->line_csum);
2545 /* send NAK reply */
2546 reply = '-';
2547 put_buffer(s, &reply, 1);
2548 s->state = RS_IDLE;
2549 } else {
2550 /* send ACK reply */
2551 reply = '+';
2552 put_buffer(s, &reply, 1);
2553 s->state = gdb_handle_packet(s, s->line_buf);
2555 break;
2556 default:
2557 abort();
2562 /* Tell the remote gdb that the process has exited. */
2563 void gdb_exit(CPUArchState *env, int code)
2565 GDBState *s;
2566 char buf[4];
2568 s = gdbserver_state;
2569 if (!s) {
2570 return;
2572 #ifdef CONFIG_USER_ONLY
2573 if (gdbserver_fd < 0 || s->fd < 0) {
2574 return;
2576 #endif
2578 trace_gdbstub_op_exiting((uint8_t)code);
2580 snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
2581 put_packet(s, buf);
2583 #ifndef CONFIG_USER_ONLY
2584 qemu_chr_fe_deinit(&s->chr, true);
2585 #endif
2589 * Create the process that will contain all the "orphan" CPUs (that are not
2590 * part of a CPU cluster). Note that if this process contains no CPUs, it won't
2591 * be attachable and thus will be invisible to the user.
2593 static void create_default_process(GDBState *s)
2595 GDBProcess *process;
2596 int max_pid = 0;
2598 if (s->process_num) {
2599 max_pid = s->processes[s->process_num - 1].pid;
2602 s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
2603 process = &s->processes[s->process_num - 1];
2605 /* We need an available PID slot for this process */
2606 assert(max_pid < UINT32_MAX);
2608 process->pid = max_pid + 1;
2609 process->attached = false;
2610 process->target_xml[0] = '\0';
2613 #ifdef CONFIG_USER_ONLY
2615 gdb_handlesig(CPUState *cpu, int sig)
2617 GDBState *s;
2618 char buf[256];
2619 int n;
2621 s = gdbserver_state;
2622 if (gdbserver_fd < 0 || s->fd < 0) {
2623 return sig;
2626 /* disable single step if it was enabled */
2627 cpu_single_step(cpu, 0);
2628 tb_flush(cpu);
2630 if (sig != 0) {
2631 snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
2632 put_packet(s, buf);
2634 /* put_packet() might have detected that the peer terminated the
2635 connection. */
2636 if (s->fd < 0) {
2637 return sig;
2640 sig = 0;
2641 s->state = RS_IDLE;
2642 s->running_state = 0;
2643 while (s->running_state == 0) {
2644 n = read(s->fd, buf, 256);
2645 if (n > 0) {
2646 int i;
2648 for (i = 0; i < n; i++) {
2649 gdb_read_byte(s, buf[i]);
2651 } else {
2652 /* XXX: Connection closed. Should probably wait for another
2653 connection before continuing. */
2654 if (n == 0) {
2655 close(s->fd);
2657 s->fd = -1;
2658 return sig;
2661 sig = s->signal;
2662 s->signal = 0;
2663 return sig;
2666 /* Tell the remote gdb that the process has exited due to SIG. */
2667 void gdb_signalled(CPUArchState *env, int sig)
2669 GDBState *s;
2670 char buf[4];
2672 s = gdbserver_state;
2673 if (gdbserver_fd < 0 || s->fd < 0) {
2674 return;
2677 snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
2678 put_packet(s, buf);
2681 static bool gdb_accept(void)
2683 GDBState *s;
2684 struct sockaddr_in sockaddr;
2685 socklen_t len;
2686 int fd;
2688 for(;;) {
2689 len = sizeof(sockaddr);
2690 fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
2691 if (fd < 0 && errno != EINTR) {
2692 perror("accept");
2693 return false;
2694 } else if (fd >= 0) {
2695 qemu_set_cloexec(fd);
2696 break;
2700 /* set short latency */
2701 if (socket_set_nodelay(fd)) {
2702 perror("setsockopt");
2703 close(fd);
2704 return false;
2707 s = g_malloc0(sizeof(GDBState));
2708 create_default_process(s);
2709 s->processes[0].attached = true;
2710 s->c_cpu = gdb_first_attached_cpu(s);
2711 s->g_cpu = s->c_cpu;
2712 s->fd = fd;
2713 gdb_has_xml = false;
2715 gdbserver_state = s;
2716 return true;
2719 static int gdbserver_open(int port)
2721 struct sockaddr_in sockaddr;
2722 int fd, ret;
2724 fd = socket(PF_INET, SOCK_STREAM, 0);
2725 if (fd < 0) {
2726 perror("socket");
2727 return -1;
2729 qemu_set_cloexec(fd);
2731 socket_set_fast_reuse(fd);
2733 sockaddr.sin_family = AF_INET;
2734 sockaddr.sin_port = htons(port);
2735 sockaddr.sin_addr.s_addr = 0;
2736 ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
2737 if (ret < 0) {
2738 perror("bind");
2739 close(fd);
2740 return -1;
2742 ret = listen(fd, 1);
2743 if (ret < 0) {
2744 perror("listen");
2745 close(fd);
2746 return -1;
2748 return fd;
2751 int gdbserver_start(int port)
2753 gdbserver_fd = gdbserver_open(port);
2754 if (gdbserver_fd < 0)
2755 return -1;
2756 /* accept connections */
2757 if (!gdb_accept()) {
2758 close(gdbserver_fd);
2759 gdbserver_fd = -1;
2760 return -1;
2762 return 0;
2765 /* Disable gdb stub for child processes. */
2766 void gdbserver_fork(CPUState *cpu)
2768 GDBState *s = gdbserver_state;
2770 if (gdbserver_fd < 0 || s->fd < 0) {
2771 return;
2773 close(s->fd);
2774 s->fd = -1;
2775 cpu_breakpoint_remove_all(cpu, BP_GDB);
2776 cpu_watchpoint_remove_all(cpu, BP_GDB);
2778 #else
2779 static int gdb_chr_can_receive(void *opaque)
2781 /* We can handle an arbitrarily large amount of data.
2782 Pick the maximum packet size, which is as good as anything. */
2783 return MAX_PACKET_LENGTH;
2786 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
2788 int i;
2790 for (i = 0; i < size; i++) {
2791 gdb_read_byte(gdbserver_state, buf[i]);
2795 static void gdb_chr_event(void *opaque, int event)
2797 int i;
2798 GDBState *s = (GDBState *) opaque;
2800 switch (event) {
2801 case CHR_EVENT_OPENED:
2802 /* Start with first process attached, others detached */
2803 for (i = 0; i < s->process_num; i++) {
2804 s->processes[i].attached = !i;
2807 s->c_cpu = gdb_first_attached_cpu(s);
2808 s->g_cpu = s->c_cpu;
2810 vm_stop(RUN_STATE_PAUSED);
2811 gdb_has_xml = false;
2812 break;
2813 default:
2814 break;
2818 static void gdb_monitor_output(GDBState *s, const char *msg, int len)
2820 char buf[MAX_PACKET_LENGTH];
2822 buf[0] = 'O';
2823 if (len > (MAX_PACKET_LENGTH/2) - 1)
2824 len = (MAX_PACKET_LENGTH/2) - 1;
2825 memtohex(buf + 1, (uint8_t *)msg, len);
2826 put_packet(s, buf);
2829 static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
2831 const char *p = (const char *)buf;
2832 int max_sz;
2834 max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
2835 for (;;) {
2836 if (len <= max_sz) {
2837 gdb_monitor_output(gdbserver_state, p, len);
2838 break;
2840 gdb_monitor_output(gdbserver_state, p, max_sz);
2841 p += max_sz;
2842 len -= max_sz;
2844 return len;
2847 #ifndef _WIN32
2848 static void gdb_sigterm_handler(int signal)
2850 if (runstate_is_running()) {
2851 vm_stop(RUN_STATE_PAUSED);
2854 #endif
2856 static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
2857 bool *be_opened, Error **errp)
2859 *be_opened = false;
2862 static void char_gdb_class_init(ObjectClass *oc, void *data)
2864 ChardevClass *cc = CHARDEV_CLASS(oc);
2866 cc->internal = true;
2867 cc->open = gdb_monitor_open;
2868 cc->chr_write = gdb_monitor_write;
2871 #define TYPE_CHARDEV_GDB "chardev-gdb"
2873 static const TypeInfo char_gdb_type_info = {
2874 .name = TYPE_CHARDEV_GDB,
2875 .parent = TYPE_CHARDEV,
2876 .class_init = char_gdb_class_init,
2879 static int find_cpu_clusters(Object *child, void *opaque)
2881 if (object_dynamic_cast(child, TYPE_CPU_CLUSTER)) {
2882 GDBState *s = (GDBState *) opaque;
2883 CPUClusterState *cluster = CPU_CLUSTER(child);
2884 GDBProcess *process;
2886 s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
2888 process = &s->processes[s->process_num - 1];
2891 * GDB process IDs -1 and 0 are reserved. To avoid subtle errors at
2892 * runtime, we enforce here that the machine does not use a cluster ID
2893 * that would lead to PID 0.
2895 assert(cluster->cluster_id != UINT32_MAX);
2896 process->pid = cluster->cluster_id + 1;
2897 process->attached = false;
2898 process->target_xml[0] = '\0';
2900 return 0;
2903 return object_child_foreach(child, find_cpu_clusters, opaque);
2906 static int pid_order(const void *a, const void *b)
2908 GDBProcess *pa = (GDBProcess *) a;
2909 GDBProcess *pb = (GDBProcess *) b;
2911 if (pa->pid < pb->pid) {
2912 return -1;
2913 } else if (pa->pid > pb->pid) {
2914 return 1;
2915 } else {
2916 return 0;
2920 static void create_processes(GDBState *s)
2922 object_child_foreach(object_get_root(), find_cpu_clusters, s);
2924 if (s->processes) {
2925 /* Sort by PID */
2926 qsort(s->processes, s->process_num, sizeof(s->processes[0]), pid_order);
2929 create_default_process(s);
2932 static void cleanup_processes(GDBState *s)
2934 g_free(s->processes);
2935 s->process_num = 0;
2936 s->processes = NULL;
2939 int gdbserver_start(const char *device)
2941 trace_gdbstub_op_start(device);
2943 GDBState *s;
2944 char gdbstub_device_name[128];
2945 Chardev *chr = NULL;
2946 Chardev *mon_chr;
2948 if (!first_cpu) {
2949 error_report("gdbstub: meaningless to attach gdb to a "
2950 "machine without any CPU.");
2951 return -1;
2954 if (!device)
2955 return -1;
2956 if (strcmp(device, "none") != 0) {
2957 if (strstart(device, "tcp:", NULL)) {
2958 /* enforce required TCP attributes */
2959 snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
2960 "%s,nowait,nodelay,server", device);
2961 device = gdbstub_device_name;
2963 #ifndef _WIN32
2964 else if (strcmp(device, "stdio") == 0) {
2965 struct sigaction act;
2967 memset(&act, 0, sizeof(act));
2968 act.sa_handler = gdb_sigterm_handler;
2969 sigaction(SIGINT, &act, NULL);
2971 #endif
2973 * FIXME: it's a bit weird to allow using a mux chardev here
2974 * and implicitly setup a monitor. We may want to break this.
2976 chr = qemu_chr_new_noreplay("gdb", device, true, NULL);
2977 if (!chr)
2978 return -1;
2981 s = gdbserver_state;
2982 if (!s) {
2983 s = g_malloc0(sizeof(GDBState));
2984 gdbserver_state = s;
2986 qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
2988 /* Initialize a monitor terminal for gdb */
2989 mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
2990 NULL, NULL, &error_abort);
2991 monitor_init(mon_chr, 0);
2992 } else {
2993 qemu_chr_fe_deinit(&s->chr, true);
2994 mon_chr = s->mon_chr;
2995 cleanup_processes(s);
2996 memset(s, 0, sizeof(GDBState));
2997 s->mon_chr = mon_chr;
3000 create_processes(s);
3002 if (chr) {
3003 qemu_chr_fe_init(&s->chr, chr, &error_abort);
3004 qemu_chr_fe_set_handlers(&s->chr, gdb_chr_can_receive, gdb_chr_receive,
3005 gdb_chr_event, NULL, s, NULL, true);
3007 s->state = chr ? RS_IDLE : RS_INACTIVE;
3008 s->mon_chr = mon_chr;
3009 s->current_syscall_cb = NULL;
3011 return 0;
3014 void gdbserver_cleanup(void)
3016 if (gdbserver_state) {
3017 put_packet(gdbserver_state, "W00");
3021 static void register_types(void)
3023 type_register_static(&char_gdb_type_info);
3026 type_init(register_types);
3027 #endif