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