]> git.proxmox.com Git - mirror_qemu.git/blob - gdbstub.c
7243a2f7af989c7568401e4ea3cb47295b31e733
[mirror_qemu.git] / gdbstub.c
1 /*
2 * gdb server stub
3 *
4 * This implements a subset of the remote protocol as described in:
5 *
6 * https://sourceware.org/gdb/onlinedocs/gdb/Remote-Protocol.html
7 *
8 * Copyright (c) 2003-2005 Fabrice Bellard
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
22 *
23 * SPDX-License-Identifier: LGPL-2.0+
24 */
25
26 #include "qemu/osdep.h"
27 #include "qemu-common.h"
28 #include "qapi/error.h"
29 #include "qemu/error-report.h"
30 #include "qemu/ctype.h"
31 #include "qemu/cutils.h"
32 #include "qemu/module.h"
33 #include "trace-root.h"
34 #ifdef CONFIG_USER_ONLY
35 #include "qemu.h"
36 #else
37 #include "monitor/monitor.h"
38 #include "chardev/char.h"
39 #include "chardev/char-fe.h"
40 #include "sysemu/sysemu.h"
41 #include "exec/gdbstub.h"
42 #include "hw/cpu/cluster.h"
43 #include "hw/boards.h"
44 #endif
45
46 #define MAX_PACKET_LENGTH 4096
47
48 #include "qemu/sockets.h"
49 #include "sysemu/hw_accel.h"
50 #include "sysemu/kvm.h"
51 #include "sysemu/runstate.h"
52 #include "hw/semihosting/semihost.h"
53 #include "exec/exec-all.h"
54
55 #ifdef CONFIG_USER_ONLY
56 #define GDB_ATTACHED "0"
57 #else
58 #define GDB_ATTACHED "1"
59 #endif
60
61 #ifndef CONFIG_USER_ONLY
62 static int phy_memory_mode;
63 #endif
64
65 static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
66 uint8_t *buf, int len, bool is_write)
67 {
68 CPUClass *cc;
69
70 #ifndef CONFIG_USER_ONLY
71 if (phy_memory_mode) {
72 if (is_write) {
73 cpu_physical_memory_write(addr, buf, len);
74 } else {
75 cpu_physical_memory_read(addr, buf, len);
76 }
77 return 0;
78 }
79 #endif
80
81 cc = CPU_GET_CLASS(cpu);
82 if (cc->memory_rw_debug) {
83 return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
84 }
85 return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
86 }
87
88 /* Return the GDB index for a given vCPU state.
89 *
90 * For user mode this is simply the thread id. In system mode GDB
91 * numbers CPUs from 1 as 0 is reserved as an "any cpu" index.
92 */
93 static inline int cpu_gdb_index(CPUState *cpu)
94 {
95 #if defined(CONFIG_USER_ONLY)
96 TaskState *ts = (TaskState *) cpu->opaque;
97 return ts->ts_tid;
98 #else
99 return cpu->cpu_index + 1;
100 #endif
101 }
102
103 enum {
104 GDB_SIGNAL_0 = 0,
105 GDB_SIGNAL_INT = 2,
106 GDB_SIGNAL_QUIT = 3,
107 GDB_SIGNAL_TRAP = 5,
108 GDB_SIGNAL_ABRT = 6,
109 GDB_SIGNAL_ALRM = 14,
110 GDB_SIGNAL_IO = 23,
111 GDB_SIGNAL_XCPU = 24,
112 GDB_SIGNAL_UNKNOWN = 143
113 };
114
115 #ifdef CONFIG_USER_ONLY
116
117 /* Map target signal numbers to GDB protocol signal numbers and vice
118 * versa. For user emulation's currently supported systems, we can
119 * assume most signals are defined.
120 */
121
122 static int gdb_signal_table[] = {
123 0,
124 TARGET_SIGHUP,
125 TARGET_SIGINT,
126 TARGET_SIGQUIT,
127 TARGET_SIGILL,
128 TARGET_SIGTRAP,
129 TARGET_SIGABRT,
130 -1, /* SIGEMT */
131 TARGET_SIGFPE,
132 TARGET_SIGKILL,
133 TARGET_SIGBUS,
134 TARGET_SIGSEGV,
135 TARGET_SIGSYS,
136 TARGET_SIGPIPE,
137 TARGET_SIGALRM,
138 TARGET_SIGTERM,
139 TARGET_SIGURG,
140 TARGET_SIGSTOP,
141 TARGET_SIGTSTP,
142 TARGET_SIGCONT,
143 TARGET_SIGCHLD,
144 TARGET_SIGTTIN,
145 TARGET_SIGTTOU,
146 TARGET_SIGIO,
147 TARGET_SIGXCPU,
148 TARGET_SIGXFSZ,
149 TARGET_SIGVTALRM,
150 TARGET_SIGPROF,
151 TARGET_SIGWINCH,
152 -1, /* SIGLOST */
153 TARGET_SIGUSR1,
154 TARGET_SIGUSR2,
155 #ifdef TARGET_SIGPWR
156 TARGET_SIGPWR,
157 #else
158 -1,
159 #endif
160 -1, /* SIGPOLL */
161 -1,
162 -1,
163 -1,
164 -1,
165 -1,
166 -1,
167 -1,
168 -1,
169 -1,
170 -1,
171 -1,
172 #ifdef __SIGRTMIN
173 __SIGRTMIN + 1,
174 __SIGRTMIN + 2,
175 __SIGRTMIN + 3,
176 __SIGRTMIN + 4,
177 __SIGRTMIN + 5,
178 __SIGRTMIN + 6,
179 __SIGRTMIN + 7,
180 __SIGRTMIN + 8,
181 __SIGRTMIN + 9,
182 __SIGRTMIN + 10,
183 __SIGRTMIN + 11,
184 __SIGRTMIN + 12,
185 __SIGRTMIN + 13,
186 __SIGRTMIN + 14,
187 __SIGRTMIN + 15,
188 __SIGRTMIN + 16,
189 __SIGRTMIN + 17,
190 __SIGRTMIN + 18,
191 __SIGRTMIN + 19,
192 __SIGRTMIN + 20,
193 __SIGRTMIN + 21,
194 __SIGRTMIN + 22,
195 __SIGRTMIN + 23,
196 __SIGRTMIN + 24,
197 __SIGRTMIN + 25,
198 __SIGRTMIN + 26,
199 __SIGRTMIN + 27,
200 __SIGRTMIN + 28,
201 __SIGRTMIN + 29,
202 __SIGRTMIN + 30,
203 __SIGRTMIN + 31,
204 -1, /* SIGCANCEL */
205 __SIGRTMIN,
206 __SIGRTMIN + 32,
207 __SIGRTMIN + 33,
208 __SIGRTMIN + 34,
209 __SIGRTMIN + 35,
210 __SIGRTMIN + 36,
211 __SIGRTMIN + 37,
212 __SIGRTMIN + 38,
213 __SIGRTMIN + 39,
214 __SIGRTMIN + 40,
215 __SIGRTMIN + 41,
216 __SIGRTMIN + 42,
217 __SIGRTMIN + 43,
218 __SIGRTMIN + 44,
219 __SIGRTMIN + 45,
220 __SIGRTMIN + 46,
221 __SIGRTMIN + 47,
222 __SIGRTMIN + 48,
223 __SIGRTMIN + 49,
224 __SIGRTMIN + 50,
225 __SIGRTMIN + 51,
226 __SIGRTMIN + 52,
227 __SIGRTMIN + 53,
228 __SIGRTMIN + 54,
229 __SIGRTMIN + 55,
230 __SIGRTMIN + 56,
231 __SIGRTMIN + 57,
232 __SIGRTMIN + 58,
233 __SIGRTMIN + 59,
234 __SIGRTMIN + 60,
235 __SIGRTMIN + 61,
236 __SIGRTMIN + 62,
237 __SIGRTMIN + 63,
238 __SIGRTMIN + 64,
239 __SIGRTMIN + 65,
240 __SIGRTMIN + 66,
241 __SIGRTMIN + 67,
242 __SIGRTMIN + 68,
243 __SIGRTMIN + 69,
244 __SIGRTMIN + 70,
245 __SIGRTMIN + 71,
246 __SIGRTMIN + 72,
247 __SIGRTMIN + 73,
248 __SIGRTMIN + 74,
249 __SIGRTMIN + 75,
250 __SIGRTMIN + 76,
251 __SIGRTMIN + 77,
252 __SIGRTMIN + 78,
253 __SIGRTMIN + 79,
254 __SIGRTMIN + 80,
255 __SIGRTMIN + 81,
256 __SIGRTMIN + 82,
257 __SIGRTMIN + 83,
258 __SIGRTMIN + 84,
259 __SIGRTMIN + 85,
260 __SIGRTMIN + 86,
261 __SIGRTMIN + 87,
262 __SIGRTMIN + 88,
263 __SIGRTMIN + 89,
264 __SIGRTMIN + 90,
265 __SIGRTMIN + 91,
266 __SIGRTMIN + 92,
267 __SIGRTMIN + 93,
268 __SIGRTMIN + 94,
269 __SIGRTMIN + 95,
270 -1, /* SIGINFO */
271 -1, /* UNKNOWN */
272 -1, /* DEFAULT */
273 -1,
274 -1,
275 -1,
276 -1,
277 -1,
278 -1
279 #endif
280 };
281 #else
282 /* In system mode we only need SIGINT and SIGTRAP; other signals
283 are not yet supported. */
284
285 enum {
286 TARGET_SIGINT = 2,
287 TARGET_SIGTRAP = 5
288 };
289
290 static int gdb_signal_table[] = {
291 -1,
292 -1,
293 TARGET_SIGINT,
294 -1,
295 -1,
296 TARGET_SIGTRAP
297 };
298 #endif
299
300 #ifdef CONFIG_USER_ONLY
301 static int target_signal_to_gdb (int sig)
302 {
303 int i;
304 for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
305 if (gdb_signal_table[i] == sig)
306 return i;
307 return GDB_SIGNAL_UNKNOWN;
308 }
309 #endif
310
311 static int gdb_signal_to_target (int sig)
312 {
313 if (sig < ARRAY_SIZE (gdb_signal_table))
314 return gdb_signal_table[sig];
315 else
316 return -1;
317 }
318
319 typedef struct GDBRegisterState {
320 int base_reg;
321 int num_regs;
322 gdb_reg_cb get_reg;
323 gdb_reg_cb set_reg;
324 const char *xml;
325 struct GDBRegisterState *next;
326 } GDBRegisterState;
327
328 typedef struct GDBProcess {
329 uint32_t pid;
330 bool attached;
331
332 char target_xml[1024];
333 } GDBProcess;
334
335 enum RSState {
336 RS_INACTIVE,
337 RS_IDLE,
338 RS_GETLINE,
339 RS_GETLINE_ESC,
340 RS_GETLINE_RLE,
341 RS_CHKSUM1,
342 RS_CHKSUM2,
343 };
344 typedef struct GDBState {
345 bool init; /* have we been initialised? */
346 CPUState *c_cpu; /* current CPU for step/continue ops */
347 CPUState *g_cpu; /* current CPU for other ops */
348 CPUState *query_cpu; /* for q{f|s}ThreadInfo */
349 enum RSState state; /* parsing state */
350 char line_buf[MAX_PACKET_LENGTH];
351 int line_buf_index;
352 int line_sum; /* running checksum */
353 int line_csum; /* checksum at the end of the packet */
354 uint8_t last_packet[MAX_PACKET_LENGTH + 4];
355 int last_packet_len;
356 int signal;
357 #ifdef CONFIG_USER_ONLY
358 int fd;
359 int running_state;
360 #else
361 CharBackend chr;
362 Chardev *mon_chr;
363 #endif
364 bool multiprocess;
365 GDBProcess *processes;
366 int process_num;
367 char syscall_buf[256];
368 gdb_syscall_complete_cb current_syscall_cb;
369 } GDBState;
370
371 /* By default use no IRQs and no timers while single stepping so as to
372 * make single stepping like an ICE HW step.
373 */
374 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
375
376 static GDBState gdbserver_state;
377
378 static void init_gdbserver_state(void)
379 {
380 g_assert(!gdbserver_state.init);
381 memset(&gdbserver_state, 0, sizeof(GDBState));
382 gdbserver_state.init = true;
383 }
384
385 #ifndef CONFIG_USER_ONLY
386 static void reset_gdbserver_state(void)
387 {
388 g_free(gdbserver_state.processes);
389 gdbserver_state.processes = NULL;
390 gdbserver_state.process_num = 0;
391 }
392 #endif
393
394 bool gdb_has_xml;
395
396 #ifdef CONFIG_USER_ONLY
397 /* XXX: This is not thread safe. Do we care? */
398 static int gdbserver_fd = -1;
399
400 static int get_char(void)
401 {
402 uint8_t ch;
403 int ret;
404
405 for(;;) {
406 ret = qemu_recv(gdbserver_state.fd, &ch, 1, 0);
407 if (ret < 0) {
408 if (errno == ECONNRESET)
409 gdbserver_state.fd = -1;
410 if (errno != EINTR)
411 return -1;
412 } else if (ret == 0) {
413 close(gdbserver_state.fd);
414 gdbserver_state.fd = -1;
415 return -1;
416 } else {
417 break;
418 }
419 }
420 return ch;
421 }
422 #endif
423
424 static enum {
425 GDB_SYS_UNKNOWN,
426 GDB_SYS_ENABLED,
427 GDB_SYS_DISABLED,
428 } gdb_syscall_mode;
429
430 /* Decide if either remote gdb syscalls or native file IO should be used. */
431 int use_gdb_syscalls(void)
432 {
433 SemihostingTarget target = semihosting_get_target();
434 if (target == SEMIHOSTING_TARGET_NATIVE) {
435 /* -semihosting-config target=native */
436 return false;
437 } else if (target == SEMIHOSTING_TARGET_GDB) {
438 /* -semihosting-config target=gdb */
439 return true;
440 }
441
442 /* -semihosting-config target=auto */
443 /* On the first call check if gdb is connected and remember. */
444 if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
445 gdb_syscall_mode = gdbserver_state.init ?
446 GDB_SYS_ENABLED : GDB_SYS_DISABLED;
447 }
448 return gdb_syscall_mode == GDB_SYS_ENABLED;
449 }
450
451 /* Resume execution. */
452 static inline void gdb_continue(void)
453 {
454
455 #ifdef CONFIG_USER_ONLY
456 gdbserver_state.running_state = 1;
457 trace_gdbstub_op_continue();
458 #else
459 if (!runstate_needs_reset()) {
460 trace_gdbstub_op_continue();
461 vm_start();
462 }
463 #endif
464 }
465
466 /*
467 * Resume execution, per CPU actions. For user-mode emulation it's
468 * equivalent to gdb_continue.
469 */
470 static int gdb_continue_partial(char *newstates)
471 {
472 CPUState *cpu;
473 int res = 0;
474 #ifdef CONFIG_USER_ONLY
475 /*
476 * This is not exactly accurate, but it's an improvement compared to the
477 * previous situation, where only one CPU would be single-stepped.
478 */
479 CPU_FOREACH(cpu) {
480 if (newstates[cpu->cpu_index] == 's') {
481 trace_gdbstub_op_stepping(cpu->cpu_index);
482 cpu_single_step(cpu, sstep_flags);
483 }
484 }
485 gdbserver_state.running_state = 1;
486 #else
487 int flag = 0;
488
489 if (!runstate_needs_reset()) {
490 if (vm_prepare_start()) {
491 return 0;
492 }
493
494 CPU_FOREACH(cpu) {
495 switch (newstates[cpu->cpu_index]) {
496 case 0:
497 case 1:
498 break; /* nothing to do here */
499 case 's':
500 trace_gdbstub_op_stepping(cpu->cpu_index);
501 cpu_single_step(cpu, sstep_flags);
502 cpu_resume(cpu);
503 flag = 1;
504 break;
505 case 'c':
506 trace_gdbstub_op_continue_cpu(cpu->cpu_index);
507 cpu_resume(cpu);
508 flag = 1;
509 break;
510 default:
511 res = -1;
512 break;
513 }
514 }
515 }
516 if (flag) {
517 qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
518 }
519 #endif
520 return res;
521 }
522
523 static void put_buffer(const uint8_t *buf, int len)
524 {
525 #ifdef CONFIG_USER_ONLY
526 int ret;
527
528 while (len > 0) {
529 ret = send(gdbserver_state.fd, buf, len, 0);
530 if (ret < 0) {
531 if (errno != EINTR)
532 return;
533 } else {
534 buf += ret;
535 len -= ret;
536 }
537 }
538 #else
539 /* XXX this blocks entire thread. Rewrite to use
540 * qemu_chr_fe_write and background I/O callbacks */
541 qemu_chr_fe_write_all(&gdbserver_state.chr, buf, len);
542 #endif
543 }
544
545 static inline int fromhex(int v)
546 {
547 if (v >= '0' && v <= '9')
548 return v - '0';
549 else if (v >= 'A' && v <= 'F')
550 return v - 'A' + 10;
551 else if (v >= 'a' && v <= 'f')
552 return v - 'a' + 10;
553 else
554 return 0;
555 }
556
557 static inline int tohex(int v)
558 {
559 if (v < 10)
560 return v + '0';
561 else
562 return v - 10 + 'a';
563 }
564
565 /* writes 2*len+1 bytes in buf */
566 static void memtohex(char *buf, const uint8_t *mem, int len)
567 {
568 int i, c;
569 char *q;
570 q = buf;
571 for(i = 0; i < len; i++) {
572 c = mem[i];
573 *q++ = tohex(c >> 4);
574 *q++ = tohex(c & 0xf);
575 }
576 *q = '\0';
577 }
578
579 static void hextomem(uint8_t *mem, const char *buf, int len)
580 {
581 int i;
582
583 for(i = 0; i < len; i++) {
584 mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
585 buf += 2;
586 }
587 }
588
589 static void hexdump(const char *buf, int len,
590 void (*trace_fn)(size_t ofs, char const *text))
591 {
592 char line_buffer[3 * 16 + 4 + 16 + 1];
593
594 size_t i;
595 for (i = 0; i < len || (i & 0xF); ++i) {
596 size_t byte_ofs = i & 15;
597
598 if (byte_ofs == 0) {
599 memset(line_buffer, ' ', 3 * 16 + 4 + 16);
600 line_buffer[3 * 16 + 4 + 16] = 0;
601 }
602
603 size_t col_group = (i >> 2) & 3;
604 size_t hex_col = byte_ofs * 3 + col_group;
605 size_t txt_col = 3 * 16 + 4 + byte_ofs;
606
607 if (i < len) {
608 char value = buf[i];
609
610 line_buffer[hex_col + 0] = tohex((value >> 4) & 0xF);
611 line_buffer[hex_col + 1] = tohex((value >> 0) & 0xF);
612 line_buffer[txt_col + 0] = (value >= ' ' && value < 127)
613 ? value
614 : '.';
615 }
616
617 if (byte_ofs == 0xF)
618 trace_fn(i & -16, line_buffer);
619 }
620 }
621
622 /* return -1 if error, 0 if OK */
623 static int put_packet_binary(const char *buf, int len, bool dump)
624 {
625 int csum, i;
626 uint8_t *p;
627 uint8_t *ps = &gdbserver_state.last_packet[0];
628
629 if (dump && trace_event_get_state_backends(TRACE_GDBSTUB_IO_BINARYREPLY)) {
630 hexdump(buf, len, trace_gdbstub_io_binaryreply);
631 }
632
633 for(;;) {
634 p = ps;
635 *(p++) = '$';
636 memcpy(p, buf, len);
637 p += len;
638 csum = 0;
639 for(i = 0; i < len; i++) {
640 csum += buf[i];
641 }
642 *(p++) = '#';
643 *(p++) = tohex((csum >> 4) & 0xf);
644 *(p++) = tohex((csum) & 0xf);
645
646 gdbserver_state.last_packet_len = p - ps;
647 put_buffer(ps, gdbserver_state.last_packet_len);
648
649 #ifdef CONFIG_USER_ONLY
650 i = get_char();
651 if (i < 0)
652 return -1;
653 if (i == '+')
654 break;
655 #else
656 break;
657 #endif
658 }
659 return 0;
660 }
661
662 /* return -1 if error, 0 if OK */
663 static int put_packet(const char *buf)
664 {
665 trace_gdbstub_io_reply(buf);
666
667 return put_packet_binary(buf, strlen(buf), false);
668 }
669
670 /* Encode data using the encoding for 'x' packets. */
671 static int memtox(char *buf, const char *mem, int len)
672 {
673 char *p = buf;
674 char c;
675
676 while (len--) {
677 c = *(mem++);
678 switch (c) {
679 case '#': case '$': case '*': case '}':
680 *(p++) = '}';
681 *(p++) = c ^ 0x20;
682 break;
683 default:
684 *(p++) = c;
685 break;
686 }
687 }
688 return p - buf;
689 }
690
691 static uint32_t gdb_get_cpu_pid(CPUState *cpu)
692 {
693 /* TODO: In user mode, we should use the task state PID */
694 if (cpu->cluster_index == UNASSIGNED_CLUSTER_INDEX) {
695 /* Return the default process' PID */
696 int index = gdbserver_state.process_num - 1;
697 return gdbserver_state.processes[index].pid;
698 }
699 return cpu->cluster_index + 1;
700 }
701
702 static GDBProcess *gdb_get_process(uint32_t pid)
703 {
704 int i;
705
706 if (!pid) {
707 /* 0 means any process, we take the first one */
708 return &gdbserver_state.processes[0];
709 }
710
711 for (i = 0; i < gdbserver_state.process_num; i++) {
712 if (gdbserver_state.processes[i].pid == pid) {
713 return &gdbserver_state.processes[i];
714 }
715 }
716
717 return NULL;
718 }
719
720 static GDBProcess *gdb_get_cpu_process(CPUState *cpu)
721 {
722 return gdb_get_process(gdb_get_cpu_pid(cpu));
723 }
724
725 static CPUState *find_cpu(uint32_t thread_id)
726 {
727 CPUState *cpu;
728
729 CPU_FOREACH(cpu) {
730 if (cpu_gdb_index(cpu) == thread_id) {
731 return cpu;
732 }
733 }
734
735 return NULL;
736 }
737
738 static CPUState *get_first_cpu_in_process(GDBProcess *process)
739 {
740 CPUState *cpu;
741
742 CPU_FOREACH(cpu) {
743 if (gdb_get_cpu_pid(cpu) == process->pid) {
744 return cpu;
745 }
746 }
747
748 return NULL;
749 }
750
751 static CPUState *gdb_next_cpu_in_process(CPUState *cpu)
752 {
753 uint32_t pid = gdb_get_cpu_pid(cpu);
754 cpu = CPU_NEXT(cpu);
755
756 while (cpu) {
757 if (gdb_get_cpu_pid(cpu) == pid) {
758 break;
759 }
760
761 cpu = CPU_NEXT(cpu);
762 }
763
764 return cpu;
765 }
766
767 /* Return the cpu following @cpu, while ignoring unattached processes. */
768 static CPUState *gdb_next_attached_cpu(CPUState *cpu)
769 {
770 cpu = CPU_NEXT(cpu);
771
772 while (cpu) {
773 if (gdb_get_cpu_process(cpu)->attached) {
774 break;
775 }
776
777 cpu = CPU_NEXT(cpu);
778 }
779
780 return cpu;
781 }
782
783 /* Return the first attached cpu */
784 static CPUState *gdb_first_attached_cpu(void)
785 {
786 CPUState *cpu = first_cpu;
787 GDBProcess *process = gdb_get_cpu_process(cpu);
788
789 if (!process->attached) {
790 return gdb_next_attached_cpu(cpu);
791 }
792
793 return cpu;
794 }
795
796 static CPUState *gdb_get_cpu(uint32_t pid, uint32_t tid)
797 {
798 GDBProcess *process;
799 CPUState *cpu;
800
801 if (!pid && !tid) {
802 /* 0 means any process/thread, we take the first attached one */
803 return gdb_first_attached_cpu();
804 } else if (pid && !tid) {
805 /* any thread in a specific process */
806 process = gdb_get_process(pid);
807
808 if (process == NULL) {
809 return NULL;
810 }
811
812 if (!process->attached) {
813 return NULL;
814 }
815
816 return get_first_cpu_in_process(process);
817 } else {
818 /* a specific thread */
819 cpu = find_cpu(tid);
820
821 if (cpu == NULL) {
822 return NULL;
823 }
824
825 process = gdb_get_cpu_process(cpu);
826
827 if (pid && process->pid != pid) {
828 return NULL;
829 }
830
831 if (!process->attached) {
832 return NULL;
833 }
834
835 return cpu;
836 }
837 }
838
839 static const char *get_feature_xml(const char *p, const char **newp,
840 GDBProcess *process)
841 {
842 size_t len;
843 int i;
844 const char *name;
845 CPUState *cpu = get_first_cpu_in_process(process);
846 CPUClass *cc = CPU_GET_CLASS(cpu);
847
848 len = 0;
849 while (p[len] && p[len] != ':')
850 len++;
851 *newp = p + len;
852
853 name = NULL;
854 if (strncmp(p, "target.xml", len) == 0) {
855 char *buf = process->target_xml;
856 const size_t buf_sz = sizeof(process->target_xml);
857
858 /* Generate the XML description for this CPU. */
859 if (!buf[0]) {
860 GDBRegisterState *r;
861
862 pstrcat(buf, buf_sz,
863 "<?xml version=\"1.0\"?>"
864 "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
865 "<target>");
866 if (cc->gdb_arch_name) {
867 gchar *arch = cc->gdb_arch_name(cpu);
868 pstrcat(buf, buf_sz, "<architecture>");
869 pstrcat(buf, buf_sz, arch);
870 pstrcat(buf, buf_sz, "</architecture>");
871 g_free(arch);
872 }
873 pstrcat(buf, buf_sz, "<xi:include href=\"");
874 pstrcat(buf, buf_sz, cc->gdb_core_xml_file);
875 pstrcat(buf, buf_sz, "\"/>");
876 for (r = cpu->gdb_regs; r; r = r->next) {
877 pstrcat(buf, buf_sz, "<xi:include href=\"");
878 pstrcat(buf, buf_sz, r->xml);
879 pstrcat(buf, buf_sz, "\"/>");
880 }
881 pstrcat(buf, buf_sz, "</target>");
882 }
883 return buf;
884 }
885 if (cc->gdb_get_dynamic_xml) {
886 char *xmlname = g_strndup(p, len);
887 const char *xml = cc->gdb_get_dynamic_xml(cpu, xmlname);
888
889 g_free(xmlname);
890 if (xml) {
891 return xml;
892 }
893 }
894 for (i = 0; ; i++) {
895 name = xml_builtin[i][0];
896 if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
897 break;
898 }
899 return name ? xml_builtin[i][1] : NULL;
900 }
901
902 static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
903 {
904 CPUClass *cc = CPU_GET_CLASS(cpu);
905 CPUArchState *env = cpu->env_ptr;
906 GDBRegisterState *r;
907
908 if (reg < cc->gdb_num_core_regs) {
909 return cc->gdb_read_register(cpu, mem_buf, reg);
910 }
911
912 for (r = cpu->gdb_regs; r; r = r->next) {
913 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
914 return r->get_reg(env, mem_buf, reg - r->base_reg);
915 }
916 }
917 return 0;
918 }
919
920 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
921 {
922 CPUClass *cc = CPU_GET_CLASS(cpu);
923 CPUArchState *env = cpu->env_ptr;
924 GDBRegisterState *r;
925
926 if (reg < cc->gdb_num_core_regs) {
927 return cc->gdb_write_register(cpu, mem_buf, reg);
928 }
929
930 for (r = cpu->gdb_regs; r; r = r->next) {
931 if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
932 return r->set_reg(env, mem_buf, reg - r->base_reg);
933 }
934 }
935 return 0;
936 }
937
938 /* Register a supplemental set of CPU registers. If g_pos is nonzero it
939 specifies the first register number and these registers are included in
940 a standard "g" packet. Direction is relative to gdb, i.e. get_reg is
941 gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
942 */
943
944 void gdb_register_coprocessor(CPUState *cpu,
945 gdb_reg_cb get_reg, gdb_reg_cb set_reg,
946 int num_regs, const char *xml, int g_pos)
947 {
948 GDBRegisterState *s;
949 GDBRegisterState **p;
950
951 p = &cpu->gdb_regs;
952 while (*p) {
953 /* Check for duplicates. */
954 if (strcmp((*p)->xml, xml) == 0)
955 return;
956 p = &(*p)->next;
957 }
958
959 s = g_new0(GDBRegisterState, 1);
960 s->base_reg = cpu->gdb_num_regs;
961 s->num_regs = num_regs;
962 s->get_reg = get_reg;
963 s->set_reg = set_reg;
964 s->xml = xml;
965
966 /* Add to end of list. */
967 cpu->gdb_num_regs += num_regs;
968 *p = s;
969 if (g_pos) {
970 if (g_pos != s->base_reg) {
971 error_report("Error: Bad gdb register numbering for '%s', "
972 "expected %d got %d", xml, g_pos, s->base_reg);
973 } else {
974 cpu->gdb_num_g_regs = cpu->gdb_num_regs;
975 }
976 }
977 }
978
979 #ifndef CONFIG_USER_ONLY
980 /* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
981 static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
982 {
983 static const int xlat[] = {
984 [GDB_WATCHPOINT_WRITE] = BP_GDB | BP_MEM_WRITE,
985 [GDB_WATCHPOINT_READ] = BP_GDB | BP_MEM_READ,
986 [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
987 };
988
989 CPUClass *cc = CPU_GET_CLASS(cpu);
990 int cputype = xlat[gdbtype];
991
992 if (cc->gdb_stop_before_watchpoint) {
993 cputype |= BP_STOP_BEFORE_ACCESS;
994 }
995 return cputype;
996 }
997 #endif
998
999 static int gdb_breakpoint_insert(int type, target_ulong addr, target_ulong len)
1000 {
1001 CPUState *cpu;
1002 int err = 0;
1003
1004 if (kvm_enabled()) {
1005 return kvm_insert_breakpoint(gdbserver_state.c_cpu, addr, len, type);
1006 }
1007
1008 switch (type) {
1009 case GDB_BREAKPOINT_SW:
1010 case GDB_BREAKPOINT_HW:
1011 CPU_FOREACH(cpu) {
1012 err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
1013 if (err) {
1014 break;
1015 }
1016 }
1017 return err;
1018 #ifndef CONFIG_USER_ONLY
1019 case GDB_WATCHPOINT_WRITE:
1020 case GDB_WATCHPOINT_READ:
1021 case GDB_WATCHPOINT_ACCESS:
1022 CPU_FOREACH(cpu) {
1023 err = cpu_watchpoint_insert(cpu, addr, len,
1024 xlat_gdb_type(cpu, type), NULL);
1025 if (err) {
1026 break;
1027 }
1028 }
1029 return err;
1030 #endif
1031 default:
1032 return -ENOSYS;
1033 }
1034 }
1035
1036 static int gdb_breakpoint_remove(int type, target_ulong addr, target_ulong len)
1037 {
1038 CPUState *cpu;
1039 int err = 0;
1040
1041 if (kvm_enabled()) {
1042 return kvm_remove_breakpoint(gdbserver_state.c_cpu, addr, len, type);
1043 }
1044
1045 switch (type) {
1046 case GDB_BREAKPOINT_SW:
1047 case GDB_BREAKPOINT_HW:
1048 CPU_FOREACH(cpu) {
1049 err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
1050 if (err) {
1051 break;
1052 }
1053 }
1054 return err;
1055 #ifndef CONFIG_USER_ONLY
1056 case GDB_WATCHPOINT_WRITE:
1057 case GDB_WATCHPOINT_READ:
1058 case GDB_WATCHPOINT_ACCESS:
1059 CPU_FOREACH(cpu) {
1060 err = cpu_watchpoint_remove(cpu, addr, len,
1061 xlat_gdb_type(cpu, type));
1062 if (err)
1063 break;
1064 }
1065 return err;
1066 #endif
1067 default:
1068 return -ENOSYS;
1069 }
1070 }
1071
1072 static inline void gdb_cpu_breakpoint_remove_all(CPUState *cpu)
1073 {
1074 cpu_breakpoint_remove_all(cpu, BP_GDB);
1075 #ifndef CONFIG_USER_ONLY
1076 cpu_watchpoint_remove_all(cpu, BP_GDB);
1077 #endif
1078 }
1079
1080 static void gdb_process_breakpoint_remove_all(GDBProcess *p)
1081 {
1082 CPUState *cpu = get_first_cpu_in_process(p);
1083
1084 while (cpu) {
1085 gdb_cpu_breakpoint_remove_all(cpu);
1086 cpu = gdb_next_cpu_in_process(cpu);
1087 }
1088 }
1089
1090 static void gdb_breakpoint_remove_all(void)
1091 {
1092 CPUState *cpu;
1093
1094 if (kvm_enabled()) {
1095 kvm_remove_all_breakpoints(gdbserver_state.c_cpu);
1096 return;
1097 }
1098
1099 CPU_FOREACH(cpu) {
1100 gdb_cpu_breakpoint_remove_all(cpu);
1101 }
1102 }
1103
1104 static void gdb_set_cpu_pc(target_ulong pc)
1105 {
1106 CPUState *cpu = gdbserver_state.c_cpu;
1107
1108 cpu_synchronize_state(cpu);
1109 cpu_set_pc(cpu, pc);
1110 }
1111
1112 static char *gdb_fmt_thread_id(CPUState *cpu, char *buf, size_t buf_size)
1113 {
1114 if (gdbserver_state.multiprocess) {
1115 snprintf(buf, buf_size, "p%02x.%02x",
1116 gdb_get_cpu_pid(cpu), cpu_gdb_index(cpu));
1117 } else {
1118 snprintf(buf, buf_size, "%02x", cpu_gdb_index(cpu));
1119 }
1120
1121 return buf;
1122 }
1123
1124 typedef enum GDBThreadIdKind {
1125 GDB_ONE_THREAD = 0,
1126 GDB_ALL_THREADS, /* One process, all threads */
1127 GDB_ALL_PROCESSES,
1128 GDB_READ_THREAD_ERR
1129 } GDBThreadIdKind;
1130
1131 static GDBThreadIdKind read_thread_id(const char *buf, const char **end_buf,
1132 uint32_t *pid, uint32_t *tid)
1133 {
1134 unsigned long p, t;
1135 int ret;
1136
1137 if (*buf == 'p') {
1138 buf++;
1139 ret = qemu_strtoul(buf, &buf, 16, &p);
1140
1141 if (ret) {
1142 return GDB_READ_THREAD_ERR;
1143 }
1144
1145 /* Skip '.' */
1146 buf++;
1147 } else {
1148 p = 1;
1149 }
1150
1151 ret = qemu_strtoul(buf, &buf, 16, &t);
1152
1153 if (ret) {
1154 return GDB_READ_THREAD_ERR;
1155 }
1156
1157 *end_buf = buf;
1158
1159 if (p == -1) {
1160 return GDB_ALL_PROCESSES;
1161 }
1162
1163 if (pid) {
1164 *pid = p;
1165 }
1166
1167 if (t == -1) {
1168 return GDB_ALL_THREADS;
1169 }
1170
1171 if (tid) {
1172 *tid = t;
1173 }
1174
1175 return GDB_ONE_THREAD;
1176 }
1177
1178 /**
1179 * gdb_handle_vcont - Parses and handles a vCont packet.
1180 * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
1181 * a format error, 0 on success.
1182 */
1183 static int gdb_handle_vcont(const char *p)
1184 {
1185 int res, signal = 0;
1186 char cur_action;
1187 char *newstates;
1188 unsigned long tmp;
1189 uint32_t pid, tid;
1190 GDBProcess *process;
1191 CPUState *cpu;
1192 GDBThreadIdKind kind;
1193 #ifdef CONFIG_USER_ONLY
1194 int max_cpus = 1; /* global variable max_cpus exists only in system mode */
1195
1196 CPU_FOREACH(cpu) {
1197 max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
1198 }
1199 #else
1200 MachineState *ms = MACHINE(qdev_get_machine());
1201 unsigned int max_cpus = ms->smp.max_cpus;
1202 #endif
1203 /* uninitialised CPUs stay 0 */
1204 newstates = g_new0(char, max_cpus);
1205
1206 /* mark valid CPUs with 1 */
1207 CPU_FOREACH(cpu) {
1208 newstates[cpu->cpu_index] = 1;
1209 }
1210
1211 /*
1212 * res keeps track of what error we are returning, with -ENOTSUP meaning
1213 * that the command is unknown or unsupported, thus returning an empty
1214 * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
1215 * or incorrect parameters passed.
1216 */
1217 res = 0;
1218 while (*p) {
1219 if (*p++ != ';') {
1220 res = -ENOTSUP;
1221 goto out;
1222 }
1223
1224 cur_action = *p++;
1225 if (cur_action == 'C' || cur_action == 'S') {
1226 cur_action = qemu_tolower(cur_action);
1227 res = qemu_strtoul(p + 1, &p, 16, &tmp);
1228 if (res) {
1229 goto out;
1230 }
1231 signal = gdb_signal_to_target(tmp);
1232 } else if (cur_action != 'c' && cur_action != 's') {
1233 /* unknown/invalid/unsupported command */
1234 res = -ENOTSUP;
1235 goto out;
1236 }
1237
1238 if (*p == '\0' || *p == ';') {
1239 /*
1240 * No thread specifier, action is on "all threads". The
1241 * specification is unclear regarding the process to act on. We
1242 * choose all processes.
1243 */
1244 kind = GDB_ALL_PROCESSES;
1245 } else if (*p++ == ':') {
1246 kind = read_thread_id(p, &p, &pid, &tid);
1247 } else {
1248 res = -ENOTSUP;
1249 goto out;
1250 }
1251
1252 switch (kind) {
1253 case GDB_READ_THREAD_ERR:
1254 res = -EINVAL;
1255 goto out;
1256
1257 case GDB_ALL_PROCESSES:
1258 cpu = gdb_first_attached_cpu();
1259 while (cpu) {
1260 if (newstates[cpu->cpu_index] == 1) {
1261 newstates[cpu->cpu_index] = cur_action;
1262 }
1263
1264 cpu = gdb_next_attached_cpu(cpu);
1265 }
1266 break;
1267
1268 case GDB_ALL_THREADS:
1269 process = gdb_get_process(pid);
1270
1271 if (!process->attached) {
1272 res = -EINVAL;
1273 goto out;
1274 }
1275
1276 cpu = get_first_cpu_in_process(process);
1277 while (cpu) {
1278 if (newstates[cpu->cpu_index] == 1) {
1279 newstates[cpu->cpu_index] = cur_action;
1280 }
1281
1282 cpu = gdb_next_cpu_in_process(cpu);
1283 }
1284 break;
1285
1286 case GDB_ONE_THREAD:
1287 cpu = gdb_get_cpu(pid, tid);
1288
1289 /* invalid CPU/thread specified */
1290 if (!cpu) {
1291 res = -EINVAL;
1292 goto out;
1293 }
1294
1295 /* only use if no previous match occourred */
1296 if (newstates[cpu->cpu_index] == 1) {
1297 newstates[cpu->cpu_index] = cur_action;
1298 }
1299 break;
1300 }
1301 }
1302 gdbserver_state.signal = signal;
1303 gdb_continue_partial(newstates);
1304
1305 out:
1306 g_free(newstates);
1307
1308 return res;
1309 }
1310
1311 typedef union GdbCmdVariant {
1312 const char *data;
1313 uint8_t opcode;
1314 unsigned long val_ul;
1315 unsigned long long val_ull;
1316 struct {
1317 GDBThreadIdKind kind;
1318 uint32_t pid;
1319 uint32_t tid;
1320 } thread_id;
1321 } GdbCmdVariant;
1322
1323 static const char *cmd_next_param(const char *param, const char delimiter)
1324 {
1325 static const char all_delimiters[] = ",;:=";
1326 char curr_delimiters[2] = {0};
1327 const char *delimiters;
1328
1329 if (delimiter == '?') {
1330 delimiters = all_delimiters;
1331 } else if (delimiter == '0') {
1332 return strchr(param, '\0');
1333 } else if (delimiter == '.' && *param) {
1334 return param + 1;
1335 } else {
1336 curr_delimiters[0] = delimiter;
1337 delimiters = curr_delimiters;
1338 }
1339
1340 param += strcspn(param, delimiters);
1341 if (*param) {
1342 param++;
1343 }
1344 return param;
1345 }
1346
1347 static int cmd_parse_params(const char *data, const char *schema,
1348 GdbCmdVariant *params, int *num_params)
1349 {
1350 int curr_param;
1351 const char *curr_schema, *curr_data;
1352
1353 *num_params = 0;
1354
1355 if (!schema) {
1356 return 0;
1357 }
1358
1359 curr_schema = schema;
1360 curr_param = 0;
1361 curr_data = data;
1362 while (curr_schema[0] && curr_schema[1] && *curr_data) {
1363 switch (curr_schema[0]) {
1364 case 'l':
1365 if (qemu_strtoul(curr_data, &curr_data, 16,
1366 &params[curr_param].val_ul)) {
1367 return -EINVAL;
1368 }
1369 curr_param++;
1370 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1371 break;
1372 case 'L':
1373 if (qemu_strtou64(curr_data, &curr_data, 16,
1374 (uint64_t *)&params[curr_param].val_ull)) {
1375 return -EINVAL;
1376 }
1377 curr_param++;
1378 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1379 break;
1380 case 's':
1381 params[curr_param].data = curr_data;
1382 curr_param++;
1383 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1384 break;
1385 case 'o':
1386 params[curr_param].opcode = *(uint8_t *)curr_data;
1387 curr_param++;
1388 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1389 break;
1390 case 't':
1391 params[curr_param].thread_id.kind =
1392 read_thread_id(curr_data, &curr_data,
1393 &params[curr_param].thread_id.pid,
1394 &params[curr_param].thread_id.tid);
1395 curr_param++;
1396 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1397 break;
1398 case '?':
1399 curr_data = cmd_next_param(curr_data, curr_schema[1]);
1400 break;
1401 default:
1402 return -EINVAL;
1403 }
1404 curr_schema += 2;
1405 }
1406
1407 *num_params = curr_param;
1408 return 0;
1409 }
1410
1411 typedef struct GdbCmdContext {
1412 GdbCmdVariant *params;
1413 int num_params;
1414 uint8_t mem_buf[MAX_PACKET_LENGTH];
1415 char str_buf[MAX_PACKET_LENGTH + 1];
1416 } GdbCmdContext;
1417
1418 typedef void (*GdbCmdHandler)(GdbCmdContext *gdb_ctx, void *user_ctx);
1419
1420 /*
1421 * cmd_startswith -> cmd is compared using startswith
1422 *
1423 *
1424 * schema definitions:
1425 * Each schema parameter entry consists of 2 chars,
1426 * the first char represents the parameter type handling
1427 * the second char represents the delimiter for the next parameter
1428 *
1429 * Currently supported schema types:
1430 * 'l' -> unsigned long (stored in .val_ul)
1431 * 'L' -> unsigned long long (stored in .val_ull)
1432 * 's' -> string (stored in .data)
1433 * 'o' -> single char (stored in .opcode)
1434 * 't' -> thread id (stored in .thread_id)
1435 * '?' -> skip according to delimiter
1436 *
1437 * Currently supported delimiters:
1438 * '?' -> Stop at any delimiter (",;:=\0")
1439 * '0' -> Stop at "\0"
1440 * '.' -> Skip 1 char unless reached "\0"
1441 * Any other value is treated as the delimiter value itself
1442 */
1443 typedef struct GdbCmdParseEntry {
1444 GdbCmdHandler handler;
1445 const char *cmd;
1446 bool cmd_startswith;
1447 const char *schema;
1448 } GdbCmdParseEntry;
1449
1450 static inline int startswith(const char *string, const char *pattern)
1451 {
1452 return !strncmp(string, pattern, strlen(pattern));
1453 }
1454
1455 static int process_string_cmd(void *user_ctx, const char *data,
1456 const GdbCmdParseEntry *cmds, int num_cmds)
1457 {
1458 int i, schema_len, max_num_params = 0;
1459 GdbCmdContext gdb_ctx;
1460
1461 if (!cmds) {
1462 return -1;
1463 }
1464
1465 for (i = 0; i < num_cmds; i++) {
1466 const GdbCmdParseEntry *cmd = &cmds[i];
1467 g_assert(cmd->handler && cmd->cmd);
1468
1469 if ((cmd->cmd_startswith && !startswith(data, cmd->cmd)) ||
1470 (!cmd->cmd_startswith && strcmp(cmd->cmd, data))) {
1471 continue;
1472 }
1473
1474 if (cmd->schema) {
1475 schema_len = strlen(cmd->schema);
1476 if (schema_len % 2) {
1477 return -2;
1478 }
1479
1480 max_num_params = schema_len / 2;
1481 }
1482
1483 gdb_ctx.params =
1484 (GdbCmdVariant *)alloca(sizeof(*gdb_ctx.params) * max_num_params);
1485 memset(gdb_ctx.params, 0, sizeof(*gdb_ctx.params) * max_num_params);
1486
1487 if (cmd_parse_params(&data[strlen(cmd->cmd)], cmd->schema,
1488 gdb_ctx.params, &gdb_ctx.num_params)) {
1489 return -1;
1490 }
1491
1492 cmd->handler(&gdb_ctx, user_ctx);
1493 return 0;
1494 }
1495
1496 return -1;
1497 }
1498
1499 static void run_cmd_parser(const char *data, const GdbCmdParseEntry *cmd)
1500 {
1501 if (!data) {
1502 return;
1503 }
1504
1505 /* In case there was an error during the command parsing we must
1506 * send a NULL packet to indicate the command is not supported */
1507 if (process_string_cmd(NULL, data, cmd, 1)) {
1508 put_packet("");
1509 }
1510 }
1511
1512 static void handle_detach(GdbCmdContext *gdb_ctx, void *user_ctx)
1513 {
1514 GDBProcess *process;
1515 uint32_t pid = 1;
1516
1517 if (gdbserver_state.multiprocess) {
1518 if (!gdb_ctx->num_params) {
1519 put_packet("E22");
1520 return;
1521 }
1522
1523 pid = gdb_ctx->params[0].val_ul;
1524 }
1525
1526 process = gdb_get_process(pid);
1527 gdb_process_breakpoint_remove_all(process);
1528 process->attached = false;
1529
1530 if (pid == gdb_get_cpu_pid(gdbserver_state.c_cpu)) {
1531 gdbserver_state.c_cpu = gdb_first_attached_cpu();
1532 }
1533
1534 if (pid == gdb_get_cpu_pid(gdbserver_state.g_cpu)) {
1535 gdbserver_state.g_cpu = gdb_first_attached_cpu();
1536 }
1537
1538 if (!gdbserver_state.c_cpu) {
1539 /* No more process attached */
1540 gdb_syscall_mode = GDB_SYS_DISABLED;
1541 gdb_continue();
1542 }
1543 put_packet("OK");
1544 }
1545
1546 static void handle_thread_alive(GdbCmdContext *gdb_ctx, void *user_ctx)
1547 {
1548 CPUState *cpu;
1549
1550 if (!gdb_ctx->num_params) {
1551 put_packet("E22");
1552 return;
1553 }
1554
1555 if (gdb_ctx->params[0].thread_id.kind == GDB_READ_THREAD_ERR) {
1556 put_packet("E22");
1557 return;
1558 }
1559
1560 cpu = gdb_get_cpu(gdb_ctx->params[0].thread_id.pid,
1561 gdb_ctx->params[0].thread_id.tid);
1562 if (!cpu) {
1563 put_packet("E22");
1564 return;
1565 }
1566
1567 put_packet("OK");
1568 }
1569
1570 static void handle_continue(GdbCmdContext *gdb_ctx, void *user_ctx)
1571 {
1572 if (gdb_ctx->num_params) {
1573 gdb_set_cpu_pc(gdb_ctx->params[0].val_ull);
1574 }
1575
1576 gdbserver_state.signal = 0;
1577 gdb_continue();
1578 }
1579
1580 static void handle_cont_with_sig(GdbCmdContext *gdb_ctx, void *user_ctx)
1581 {
1582 unsigned long signal = 0;
1583
1584 /*
1585 * Note: C sig;[addr] is currently unsupported and we simply
1586 * omit the addr parameter
1587 */
1588 if (gdb_ctx->num_params) {
1589 signal = gdb_ctx->params[0].val_ul;
1590 }
1591
1592 gdbserver_state.signal = gdb_signal_to_target(signal);
1593 if (gdbserver_state.signal == -1) {
1594 gdbserver_state.signal = 0;
1595 }
1596 gdb_continue();
1597 }
1598
1599 static void handle_set_thread(GdbCmdContext *gdb_ctx, void *user_ctx)
1600 {
1601 CPUState *cpu;
1602
1603 if (gdb_ctx->num_params != 2) {
1604 put_packet("E22");
1605 return;
1606 }
1607
1608 if (gdb_ctx->params[1].thread_id.kind == GDB_READ_THREAD_ERR) {
1609 put_packet("E22");
1610 return;
1611 }
1612
1613 if (gdb_ctx->params[1].thread_id.kind != GDB_ONE_THREAD) {
1614 put_packet("OK");
1615 return;
1616 }
1617
1618 cpu = gdb_get_cpu(gdb_ctx->params[1].thread_id.pid,
1619 gdb_ctx->params[1].thread_id.tid);
1620 if (!cpu) {
1621 put_packet("E22");
1622 return;
1623 }
1624
1625 /*
1626 * Note: This command is deprecated and modern gdb's will be using the
1627 * vCont command instead.
1628 */
1629 switch (gdb_ctx->params[0].opcode) {
1630 case 'c':
1631 gdbserver_state.c_cpu = cpu;
1632 put_packet("OK");
1633 break;
1634 case 'g':
1635 gdbserver_state.g_cpu = cpu;
1636 put_packet("OK");
1637 break;
1638 default:
1639 put_packet("E22");
1640 break;
1641 }
1642 }
1643
1644 static void handle_insert_bp(GdbCmdContext *gdb_ctx, void *user_ctx)
1645 {
1646 int res;
1647
1648 if (gdb_ctx->num_params != 3) {
1649 put_packet("E22");
1650 return;
1651 }
1652
1653 res = gdb_breakpoint_insert(gdb_ctx->params[0].val_ul,
1654 gdb_ctx->params[1].val_ull,
1655 gdb_ctx->params[2].val_ull);
1656 if (res >= 0) {
1657 put_packet("OK");
1658 return;
1659 } else if (res == -ENOSYS) {
1660 put_packet("");
1661 return;
1662 }
1663
1664 put_packet("E22");
1665 }
1666
1667 static void handle_remove_bp(GdbCmdContext *gdb_ctx, void *user_ctx)
1668 {
1669 int res;
1670
1671 if (gdb_ctx->num_params != 3) {
1672 put_packet("E22");
1673 return;
1674 }
1675
1676 res = gdb_breakpoint_remove(gdb_ctx->params[0].val_ul,
1677 gdb_ctx->params[1].val_ull,
1678 gdb_ctx->params[2].val_ull);
1679 if (res >= 0) {
1680 put_packet("OK");
1681 return;
1682 } else if (res == -ENOSYS) {
1683 put_packet("");
1684 return;
1685 }
1686
1687 put_packet("E22");
1688 }
1689
1690 /*
1691 * handle_set/get_reg
1692 *
1693 * Older gdb are really dumb, and don't use 'G/g' if 'P/p' is available.
1694 * This works, but can be very slow. Anything new enough to understand
1695 * XML also knows how to use this properly. However to use this we
1696 * need to define a local XML file as well as be talking to a
1697 * reasonably modern gdb. Responding with an empty packet will cause
1698 * the remote gdb to fallback to older methods.
1699 */
1700
1701 static void handle_set_reg(GdbCmdContext *gdb_ctx, void *user_ctx)
1702 {
1703 int reg_size;
1704
1705 if (!gdb_has_xml) {
1706 put_packet("");
1707 return;
1708 }
1709
1710 if (gdb_ctx->num_params != 2) {
1711 put_packet("E22");
1712 return;
1713 }
1714
1715 reg_size = strlen(gdb_ctx->params[1].data) / 2;
1716 hextomem(gdb_ctx->mem_buf, gdb_ctx->params[1].data, reg_size);
1717 gdb_write_register(gdbserver_state.g_cpu, gdb_ctx->mem_buf,
1718 gdb_ctx->params[0].val_ull);
1719 put_packet("OK");
1720 }
1721
1722 static void handle_get_reg(GdbCmdContext *gdb_ctx, void *user_ctx)
1723 {
1724 int reg_size;
1725
1726 if (!gdb_has_xml) {
1727 put_packet("");
1728 return;
1729 }
1730
1731 if (!gdb_ctx->num_params) {
1732 put_packet("E14");
1733 return;
1734 }
1735
1736 reg_size = gdb_read_register(gdbserver_state.g_cpu, gdb_ctx->mem_buf,
1737 gdb_ctx->params[0].val_ull);
1738 if (!reg_size) {
1739 put_packet("E14");
1740 return;
1741 }
1742
1743 memtohex(gdb_ctx->str_buf, gdb_ctx->mem_buf, reg_size);
1744 put_packet(gdb_ctx->str_buf);
1745 }
1746
1747 static void handle_write_mem(GdbCmdContext *gdb_ctx, void *user_ctx)
1748 {
1749 if (gdb_ctx->num_params != 3) {
1750 put_packet("E22");
1751 return;
1752 }
1753
1754 /* hextomem() reads 2*len bytes */
1755 if (gdb_ctx->params[1].val_ull > strlen(gdb_ctx->params[2].data) / 2) {
1756 put_packet("E22");
1757 return;
1758 }
1759
1760 hextomem(gdb_ctx->mem_buf, gdb_ctx->params[2].data,
1761 gdb_ctx->params[1].val_ull);
1762 if (target_memory_rw_debug(gdbserver_state.g_cpu, gdb_ctx->params[0].val_ull,
1763 gdb_ctx->mem_buf,
1764 gdb_ctx->params[1].val_ull, true)) {
1765 put_packet("E14");
1766 return;
1767 }
1768
1769 put_packet("OK");
1770 }
1771
1772 static void handle_read_mem(GdbCmdContext *gdb_ctx, void *user_ctx)
1773 {
1774 if (gdb_ctx->num_params != 2) {
1775 put_packet("E22");
1776 return;
1777 }
1778
1779 /* memtohex() doubles the required space */
1780 if (gdb_ctx->params[1].val_ull > MAX_PACKET_LENGTH / 2) {
1781 put_packet("E22");
1782 return;
1783 }
1784
1785 if (target_memory_rw_debug(gdbserver_state.g_cpu, gdb_ctx->params[0].val_ull,
1786 gdb_ctx->mem_buf,
1787 gdb_ctx->params[1].val_ull, false)) {
1788 put_packet("E14");
1789 return;
1790 }
1791
1792 memtohex(gdb_ctx->str_buf, gdb_ctx->mem_buf, gdb_ctx->params[1].val_ull);
1793 put_packet(gdb_ctx->str_buf);
1794 }
1795
1796 static void handle_write_all_regs(GdbCmdContext *gdb_ctx, void *user_ctx)
1797 {
1798 target_ulong addr, len;
1799 uint8_t *registers;
1800 int reg_size;
1801
1802 if (!gdb_ctx->num_params) {
1803 return;
1804 }
1805
1806 cpu_synchronize_state(gdbserver_state.g_cpu);
1807 registers = gdb_ctx->mem_buf;
1808 len = strlen(gdb_ctx->params[0].data) / 2;
1809 hextomem(registers, gdb_ctx->params[0].data, len);
1810 for (addr = 0; addr < gdbserver_state.g_cpu->gdb_num_g_regs && len > 0;
1811 addr++) {
1812 reg_size = gdb_write_register(gdbserver_state.g_cpu, registers, addr);
1813 len -= reg_size;
1814 registers += reg_size;
1815 }
1816 put_packet("OK");
1817 }
1818
1819 static void handle_read_all_regs(GdbCmdContext *gdb_ctx, void *user_ctx)
1820 {
1821 target_ulong addr, len;
1822
1823 cpu_synchronize_state(gdbserver_state.g_cpu);
1824 len = 0;
1825 for (addr = 0; addr < gdbserver_state.g_cpu->gdb_num_g_regs; addr++) {
1826 len += gdb_read_register(gdbserver_state.g_cpu, gdb_ctx->mem_buf + len,
1827 addr);
1828 }
1829
1830 memtohex(gdb_ctx->str_buf, gdb_ctx->mem_buf, len);
1831 put_packet(gdb_ctx->str_buf);
1832 }
1833
1834 static void handle_file_io(GdbCmdContext *gdb_ctx, void *user_ctx)
1835 {
1836 if (gdb_ctx->num_params >= 1 && gdbserver_state.current_syscall_cb) {
1837 target_ulong ret, err;
1838
1839 ret = (target_ulong)gdb_ctx->params[0].val_ull;
1840 if (gdb_ctx->num_params >= 2) {
1841 err = (target_ulong)gdb_ctx->params[1].val_ull;
1842 } else {
1843 err = 0;
1844 }
1845 gdbserver_state.current_syscall_cb(gdbserver_state.c_cpu, ret, err);
1846 gdbserver_state.current_syscall_cb = NULL;
1847 }
1848
1849 if (gdb_ctx->num_params >= 3 && gdb_ctx->params[2].opcode == (uint8_t)'C') {
1850 put_packet("T02");
1851 return;
1852 }
1853
1854 gdb_continue();
1855 }
1856
1857 static void handle_step(GdbCmdContext *gdb_ctx, void *user_ctx)
1858 {
1859 if (gdb_ctx->num_params) {
1860 gdb_set_cpu_pc((target_ulong)gdb_ctx->params[0].val_ull);
1861 }
1862
1863 cpu_single_step(gdbserver_state.c_cpu, sstep_flags);
1864 gdb_continue();
1865 }
1866
1867 static void handle_v_cont_query(GdbCmdContext *gdb_ctx, void *user_ctx)
1868 {
1869 put_packet("vCont;c;C;s;S");
1870 }
1871
1872 static void handle_v_cont(GdbCmdContext *gdb_ctx, void *user_ctx)
1873 {
1874 int res;
1875
1876 if (!gdb_ctx->num_params) {
1877 return;
1878 }
1879
1880 res = gdb_handle_vcont(gdb_ctx->params[0].data);
1881 if ((res == -EINVAL) || (res == -ERANGE)) {
1882 put_packet("E22");
1883 } else if (res) {
1884 put_packet("");
1885 }
1886 }
1887
1888 static void handle_v_attach(GdbCmdContext *gdb_ctx, void *user_ctx)
1889 {
1890 GDBProcess *process;
1891 CPUState *cpu;
1892 char thread_id[16];
1893
1894 pstrcpy(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "E22");
1895 if (!gdb_ctx->num_params) {
1896 goto cleanup;
1897 }
1898
1899 process = gdb_get_process(gdb_ctx->params[0].val_ul);
1900 if (!process) {
1901 goto cleanup;
1902 }
1903
1904 cpu = get_first_cpu_in_process(process);
1905 if (!cpu) {
1906 goto cleanup;
1907 }
1908
1909 process->attached = true;
1910 gdbserver_state.g_cpu = cpu;
1911 gdbserver_state.c_cpu = cpu;
1912
1913 gdb_fmt_thread_id(cpu, thread_id, sizeof(thread_id));
1914 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "T%02xthread:%s;",
1915 GDB_SIGNAL_TRAP, thread_id);
1916 cleanup:
1917 put_packet(gdb_ctx->str_buf);
1918 }
1919
1920 static void handle_v_kill(GdbCmdContext *gdb_ctx, void *user_ctx)
1921 {
1922 /* Kill the target */
1923 put_packet("OK");
1924 error_report("QEMU: Terminated via GDBstub");
1925 exit(0);
1926 }
1927
1928 static GdbCmdParseEntry gdb_v_commands_table[] = {
1929 /* Order is important if has same prefix */
1930 {
1931 .handler = handle_v_cont_query,
1932 .cmd = "Cont?",
1933 .cmd_startswith = 1
1934 },
1935 {
1936 .handler = handle_v_cont,
1937 .cmd = "Cont",
1938 .cmd_startswith = 1,
1939 .schema = "s0"
1940 },
1941 {
1942 .handler = handle_v_attach,
1943 .cmd = "Attach;",
1944 .cmd_startswith = 1,
1945 .schema = "l0"
1946 },
1947 {
1948 .handler = handle_v_kill,
1949 .cmd = "Kill;",
1950 .cmd_startswith = 1
1951 },
1952 };
1953
1954 static void handle_v_commands(GdbCmdContext *gdb_ctx, void *user_ctx)
1955 {
1956 if (!gdb_ctx->num_params) {
1957 return;
1958 }
1959
1960 if (process_string_cmd(NULL, gdb_ctx->params[0].data,
1961 gdb_v_commands_table,
1962 ARRAY_SIZE(gdb_v_commands_table))) {
1963 put_packet("");
1964 }
1965 }
1966
1967 static void handle_query_qemu_sstepbits(GdbCmdContext *gdb_ctx, void *user_ctx)
1968 {
1969 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf),
1970 "ENABLE=%x,NOIRQ=%x,NOTIMER=%x", SSTEP_ENABLE,
1971 SSTEP_NOIRQ, SSTEP_NOTIMER);
1972 put_packet(gdb_ctx->str_buf);
1973 }
1974
1975 static void handle_set_qemu_sstep(GdbCmdContext *gdb_ctx, void *user_ctx)
1976 {
1977 if (!gdb_ctx->num_params) {
1978 return;
1979 }
1980
1981 sstep_flags = gdb_ctx->params[0].val_ul;
1982 put_packet("OK");
1983 }
1984
1985 static void handle_query_qemu_sstep(GdbCmdContext *gdb_ctx, void *user_ctx)
1986 {
1987 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "0x%x", sstep_flags);
1988 put_packet(gdb_ctx->str_buf);
1989 }
1990
1991 static void handle_query_curr_tid(GdbCmdContext *gdb_ctx, void *user_ctx)
1992 {
1993 CPUState *cpu;
1994 GDBProcess *process;
1995 char thread_id[16];
1996
1997 /*
1998 * "Current thread" remains vague in the spec, so always return
1999 * the first thread of the current process (gdb returns the
2000 * first thread).
2001 */
2002 process = gdb_get_cpu_process(gdbserver_state.g_cpu);
2003 cpu = get_first_cpu_in_process(process);
2004 gdb_fmt_thread_id(cpu, thread_id, sizeof(thread_id));
2005 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "QC%s", thread_id);
2006 put_packet(gdb_ctx->str_buf);
2007 }
2008
2009 static void handle_query_threads(GdbCmdContext *gdb_ctx, void *user_ctx)
2010 {
2011 char thread_id[16];
2012
2013 if (!gdbserver_state.query_cpu) {
2014 put_packet("l");
2015 return;
2016 }
2017
2018 gdb_fmt_thread_id(gdbserver_state.query_cpu, thread_id,
2019 sizeof(thread_id));
2020 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "m%s", thread_id);
2021 put_packet(gdb_ctx->str_buf);
2022 gdbserver_state.query_cpu = gdb_next_attached_cpu(gdbserver_state.query_cpu);
2023 }
2024
2025 static void handle_query_first_threads(GdbCmdContext *gdb_ctx, void *user_ctx)
2026 {
2027 gdbserver_state.query_cpu = gdb_first_attached_cpu();
2028 handle_query_threads(gdb_ctx, user_ctx);
2029 }
2030
2031 static void handle_query_thread_extra(GdbCmdContext *gdb_ctx, void *user_ctx)
2032 {
2033 CPUState *cpu;
2034 int len;
2035
2036 if (!gdb_ctx->num_params ||
2037 gdb_ctx->params[0].thread_id.kind == GDB_READ_THREAD_ERR) {
2038 put_packet("E22");
2039 return;
2040 }
2041
2042 cpu = gdb_get_cpu(gdb_ctx->params[0].thread_id.pid,
2043 gdb_ctx->params[0].thread_id.tid);
2044 if (!cpu) {
2045 return;
2046 }
2047
2048 cpu_synchronize_state(cpu);
2049
2050 if (gdbserver_state.multiprocess && (gdbserver_state.process_num > 1)) {
2051 /* Print the CPU model and name in multiprocess mode */
2052 ObjectClass *oc = object_get_class(OBJECT(cpu));
2053 const char *cpu_model = object_class_get_name(oc);
2054 char *cpu_name = object_get_canonical_path_component(OBJECT(cpu));
2055 len = snprintf((char *)gdb_ctx->mem_buf, sizeof(gdb_ctx->str_buf) / 2,
2056 "%s %s [%s]", cpu_model, cpu_name,
2057 cpu->halted ? "halted " : "running");
2058 g_free(cpu_name);
2059 } else {
2060 /* memtohex() doubles the required space */
2061 len = snprintf((char *)gdb_ctx->mem_buf, sizeof(gdb_ctx->str_buf) / 2,
2062 "CPU#%d [%s]", cpu->cpu_index,
2063 cpu->halted ? "halted " : "running");
2064 }
2065 trace_gdbstub_op_extra_info((char *)gdb_ctx->mem_buf);
2066 memtohex(gdb_ctx->str_buf, gdb_ctx->mem_buf, len);
2067 put_packet(gdb_ctx->str_buf);
2068 }
2069
2070 #ifdef CONFIG_USER_ONLY
2071 static void handle_query_offsets(GdbCmdContext *gdb_ctx, void *user_ctx)
2072 {
2073 TaskState *ts;
2074
2075 ts = gdbserver_state.c_cpu->opaque;
2076 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf),
2077 "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
2078 ";Bss=" TARGET_ABI_FMT_lx,
2079 ts->info->code_offset,
2080 ts->info->data_offset,
2081 ts->info->data_offset);
2082 put_packet(gdb_ctx->str_buf);
2083 }
2084 #else
2085 static void handle_query_rcmd(GdbCmdContext *gdb_ctx, void *user_ctx)
2086 {
2087 int len;
2088
2089 if (!gdb_ctx->num_params) {
2090 put_packet("E22");
2091 return;
2092 }
2093
2094 len = strlen(gdb_ctx->params[0].data);
2095 if (len % 2) {
2096 put_packet("E01");
2097 return;
2098 }
2099
2100 len = len / 2;
2101 hextomem(gdb_ctx->mem_buf, gdb_ctx->params[0].data, len);
2102 gdb_ctx->mem_buf[len++] = 0;
2103 qemu_chr_be_write(gdbserver_state.mon_chr, gdb_ctx->mem_buf, len);
2104 put_packet("OK");
2105
2106 }
2107 #endif
2108
2109 static void handle_query_supported(GdbCmdContext *gdb_ctx, void *user_ctx)
2110 {
2111 CPUClass *cc;
2112
2113 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "PacketSize=%x",
2114 MAX_PACKET_LENGTH);
2115 cc = CPU_GET_CLASS(first_cpu);
2116 if (cc->gdb_core_xml_file) {
2117 pstrcat(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf),
2118 ";qXfer:features:read+");
2119 }
2120
2121 if (gdb_ctx->num_params &&
2122 strstr(gdb_ctx->params[0].data, "multiprocess+")) {
2123 gdbserver_state.multiprocess = true;
2124 }
2125
2126 pstrcat(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), ";multiprocess+");
2127 put_packet(gdb_ctx->str_buf);
2128 }
2129
2130 static void handle_query_xfer_features(GdbCmdContext *gdb_ctx, void *user_ctx)
2131 {
2132 GDBProcess *process;
2133 CPUClass *cc;
2134 unsigned long len, total_len, addr;
2135 const char *xml;
2136 const char *p;
2137
2138 if (gdb_ctx->num_params < 3) {
2139 put_packet("E22");
2140 return;
2141 }
2142
2143 process = gdb_get_cpu_process(gdbserver_state.g_cpu);
2144 cc = CPU_GET_CLASS(gdbserver_state.g_cpu);
2145 if (!cc->gdb_core_xml_file) {
2146 put_packet("");
2147 return;
2148 }
2149
2150 gdb_has_xml = true;
2151 p = gdb_ctx->params[0].data;
2152 xml = get_feature_xml(p, &p, process);
2153 if (!xml) {
2154 put_packet("E00");
2155 return;
2156 }
2157
2158 addr = gdb_ctx->params[1].val_ul;
2159 len = gdb_ctx->params[2].val_ul;
2160 total_len = strlen(xml);
2161 if (addr > total_len) {
2162 put_packet("E00");
2163 return;
2164 }
2165
2166 if (len > (MAX_PACKET_LENGTH - 5) / 2) {
2167 len = (MAX_PACKET_LENGTH - 5) / 2;
2168 }
2169
2170 if (len < total_len - addr) {
2171 gdb_ctx->str_buf[0] = 'm';
2172 len = memtox(gdb_ctx->str_buf + 1, xml + addr, len);
2173 } else {
2174 gdb_ctx->str_buf[0] = 'l';
2175 len = memtox(gdb_ctx->str_buf + 1, xml + addr, total_len - addr);
2176 }
2177
2178 put_packet_binary(gdb_ctx->str_buf, len + 1, true);
2179 }
2180
2181 static void handle_query_attached(GdbCmdContext *gdb_ctx, void *user_ctx)
2182 {
2183 put_packet(GDB_ATTACHED);
2184 }
2185
2186 static void handle_query_qemu_supported(GdbCmdContext *gdb_ctx, void *user_ctx)
2187 {
2188 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "sstepbits;sstep");
2189 #ifndef CONFIG_USER_ONLY
2190 pstrcat(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), ";PhyMemMode");
2191 #endif
2192 put_packet(gdb_ctx->str_buf);
2193 }
2194
2195 #ifndef CONFIG_USER_ONLY
2196 static void handle_query_qemu_phy_mem_mode(GdbCmdContext *gdb_ctx,
2197 void *user_ctx)
2198 {
2199 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "%d", phy_memory_mode);
2200 put_packet(gdb_ctx->str_buf);
2201 }
2202
2203 static void handle_set_qemu_phy_mem_mode(GdbCmdContext *gdb_ctx, void *user_ctx)
2204 {
2205 if (!gdb_ctx->num_params) {
2206 put_packet("E22");
2207 return;
2208 }
2209
2210 if (!gdb_ctx->params[0].val_ul) {
2211 phy_memory_mode = 0;
2212 } else {
2213 phy_memory_mode = 1;
2214 }
2215 put_packet("OK");
2216 }
2217 #endif
2218
2219 static GdbCmdParseEntry gdb_gen_query_set_common_table[] = {
2220 /* Order is important if has same prefix */
2221 {
2222 .handler = handle_query_qemu_sstepbits,
2223 .cmd = "qemu.sstepbits",
2224 },
2225 {
2226 .handler = handle_query_qemu_sstep,
2227 .cmd = "qemu.sstep",
2228 },
2229 {
2230 .handler = handle_set_qemu_sstep,
2231 .cmd = "qemu.sstep=",
2232 .cmd_startswith = 1,
2233 .schema = "l0"
2234 },
2235 };
2236
2237 static GdbCmdParseEntry gdb_gen_query_table[] = {
2238 {
2239 .handler = handle_query_curr_tid,
2240 .cmd = "C",
2241 },
2242 {
2243 .handler = handle_query_threads,
2244 .cmd = "sThreadInfo",
2245 },
2246 {
2247 .handler = handle_query_first_threads,
2248 .cmd = "fThreadInfo",
2249 },
2250 {
2251 .handler = handle_query_thread_extra,
2252 .cmd = "ThreadExtraInfo,",
2253 .cmd_startswith = 1,
2254 .schema = "t0"
2255 },
2256 #ifdef CONFIG_USER_ONLY
2257 {
2258 .handler = handle_query_offsets,
2259 .cmd = "Offsets",
2260 },
2261 #else
2262 {
2263 .handler = handle_query_rcmd,
2264 .cmd = "Rcmd,",
2265 .cmd_startswith = 1,
2266 .schema = "s0"
2267 },
2268 #endif
2269 {
2270 .handler = handle_query_supported,
2271 .cmd = "Supported:",
2272 .cmd_startswith = 1,
2273 .schema = "s0"
2274 },
2275 {
2276 .handler = handle_query_supported,
2277 .cmd = "Supported",
2278 .schema = "s0"
2279 },
2280 {
2281 .handler = handle_query_xfer_features,
2282 .cmd = "Xfer:features:read:",
2283 .cmd_startswith = 1,
2284 .schema = "s:l,l0"
2285 },
2286 {
2287 .handler = handle_query_attached,
2288 .cmd = "Attached:",
2289 .cmd_startswith = 1
2290 },
2291 {
2292 .handler = handle_query_attached,
2293 .cmd = "Attached",
2294 },
2295 {
2296 .handler = handle_query_qemu_supported,
2297 .cmd = "qemu.Supported",
2298 },
2299 #ifndef CONFIG_USER_ONLY
2300 {
2301 .handler = handle_query_qemu_phy_mem_mode,
2302 .cmd = "qemu.PhyMemMode",
2303 },
2304 #endif
2305 };
2306
2307 static GdbCmdParseEntry gdb_gen_set_table[] = {
2308 /* Order is important if has same prefix */
2309 {
2310 .handler = handle_set_qemu_sstep,
2311 .cmd = "qemu.sstep:",
2312 .cmd_startswith = 1,
2313 .schema = "l0"
2314 },
2315 #ifndef CONFIG_USER_ONLY
2316 {
2317 .handler = handle_set_qemu_phy_mem_mode,
2318 .cmd = "qemu.PhyMemMode:",
2319 .cmd_startswith = 1,
2320 .schema = "l0"
2321 },
2322 #endif
2323 };
2324
2325 static void handle_gen_query(GdbCmdContext *gdb_ctx, void *user_ctx)
2326 {
2327 if (!gdb_ctx->num_params) {
2328 return;
2329 }
2330
2331 if (!process_string_cmd(NULL, gdb_ctx->params[0].data,
2332 gdb_gen_query_set_common_table,
2333 ARRAY_SIZE(gdb_gen_query_set_common_table))) {
2334 return;
2335 }
2336
2337 if (process_string_cmd(NULL, gdb_ctx->params[0].data,
2338 gdb_gen_query_table,
2339 ARRAY_SIZE(gdb_gen_query_table))) {
2340 put_packet("");
2341 }
2342 }
2343
2344 static void handle_gen_set(GdbCmdContext *gdb_ctx, void *user_ctx)
2345 {
2346 if (!gdb_ctx->num_params) {
2347 return;
2348 }
2349
2350 if (!process_string_cmd(NULL, gdb_ctx->params[0].data,
2351 gdb_gen_query_set_common_table,
2352 ARRAY_SIZE(gdb_gen_query_set_common_table))) {
2353 return;
2354 }
2355
2356 if (process_string_cmd(NULL, gdb_ctx->params[0].data,
2357 gdb_gen_set_table,
2358 ARRAY_SIZE(gdb_gen_set_table))) {
2359 put_packet("");
2360 }
2361 }
2362
2363 static void handle_target_halt(GdbCmdContext *gdb_ctx, void *user_ctx)
2364 {
2365 char thread_id[16];
2366
2367 gdb_fmt_thread_id(gdbserver_state.c_cpu, thread_id,
2368 sizeof(thread_id));
2369 snprintf(gdb_ctx->str_buf, sizeof(gdb_ctx->str_buf), "T%02xthread:%s;",
2370 GDB_SIGNAL_TRAP, thread_id);
2371 put_packet(gdb_ctx->str_buf);
2372 /*
2373 * Remove all the breakpoints when this query is issued,
2374 * because gdb is doing an initial connect and the state
2375 * should be cleaned up.
2376 */
2377 gdb_breakpoint_remove_all();
2378 }
2379
2380 static int gdb_handle_packet(const char *line_buf)
2381 {
2382 const GdbCmdParseEntry *cmd_parser = NULL;
2383
2384 trace_gdbstub_io_command(line_buf);
2385
2386 switch (line_buf[0]) {
2387 case '!':
2388 put_packet("OK");
2389 break;
2390 case '?':
2391 {
2392 static const GdbCmdParseEntry target_halted_cmd_desc = {
2393 .handler = handle_target_halt,
2394 .cmd = "?",
2395 .cmd_startswith = 1
2396 };
2397 cmd_parser = &target_halted_cmd_desc;
2398 }
2399 break;
2400 case 'c':
2401 {
2402 static const GdbCmdParseEntry continue_cmd_desc = {
2403 .handler = handle_continue,
2404 .cmd = "c",
2405 .cmd_startswith = 1,
2406 .schema = "L0"
2407 };
2408 cmd_parser = &continue_cmd_desc;
2409 }
2410 break;
2411 case 'C':
2412 {
2413 static const GdbCmdParseEntry cont_with_sig_cmd_desc = {
2414 .handler = handle_cont_with_sig,
2415 .cmd = "C",
2416 .cmd_startswith = 1,
2417 .schema = "l0"
2418 };
2419 cmd_parser = &cont_with_sig_cmd_desc;
2420 }
2421 break;
2422 case 'v':
2423 {
2424 static const GdbCmdParseEntry v_cmd_desc = {
2425 .handler = handle_v_commands,
2426 .cmd = "v",
2427 .cmd_startswith = 1,
2428 .schema = "s0"
2429 };
2430 cmd_parser = &v_cmd_desc;
2431 }
2432 break;
2433 case 'k':
2434 /* Kill the target */
2435 error_report("QEMU: Terminated via GDBstub");
2436 exit(0);
2437 case 'D':
2438 {
2439 static const GdbCmdParseEntry detach_cmd_desc = {
2440 .handler = handle_detach,
2441 .cmd = "D",
2442 .cmd_startswith = 1,
2443 .schema = "?.l0"
2444 };
2445 cmd_parser = &detach_cmd_desc;
2446 }
2447 break;
2448 case 's':
2449 {
2450 static const GdbCmdParseEntry step_cmd_desc = {
2451 .handler = handle_step,
2452 .cmd = "s",
2453 .cmd_startswith = 1,
2454 .schema = "L0"
2455 };
2456 cmd_parser = &step_cmd_desc;
2457 }
2458 break;
2459 case 'F':
2460 {
2461 static const GdbCmdParseEntry file_io_cmd_desc = {
2462 .handler = handle_file_io,
2463 .cmd = "F",
2464 .cmd_startswith = 1,
2465 .schema = "L,L,o0"
2466 };
2467 cmd_parser = &file_io_cmd_desc;
2468 }
2469 break;
2470 case 'g':
2471 {
2472 static const GdbCmdParseEntry read_all_regs_cmd_desc = {
2473 .handler = handle_read_all_regs,
2474 .cmd = "g",
2475 .cmd_startswith = 1
2476 };
2477 cmd_parser = &read_all_regs_cmd_desc;
2478 }
2479 break;
2480 case 'G':
2481 {
2482 static const GdbCmdParseEntry write_all_regs_cmd_desc = {
2483 .handler = handle_write_all_regs,
2484 .cmd = "G",
2485 .cmd_startswith = 1,
2486 .schema = "s0"
2487 };
2488 cmd_parser = &write_all_regs_cmd_desc;
2489 }
2490 break;
2491 case 'm':
2492 {
2493 static const GdbCmdParseEntry read_mem_cmd_desc = {
2494 .handler = handle_read_mem,
2495 .cmd = "m",
2496 .cmd_startswith = 1,
2497 .schema = "L,L0"
2498 };
2499 cmd_parser = &read_mem_cmd_desc;
2500 }
2501 break;
2502 case 'M':
2503 {
2504 static const GdbCmdParseEntry write_mem_cmd_desc = {
2505 .handler = handle_write_mem,
2506 .cmd = "M",
2507 .cmd_startswith = 1,
2508 .schema = "L,L:s0"
2509 };
2510 cmd_parser = &write_mem_cmd_desc;
2511 }
2512 break;
2513 case 'p':
2514 {
2515 static const GdbCmdParseEntry get_reg_cmd_desc = {
2516 .handler = handle_get_reg,
2517 .cmd = "p",
2518 .cmd_startswith = 1,
2519 .schema = "L0"
2520 };
2521 cmd_parser = &get_reg_cmd_desc;
2522 }
2523 break;
2524 case 'P':
2525 {
2526 static const GdbCmdParseEntry set_reg_cmd_desc = {
2527 .handler = handle_set_reg,
2528 .cmd = "P",
2529 .cmd_startswith = 1,
2530 .schema = "L?s0"
2531 };
2532 cmd_parser = &set_reg_cmd_desc;
2533 }
2534 break;
2535 case 'Z':
2536 {
2537 static const GdbCmdParseEntry insert_bp_cmd_desc = {
2538 .handler = handle_insert_bp,
2539 .cmd = "Z",
2540 .cmd_startswith = 1,
2541 .schema = "l?L?L0"
2542 };
2543 cmd_parser = &insert_bp_cmd_desc;
2544 }
2545 break;
2546 case 'z':
2547 {
2548 static const GdbCmdParseEntry remove_bp_cmd_desc = {
2549 .handler = handle_remove_bp,
2550 .cmd = "z",
2551 .cmd_startswith = 1,
2552 .schema = "l?L?L0"
2553 };
2554 cmd_parser = &remove_bp_cmd_desc;
2555 }
2556 break;
2557 case 'H':
2558 {
2559 static const GdbCmdParseEntry set_thread_cmd_desc = {
2560 .handler = handle_set_thread,
2561 .cmd = "H",
2562 .cmd_startswith = 1,
2563 .schema = "o.t0"
2564 };
2565 cmd_parser = &set_thread_cmd_desc;
2566 }
2567 break;
2568 case 'T':
2569 {
2570 static const GdbCmdParseEntry thread_alive_cmd_desc = {
2571 .handler = handle_thread_alive,
2572 .cmd = "T",
2573 .cmd_startswith = 1,
2574 .schema = "t0"
2575 };
2576 cmd_parser = &thread_alive_cmd_desc;
2577 }
2578 break;
2579 case 'q':
2580 {
2581 static const GdbCmdParseEntry gen_query_cmd_desc = {
2582 .handler = handle_gen_query,
2583 .cmd = "q",
2584 .cmd_startswith = 1,
2585 .schema = "s0"
2586 };
2587 cmd_parser = &gen_query_cmd_desc;
2588 }
2589 break;
2590 case 'Q':
2591 {
2592 static const GdbCmdParseEntry gen_set_cmd_desc = {
2593 .handler = handle_gen_set,
2594 .cmd = "Q",
2595 .cmd_startswith = 1,
2596 .schema = "s0"
2597 };
2598 cmd_parser = &gen_set_cmd_desc;
2599 }
2600 break;
2601 default:
2602 /* put empty packet */
2603 put_packet("");
2604 break;
2605 }
2606
2607 if (cmd_parser) {
2608 run_cmd_parser(line_buf, cmd_parser);
2609 }
2610
2611 return RS_IDLE;
2612 }
2613
2614 void gdb_set_stop_cpu(CPUState *cpu)
2615 {
2616 GDBProcess *p = gdb_get_cpu_process(cpu);
2617
2618 if (!p->attached) {
2619 /*
2620 * Having a stop CPU corresponding to a process that is not attached
2621 * confuses GDB. So we ignore the request.
2622 */
2623 return;
2624 }
2625
2626 gdbserver_state.c_cpu = cpu;
2627 gdbserver_state.g_cpu = cpu;
2628 }
2629
2630 #ifndef CONFIG_USER_ONLY
2631 static void gdb_vm_state_change(void *opaque, int running, RunState state)
2632 {
2633 CPUState *cpu = gdbserver_state.c_cpu;
2634 char buf[256];
2635 char thread_id[16];
2636 const char *type;
2637 int ret;
2638
2639 if (running || gdbserver_state.state == RS_INACTIVE) {
2640 return;
2641 }
2642 /* Is there a GDB syscall waiting to be sent? */
2643 if (gdbserver_state.current_syscall_cb) {
2644 put_packet(gdbserver_state.syscall_buf);
2645 return;
2646 }
2647
2648 if (cpu == NULL) {
2649 /* No process attached */
2650 return;
2651 }
2652
2653 gdb_fmt_thread_id(cpu, thread_id, sizeof(thread_id));
2654
2655 switch (state) {
2656 case RUN_STATE_DEBUG:
2657 if (cpu->watchpoint_hit) {
2658 switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
2659 case BP_MEM_READ:
2660 type = "r";
2661 break;
2662 case BP_MEM_ACCESS:
2663 type = "a";
2664 break;
2665 default:
2666 type = "";
2667 break;
2668 }
2669 trace_gdbstub_hit_watchpoint(type, cpu_gdb_index(cpu),
2670 (target_ulong)cpu->watchpoint_hit->vaddr);
2671 snprintf(buf, sizeof(buf),
2672 "T%02xthread:%s;%swatch:" TARGET_FMT_lx ";",
2673 GDB_SIGNAL_TRAP, thread_id, type,
2674 (target_ulong)cpu->watchpoint_hit->vaddr);
2675 cpu->watchpoint_hit = NULL;
2676 goto send_packet;
2677 } else {
2678 trace_gdbstub_hit_break();
2679 }
2680 tb_flush(cpu);
2681 ret = GDB_SIGNAL_TRAP;
2682 break;
2683 case RUN_STATE_PAUSED:
2684 trace_gdbstub_hit_paused();
2685 ret = GDB_SIGNAL_INT;
2686 break;
2687 case RUN_STATE_SHUTDOWN:
2688 trace_gdbstub_hit_shutdown();
2689 ret = GDB_SIGNAL_QUIT;
2690 break;
2691 case RUN_STATE_IO_ERROR:
2692 trace_gdbstub_hit_io_error();
2693 ret = GDB_SIGNAL_IO;
2694 break;
2695 case RUN_STATE_WATCHDOG:
2696 trace_gdbstub_hit_watchdog();
2697 ret = GDB_SIGNAL_ALRM;
2698 break;
2699 case RUN_STATE_INTERNAL_ERROR:
2700 trace_gdbstub_hit_internal_error();
2701 ret = GDB_SIGNAL_ABRT;
2702 break;
2703 case RUN_STATE_SAVE_VM:
2704 case RUN_STATE_RESTORE_VM:
2705 return;
2706 case RUN_STATE_FINISH_MIGRATE:
2707 ret = GDB_SIGNAL_XCPU;
2708 break;
2709 default:
2710 trace_gdbstub_hit_unknown(state);
2711 ret = GDB_SIGNAL_UNKNOWN;
2712 break;
2713 }
2714 gdb_set_stop_cpu(cpu);
2715 snprintf(buf, sizeof(buf), "T%02xthread:%s;", ret, thread_id);
2716
2717 send_packet:
2718 put_packet(buf);
2719
2720 /* disable single step if it was enabled */
2721 cpu_single_step(cpu, 0);
2722 }
2723 #endif
2724
2725 /* Send a gdb syscall request.
2726 This accepts limited printf-style format specifiers, specifically:
2727 %x - target_ulong argument printed in hex.
2728 %lx - 64-bit argument printed in hex.
2729 %s - string pointer (target_ulong) and length (int) pair. */
2730 void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
2731 {
2732 char *p;
2733 char *p_end;
2734 target_ulong addr;
2735 uint64_t i64;
2736
2737 if (!gdbserver_state.init) {
2738 return;
2739 }
2740
2741 gdbserver_state.current_syscall_cb = cb;
2742 #ifndef CONFIG_USER_ONLY
2743 vm_stop(RUN_STATE_DEBUG);
2744 #endif
2745 p = &gdbserver_state.syscall_buf[0];
2746 p_end = &gdbserver_state.syscall_buf[sizeof(gdbserver_state.syscall_buf)];
2747 *(p++) = 'F';
2748 while (*fmt) {
2749 if (*fmt == '%') {
2750 fmt++;
2751 switch (*fmt++) {
2752 case 'x':
2753 addr = va_arg(va, target_ulong);
2754 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
2755 break;
2756 case 'l':
2757 if (*(fmt++) != 'x')
2758 goto bad_format;
2759 i64 = va_arg(va, uint64_t);
2760 p += snprintf(p, p_end - p, "%" PRIx64, i64);
2761 break;
2762 case 's':
2763 addr = va_arg(va, target_ulong);
2764 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
2765 addr, va_arg(va, int));
2766 break;
2767 default:
2768 bad_format:
2769 error_report("gdbstub: Bad syscall format string '%s'",
2770 fmt - 1);
2771 break;
2772 }
2773 } else {
2774 *(p++) = *(fmt++);
2775 }
2776 }
2777 *p = 0;
2778 #ifdef CONFIG_USER_ONLY
2779 put_packet(gdbserver_state.syscall_buf);
2780 /* Return control to gdb for it to process the syscall request.
2781 * Since the protocol requires that gdb hands control back to us
2782 * using a "here are the results" F packet, we don't need to check
2783 * gdb_handlesig's return value (which is the signal to deliver if
2784 * execution was resumed via a continue packet).
2785 */
2786 gdb_handlesig(gdbserver_state.c_cpu, 0);
2787 #else
2788 /* In this case wait to send the syscall packet until notification that
2789 the CPU has stopped. This must be done because if the packet is sent
2790 now the reply from the syscall request could be received while the CPU
2791 is still in the running state, which can cause packets to be dropped
2792 and state transition 'T' packets to be sent while the syscall is still
2793 being processed. */
2794 qemu_cpu_kick(gdbserver_state.c_cpu);
2795 #endif
2796 }
2797
2798 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
2799 {
2800 va_list va;
2801
2802 va_start(va, fmt);
2803 gdb_do_syscallv(cb, fmt, va);
2804 va_end(va);
2805 }
2806
2807 static void gdb_read_byte(uint8_t ch)
2808 {
2809 uint8_t reply;
2810
2811 #ifndef CONFIG_USER_ONLY
2812 if (gdbserver_state.last_packet_len) {
2813 /* Waiting for a response to the last packet. If we see the start
2814 of a new command then abandon the previous response. */
2815 if (ch == '-') {
2816 trace_gdbstub_err_got_nack();
2817 put_buffer((uint8_t *)gdbserver_state.last_packet, gdbserver_state.last_packet_len);
2818 } else if (ch == '+') {
2819 trace_gdbstub_io_got_ack();
2820 } else {
2821 trace_gdbstub_io_got_unexpected(ch);
2822 }
2823
2824 if (ch == '+' || ch == '$')
2825 gdbserver_state.last_packet_len = 0;
2826 if (ch != '$')
2827 return;
2828 }
2829 if (runstate_is_running()) {
2830 /* when the CPU is running, we cannot do anything except stop
2831 it when receiving a char */
2832 vm_stop(RUN_STATE_PAUSED);
2833 } else
2834 #endif
2835 {
2836 switch(gdbserver_state.state) {
2837 case RS_IDLE:
2838 if (ch == '$') {
2839 /* start of command packet */
2840 gdbserver_state.line_buf_index = 0;
2841 gdbserver_state.line_sum = 0;
2842 gdbserver_state.state = RS_GETLINE;
2843 } else {
2844 trace_gdbstub_err_garbage(ch);
2845 }
2846 break;
2847 case RS_GETLINE:
2848 if (ch == '}') {
2849 /* start escape sequence */
2850 gdbserver_state.state = RS_GETLINE_ESC;
2851 gdbserver_state.line_sum += ch;
2852 } else if (ch == '*') {
2853 /* start run length encoding sequence */
2854 gdbserver_state.state = RS_GETLINE_RLE;
2855 gdbserver_state.line_sum += ch;
2856 } else if (ch == '#') {
2857 /* end of command, start of checksum*/
2858 gdbserver_state.state = RS_CHKSUM1;
2859 } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
2860 trace_gdbstub_err_overrun();
2861 gdbserver_state.state = RS_IDLE;
2862 } else {
2863 /* unescaped command character */
2864 gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch;
2865 gdbserver_state.line_sum += ch;
2866 }
2867 break;
2868 case RS_GETLINE_ESC:
2869 if (ch == '#') {
2870 /* unexpected end of command in escape sequence */
2871 gdbserver_state.state = RS_CHKSUM1;
2872 } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
2873 /* command buffer overrun */
2874 trace_gdbstub_err_overrun();
2875 gdbserver_state.state = RS_IDLE;
2876 } else {
2877 /* parse escaped character and leave escape state */
2878 gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch ^ 0x20;
2879 gdbserver_state.line_sum += ch;
2880 gdbserver_state.state = RS_GETLINE;
2881 }
2882 break;
2883 case RS_GETLINE_RLE:
2884 /*
2885 * Run-length encoding is explained in "Debugging with GDB /
2886 * Appendix E GDB Remote Serial Protocol / Overview".
2887 */
2888 if (ch < ' ' || ch == '#' || ch == '$' || ch > 126) {
2889 /* invalid RLE count encoding */
2890 trace_gdbstub_err_invalid_repeat(ch);
2891 gdbserver_state.state = RS_GETLINE;
2892 } else {
2893 /* decode repeat length */
2894 int repeat = ch - ' ' + 3;
2895 if (gdbserver_state.line_buf_index + repeat >= sizeof(gdbserver_state.line_buf) - 1) {
2896 /* that many repeats would overrun the command buffer */
2897 trace_gdbstub_err_overrun();
2898 gdbserver_state.state = RS_IDLE;
2899 } else if (gdbserver_state.line_buf_index < 1) {
2900 /* got a repeat but we have nothing to repeat */
2901 trace_gdbstub_err_invalid_rle();
2902 gdbserver_state.state = RS_GETLINE;
2903 } else {
2904 /* repeat the last character */
2905 memset(gdbserver_state.line_buf + gdbserver_state.line_buf_index,
2906 gdbserver_state.line_buf[gdbserver_state.line_buf_index - 1], repeat);
2907 gdbserver_state.line_buf_index += repeat;
2908 gdbserver_state.line_sum += ch;
2909 gdbserver_state.state = RS_GETLINE;
2910 }
2911 }
2912 break;
2913 case RS_CHKSUM1:
2914 /* get high hex digit of checksum */
2915 if (!isxdigit(ch)) {
2916 trace_gdbstub_err_checksum_invalid(ch);
2917 gdbserver_state.state = RS_GETLINE;
2918 break;
2919 }
2920 gdbserver_state.line_buf[gdbserver_state.line_buf_index] = '\0';
2921 gdbserver_state.line_csum = fromhex(ch) << 4;
2922 gdbserver_state.state = RS_CHKSUM2;
2923 break;
2924 case RS_CHKSUM2:
2925 /* get low hex digit of checksum */
2926 if (!isxdigit(ch)) {
2927 trace_gdbstub_err_checksum_invalid(ch);
2928 gdbserver_state.state = RS_GETLINE;
2929 break;
2930 }
2931 gdbserver_state.line_csum |= fromhex(ch);
2932
2933 if (gdbserver_state.line_csum != (gdbserver_state.line_sum & 0xff)) {
2934 trace_gdbstub_err_checksum_incorrect(gdbserver_state.line_sum, gdbserver_state.line_csum);
2935 /* send NAK reply */
2936 reply = '-';
2937 put_buffer(&reply, 1);
2938 gdbserver_state.state = RS_IDLE;
2939 } else {
2940 /* send ACK reply */
2941 reply = '+';
2942 put_buffer(&reply, 1);
2943 gdbserver_state.state = gdb_handle_packet(gdbserver_state.line_buf);
2944 }
2945 break;
2946 default:
2947 abort();
2948 }
2949 }
2950 }
2951
2952 /* Tell the remote gdb that the process has exited. */
2953 void gdb_exit(CPUArchState *env, int code)
2954 {
2955 char buf[4];
2956
2957 if (!gdbserver_state.init) {
2958 return;
2959 }
2960 #ifdef CONFIG_USER_ONLY
2961 if (gdbserver_fd < 0 || gdbserver_state.fd < 0) {
2962 return;
2963 }
2964 #endif
2965
2966 trace_gdbstub_op_exiting((uint8_t)code);
2967
2968 snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
2969 put_packet(buf);
2970
2971 #ifndef CONFIG_USER_ONLY
2972 qemu_chr_fe_deinit(&gdbserver_state.chr, true);
2973 #endif
2974 }
2975
2976 /*
2977 * Create the process that will contain all the "orphan" CPUs (that are not
2978 * part of a CPU cluster). Note that if this process contains no CPUs, it won't
2979 * be attachable and thus will be invisible to the user.
2980 */
2981 static void create_default_process(GDBState *s)
2982 {
2983 GDBProcess *process;
2984 int max_pid = 0;
2985
2986 if (gdbserver_state.process_num) {
2987 max_pid = s->processes[s->process_num - 1].pid;
2988 }
2989
2990 s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
2991 process = &s->processes[s->process_num - 1];
2992
2993 /* We need an available PID slot for this process */
2994 assert(max_pid < UINT32_MAX);
2995
2996 process->pid = max_pid + 1;
2997 process->attached = false;
2998 process->target_xml[0] = '\0';
2999 }
3000
3001 #ifdef CONFIG_USER_ONLY
3002 int
3003 gdb_handlesig(CPUState *cpu, int sig)
3004 {
3005 char buf[256];
3006 int n;
3007
3008 if (gdbserver_fd < 0 || gdbserver_state.fd < 0) {
3009 return sig;
3010 }
3011
3012 /* disable single step if it was enabled */
3013 cpu_single_step(cpu, 0);
3014 tb_flush(cpu);
3015
3016 if (sig != 0) {
3017 snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
3018 put_packet(buf);
3019 }
3020 /* put_packet() might have detected that the peer terminated the
3021 connection. */
3022 if (gdbserver_state.fd < 0) {
3023 return sig;
3024 }
3025
3026 sig = 0;
3027 gdbserver_state.state = RS_IDLE;
3028 gdbserver_state.running_state = 0;
3029 while (gdbserver_state.running_state == 0) {
3030 n = read(gdbserver_state.fd, buf, 256);
3031 if (n > 0) {
3032 int i;
3033
3034 for (i = 0; i < n; i++) {
3035 gdb_read_byte(buf[i]);
3036 }
3037 } else {
3038 /* XXX: Connection closed. Should probably wait for another
3039 connection before continuing. */
3040 if (n == 0) {
3041 close(gdbserver_state.fd);
3042 }
3043 gdbserver_state.fd = -1;
3044 return sig;
3045 }
3046 }
3047 sig = gdbserver_state.signal;
3048 gdbserver_state.signal = 0;
3049 return sig;
3050 }
3051
3052 /* Tell the remote gdb that the process has exited due to SIG. */
3053 void gdb_signalled(CPUArchState *env, int sig)
3054 {
3055 char buf[4];
3056
3057 if (gdbserver_fd < 0 || gdbserver_state.fd < 0) {
3058 return;
3059 }
3060
3061 snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
3062 put_packet(buf);
3063 }
3064
3065 static bool gdb_accept(void)
3066 {
3067 struct sockaddr_in sockaddr;
3068 socklen_t len;
3069 int fd;
3070
3071 for(;;) {
3072 len = sizeof(sockaddr);
3073 fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
3074 if (fd < 0 && errno != EINTR) {
3075 perror("accept");
3076 return false;
3077 } else if (fd >= 0) {
3078 qemu_set_cloexec(fd);
3079 break;
3080 }
3081 }
3082
3083 /* set short latency */
3084 if (socket_set_nodelay(fd)) {
3085 perror("setsockopt");
3086 close(fd);
3087 return false;
3088 }
3089
3090 init_gdbserver_state();
3091 create_default_process(&gdbserver_state);
3092 gdbserver_state.processes[0].attached = true;
3093 gdbserver_state.c_cpu = gdb_first_attached_cpu();
3094 gdbserver_state.g_cpu = gdbserver_state.c_cpu;
3095 gdbserver_state.fd = fd;
3096 gdb_has_xml = false;
3097 return true;
3098 }
3099
3100 static int gdbserver_open(int port)
3101 {
3102 struct sockaddr_in sockaddr;
3103 int fd, ret;
3104
3105 fd = socket(PF_INET, SOCK_STREAM, 0);
3106 if (fd < 0) {
3107 perror("socket");
3108 return -1;
3109 }
3110 qemu_set_cloexec(fd);
3111
3112 socket_set_fast_reuse(fd);
3113
3114 sockaddr.sin_family = AF_INET;
3115 sockaddr.sin_port = htons(port);
3116 sockaddr.sin_addr.s_addr = 0;
3117 ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
3118 if (ret < 0) {
3119 perror("bind");
3120 close(fd);
3121 return -1;
3122 }
3123 ret = listen(fd, 1);
3124 if (ret < 0) {
3125 perror("listen");
3126 close(fd);
3127 return -1;
3128 }
3129 return fd;
3130 }
3131
3132 int gdbserver_start(int port)
3133 {
3134 gdbserver_fd = gdbserver_open(port);
3135 if (gdbserver_fd < 0)
3136 return -1;
3137 /* accept connections */
3138 if (!gdb_accept()) {
3139 close(gdbserver_fd);
3140 gdbserver_fd = -1;
3141 return -1;
3142 }
3143 return 0;
3144 }
3145
3146 /* Disable gdb stub for child processes. */
3147 void gdbserver_fork(CPUState *cpu)
3148 {
3149 if (gdbserver_fd < 0 || gdbserver_state.fd < 0) {
3150 return;
3151 }
3152 close(gdbserver_state.fd);
3153 gdbserver_state.fd = -1;
3154 cpu_breakpoint_remove_all(cpu, BP_GDB);
3155 cpu_watchpoint_remove_all(cpu, BP_GDB);
3156 }
3157 #else
3158 static int gdb_chr_can_receive(void *opaque)
3159 {
3160 /* We can handle an arbitrarily large amount of data.
3161 Pick the maximum packet size, which is as good as anything. */
3162 return MAX_PACKET_LENGTH;
3163 }
3164
3165 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
3166 {
3167 int i;
3168
3169 for (i = 0; i < size; i++) {
3170 gdb_read_byte(buf[i]);
3171 }
3172 }
3173
3174 static void gdb_chr_event(void *opaque, QEMUChrEvent event)
3175 {
3176 int i;
3177 GDBState *s = (GDBState *) opaque;
3178
3179 switch (event) {
3180 case CHR_EVENT_OPENED:
3181 /* Start with first process attached, others detached */
3182 for (i = 0; i < s->process_num; i++) {
3183 s->processes[i].attached = !i;
3184 }
3185
3186 s->c_cpu = gdb_first_attached_cpu();
3187 s->g_cpu = s->c_cpu;
3188
3189 vm_stop(RUN_STATE_PAUSED);
3190 gdb_has_xml = false;
3191 break;
3192 default:
3193 break;
3194 }
3195 }
3196
3197 static void gdb_monitor_output(const char *msg, int len)
3198 {
3199 char buf[MAX_PACKET_LENGTH];
3200
3201 buf[0] = 'O';
3202 if (len > (MAX_PACKET_LENGTH/2) - 1)
3203 len = (MAX_PACKET_LENGTH/2) - 1;
3204 memtohex(buf + 1, (uint8_t *)msg, len);
3205 put_packet(buf);
3206 }
3207
3208 static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
3209 {
3210 const char *p = (const char *)buf;
3211 int max_sz;
3212
3213 max_sz = (sizeof(gdbserver_state.last_packet) - 2) / 2;
3214 for (;;) {
3215 if (len <= max_sz) {
3216 gdb_monitor_output(p, len);
3217 break;
3218 }
3219 gdb_monitor_output(p, max_sz);
3220 p += max_sz;
3221 len -= max_sz;
3222 }
3223 return len;
3224 }
3225
3226 #ifndef _WIN32
3227 static void gdb_sigterm_handler(int signal)
3228 {
3229 if (runstate_is_running()) {
3230 vm_stop(RUN_STATE_PAUSED);
3231 }
3232 }
3233 #endif
3234
3235 static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
3236 bool *be_opened, Error **errp)
3237 {
3238 *be_opened = false;
3239 }
3240
3241 static void char_gdb_class_init(ObjectClass *oc, void *data)
3242 {
3243 ChardevClass *cc = CHARDEV_CLASS(oc);
3244
3245 cc->internal = true;
3246 cc->open = gdb_monitor_open;
3247 cc->chr_write = gdb_monitor_write;
3248 }
3249
3250 #define TYPE_CHARDEV_GDB "chardev-gdb"
3251
3252 static const TypeInfo char_gdb_type_info = {
3253 .name = TYPE_CHARDEV_GDB,
3254 .parent = TYPE_CHARDEV,
3255 .class_init = char_gdb_class_init,
3256 };
3257
3258 static int find_cpu_clusters(Object *child, void *opaque)
3259 {
3260 if (object_dynamic_cast(child, TYPE_CPU_CLUSTER)) {
3261 GDBState *s = (GDBState *) opaque;
3262 CPUClusterState *cluster = CPU_CLUSTER(child);
3263 GDBProcess *process;
3264
3265 s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
3266
3267 process = &s->processes[s->process_num - 1];
3268
3269 /*
3270 * GDB process IDs -1 and 0 are reserved. To avoid subtle errors at
3271 * runtime, we enforce here that the machine does not use a cluster ID
3272 * that would lead to PID 0.
3273 */
3274 assert(cluster->cluster_id != UINT32_MAX);
3275 process->pid = cluster->cluster_id + 1;
3276 process->attached = false;
3277 process->target_xml[0] = '\0';
3278
3279 return 0;
3280 }
3281
3282 return object_child_foreach(child, find_cpu_clusters, opaque);
3283 }
3284
3285 static int pid_order(const void *a, const void *b)
3286 {
3287 GDBProcess *pa = (GDBProcess *) a;
3288 GDBProcess *pb = (GDBProcess *) b;
3289
3290 if (pa->pid < pb->pid) {
3291 return -1;
3292 } else if (pa->pid > pb->pid) {
3293 return 1;
3294 } else {
3295 return 0;
3296 }
3297 }
3298
3299 static void create_processes(GDBState *s)
3300 {
3301 object_child_foreach(object_get_root(), find_cpu_clusters, s);
3302
3303 if (gdbserver_state.processes) {
3304 /* Sort by PID */
3305 qsort(gdbserver_state.processes, gdbserver_state.process_num, sizeof(gdbserver_state.processes[0]), pid_order);
3306 }
3307
3308 create_default_process(s);
3309 }
3310
3311 int gdbserver_start(const char *device)
3312 {
3313 trace_gdbstub_op_start(device);
3314
3315 char gdbstub_device_name[128];
3316 Chardev *chr = NULL;
3317 Chardev *mon_chr;
3318
3319 if (!first_cpu) {
3320 error_report("gdbstub: meaningless to attach gdb to a "
3321 "machine without any CPU.");
3322 return -1;
3323 }
3324
3325 if (!device)
3326 return -1;
3327 if (strcmp(device, "none") != 0) {
3328 if (strstart(device, "tcp:", NULL)) {
3329 /* enforce required TCP attributes */
3330 snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
3331 "%s,nowait,nodelay,server", device);
3332 device = gdbstub_device_name;
3333 }
3334 #ifndef _WIN32
3335 else if (strcmp(device, "stdio") == 0) {
3336 struct sigaction act;
3337
3338 memset(&act, 0, sizeof(act));
3339 act.sa_handler = gdb_sigterm_handler;
3340 sigaction(SIGINT, &act, NULL);
3341 }
3342 #endif
3343 /*
3344 * FIXME: it's a bit weird to allow using a mux chardev here
3345 * and implicitly setup a monitor. We may want to break this.
3346 */
3347 chr = qemu_chr_new_noreplay("gdb", device, true, NULL);
3348 if (!chr)
3349 return -1;
3350 }
3351
3352 if (!gdbserver_state.init) {
3353 init_gdbserver_state();
3354
3355 qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
3356
3357 /* Initialize a monitor terminal for gdb */
3358 mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
3359 NULL, NULL, &error_abort);
3360 monitor_init_hmp(mon_chr, false, &error_abort);
3361 } else {
3362 qemu_chr_fe_deinit(&gdbserver_state.chr, true);
3363 mon_chr = gdbserver_state.mon_chr;
3364 reset_gdbserver_state();
3365 }
3366
3367 create_processes(&gdbserver_state);
3368
3369 if (chr) {
3370 qemu_chr_fe_init(&gdbserver_state.chr, chr, &error_abort);
3371 qemu_chr_fe_set_handlers(&gdbserver_state.chr, gdb_chr_can_receive,
3372 gdb_chr_receive, gdb_chr_event,
3373 NULL, &gdbserver_state, NULL, true);
3374 }
3375 gdbserver_state.state = chr ? RS_IDLE : RS_INACTIVE;
3376 gdbserver_state.mon_chr = mon_chr;
3377 gdbserver_state.current_syscall_cb = NULL;
3378
3379 return 0;
3380 }
3381
3382 void gdbserver_cleanup(void)
3383 {
3384 if (gdbserver_state.init) {
3385 put_packet("W00");
3386 }
3387 }
3388
3389 static void register_types(void)
3390 {
3391 type_register_static(&char_gdb_type_info);
3392 }
3393
3394 type_init(register_types);
3395 #endif