xref: /qemu/gdbstub/system.c (revision 589a58672e044c0415e70f018393c8406cdd5c49)
1 /*
2  * gdb server stub - softmmu specific bits
3  *
4  * Debug integration depends on support from the individual
5  * accelerators so most of this involves calling the ops helpers.
6  *
7  * Copyright (c) 2003-2005 Fabrice Bellard
8  * Copyright (c) 2022 Linaro Ltd
9  *
10  * SPDX-License-Identifier: LGPL-2.0+
11  */
12 
13 #include "qemu/osdep.h"
14 #include "qapi/error.h"
15 #include "qemu/error-report.h"
16 #include "qemu/cutils.h"
17 #include "exec/gdbstub.h"
18 #include "exec/hwaddr.h"
19 #include "exec/tb-flush.h"
20 #include "sysemu/cpus.h"
21 #include "sysemu/runstate.h"
22 #include "sysemu/replay.h"
23 #include "hw/core/cpu.h"
24 #include "hw/cpu/cluster.h"
25 #include "hw/boards.h"
26 #include "chardev/char.h"
27 #include "chardev/char-fe.h"
28 #include "monitor/monitor.h"
29 #include "trace.h"
30 #include "internals.h"
31 
32 /* System emulation specific state */
33 typedef struct {
34     CharBackend chr;
35     Chardev *mon_chr;
36 } GDBSystemState;
37 
38 GDBSystemState gdbserver_system_state;
39 
40 static void reset_gdbserver_state(void)
41 {
42     g_free(gdbserver_state.processes);
43     gdbserver_state.processes = NULL;
44     gdbserver_state.process_num = 0;
45 }
46 
47 /*
48  * Return the GDB index for a given vCPU state.
49  *
50  * In system mode GDB numbers CPUs from 1 as 0 is reserved as an "any
51  * cpu" index.
52  */
53 int gdb_get_cpu_index(CPUState *cpu)
54 {
55     return cpu->cpu_index + 1;
56 }
57 
58 /*
59  * We check the status of the last message in the chardev receive code
60  */
61 bool gdb_got_immediate_ack(void)
62 {
63     return true;
64 }
65 
66 /*
67  * GDB Connection management. For system emulation we do all of this
68  * via our existing Chardev infrastructure which allows us to support
69  * network and unix sockets.
70  */
71 
72 void gdb_put_buffer(const uint8_t *buf, int len)
73 {
74     /*
75      * XXX this blocks entire thread. Rewrite to use
76      * qemu_chr_fe_write and background I/O callbacks
77      */
78     qemu_chr_fe_write_all(&gdbserver_system_state.chr, buf, len);
79 }
80 
81 static void gdb_chr_event(void *opaque, QEMUChrEvent event)
82 {
83     int i;
84     GDBState *s = (GDBState *) opaque;
85 
86     switch (event) {
87     case CHR_EVENT_OPENED:
88         /* Start with first process attached, others detached */
89         for (i = 0; i < s->process_num; i++) {
90             s->processes[i].attached = !i;
91         }
92 
93         s->c_cpu = gdb_first_attached_cpu();
94         s->g_cpu = s->c_cpu;
95 
96         vm_stop(RUN_STATE_PAUSED);
97         replay_gdb_attached();
98         gdb_has_xml = false;
99         break;
100     default:
101         break;
102     }
103 }
104 
105 static void gdb_vm_state_change(void *opaque, bool running, RunState state)
106 {
107     CPUState *cpu = gdbserver_state.c_cpu;
108     g_autoptr(GString) buf = g_string_new(NULL);
109     g_autoptr(GString) tid = g_string_new(NULL);
110     const char *type;
111     int ret;
112 
113     if (running || gdbserver_state.state == RS_INACTIVE) {
114         return;
115     }
116     /* Is there a GDB syscall waiting to be sent?  */
117     if (gdbserver_state.current_syscall_cb) {
118         gdb_put_packet(gdbserver_state.syscall_buf);
119         return;
120     }
121 
122     if (cpu == NULL) {
123         /* No process attached */
124         return;
125     }
126 
127     gdb_append_thread_id(cpu, tid);
128 
129     switch (state) {
130     case RUN_STATE_DEBUG:
131         if (cpu->watchpoint_hit) {
132             switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
133             case BP_MEM_READ:
134                 type = "r";
135                 break;
136             case BP_MEM_ACCESS:
137                 type = "a";
138                 break;
139             default:
140                 type = "";
141                 break;
142             }
143             trace_gdbstub_hit_watchpoint(type,
144                                          gdb_get_cpu_index(cpu),
145                                          cpu->watchpoint_hit->vaddr);
146             g_string_printf(buf, "T%02xthread:%s;%swatch:%" VADDR_PRIx ";",
147                             GDB_SIGNAL_TRAP, tid->str, type,
148                             cpu->watchpoint_hit->vaddr);
149             cpu->watchpoint_hit = NULL;
150             goto send_packet;
151         } else {
152             trace_gdbstub_hit_break();
153         }
154         tb_flush(cpu);
155         ret = GDB_SIGNAL_TRAP;
156         break;
157     case RUN_STATE_PAUSED:
158         trace_gdbstub_hit_paused();
159         ret = GDB_SIGNAL_INT;
160         break;
161     case RUN_STATE_SHUTDOWN:
162         trace_gdbstub_hit_shutdown();
163         ret = GDB_SIGNAL_QUIT;
164         break;
165     case RUN_STATE_IO_ERROR:
166         trace_gdbstub_hit_io_error();
167         ret = GDB_SIGNAL_IO;
168         break;
169     case RUN_STATE_WATCHDOG:
170         trace_gdbstub_hit_watchdog();
171         ret = GDB_SIGNAL_ALRM;
172         break;
173     case RUN_STATE_INTERNAL_ERROR:
174         trace_gdbstub_hit_internal_error();
175         ret = GDB_SIGNAL_ABRT;
176         break;
177     case RUN_STATE_SAVE_VM:
178     case RUN_STATE_RESTORE_VM:
179         return;
180     case RUN_STATE_FINISH_MIGRATE:
181         ret = GDB_SIGNAL_XCPU;
182         break;
183     default:
184         trace_gdbstub_hit_unknown(state);
185         ret = GDB_SIGNAL_UNKNOWN;
186         break;
187     }
188     gdb_set_stop_cpu(cpu);
189     g_string_printf(buf, "T%02xthread:%s;", ret, tid->str);
190 
191 send_packet:
192     gdb_put_packet(buf->str);
193 
194     /* disable single step if it was enabled */
195     cpu_single_step(cpu, 0);
196 }
197 
198 #ifndef _WIN32
199 static void gdb_sigterm_handler(int signal)
200 {
201     if (runstate_is_running()) {
202         vm_stop(RUN_STATE_PAUSED);
203     }
204 }
205 #endif
206 
207 static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
208 {
209     g_autoptr(GString) hex_buf = g_string_new("O");
210     gdb_memtohex(hex_buf, buf, len);
211     gdb_put_packet(hex_buf->str);
212     return len;
213 }
214 
215 static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
216                              bool *be_opened, Error **errp)
217 {
218     *be_opened = false;
219 }
220 
221 static void char_gdb_class_init(ObjectClass *oc, void *data)
222 {
223     ChardevClass *cc = CHARDEV_CLASS(oc);
224 
225     cc->internal = true;
226     cc->open = gdb_monitor_open;
227     cc->chr_write = gdb_monitor_write;
228 }
229 
230 #define TYPE_CHARDEV_GDB "chardev-gdb"
231 
232 static const TypeInfo char_gdb_type_info = {
233     .name = TYPE_CHARDEV_GDB,
234     .parent = TYPE_CHARDEV,
235     .class_init = char_gdb_class_init,
236 };
237 
238 static int gdb_chr_can_receive(void *opaque)
239 {
240   /*
241    * We can handle an arbitrarily large amount of data.
242    * Pick the maximum packet size, which is as good as anything.
243    */
244   return MAX_PACKET_LENGTH;
245 }
246 
247 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
248 {
249     int i;
250 
251     for (i = 0; i < size; i++) {
252         gdb_read_byte(buf[i]);
253     }
254 }
255 
256 static int find_cpu_clusters(Object *child, void *opaque)
257 {
258     if (object_dynamic_cast(child, TYPE_CPU_CLUSTER)) {
259         GDBState *s = (GDBState *) opaque;
260         CPUClusterState *cluster = CPU_CLUSTER(child);
261         GDBProcess *process;
262 
263         s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
264 
265         process = &s->processes[s->process_num - 1];
266 
267         /*
268          * GDB process IDs -1 and 0 are reserved. To avoid subtle errors at
269          * runtime, we enforce here that the machine does not use a cluster ID
270          * that would lead to PID 0.
271          */
272         assert(cluster->cluster_id != UINT32_MAX);
273         process->pid = cluster->cluster_id + 1;
274         process->attached = false;
275         process->target_xml[0] = '\0';
276 
277         return 0;
278     }
279 
280     return object_child_foreach(child, find_cpu_clusters, opaque);
281 }
282 
283 static int pid_order(const void *a, const void *b)
284 {
285     GDBProcess *pa = (GDBProcess *) a;
286     GDBProcess *pb = (GDBProcess *) b;
287 
288     if (pa->pid < pb->pid) {
289         return -1;
290     } else if (pa->pid > pb->pid) {
291         return 1;
292     } else {
293         return 0;
294     }
295 }
296 
297 static void create_processes(GDBState *s)
298 {
299     object_child_foreach(object_get_root(), find_cpu_clusters, s);
300 
301     if (gdbserver_state.processes) {
302         /* Sort by PID */
303         qsort(gdbserver_state.processes,
304               gdbserver_state.process_num,
305               sizeof(gdbserver_state.processes[0]),
306               pid_order);
307     }
308 
309     gdb_create_default_process(s);
310 }
311 
312 int gdbserver_start(const char *device)
313 {
314     trace_gdbstub_op_start(device);
315 
316     char gdbstub_device_name[128];
317     Chardev *chr = NULL;
318     Chardev *mon_chr;
319 
320     if (!first_cpu) {
321         error_report("gdbstub: meaningless to attach gdb to a "
322                      "machine without any CPU.");
323         return -1;
324     }
325 
326     if (!gdb_supports_guest_debug()) {
327         error_report("gdbstub: current accelerator doesn't "
328                      "support guest debugging");
329         return -1;
330     }
331 
332     if (!device) {
333         return -1;
334     }
335     if (strcmp(device, "none") != 0) {
336         if (strstart(device, "tcp:", NULL)) {
337             /* enforce required TCP attributes */
338             snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
339                      "%s,wait=off,nodelay=on,server=on", device);
340             device = gdbstub_device_name;
341         }
342 #ifndef _WIN32
343         else if (strcmp(device, "stdio") == 0) {
344             struct sigaction act;
345 
346             memset(&act, 0, sizeof(act));
347             act.sa_handler = gdb_sigterm_handler;
348             sigaction(SIGINT, &act, NULL);
349         }
350 #endif
351         /*
352          * FIXME: it's a bit weird to allow using a mux chardev here
353          * and implicitly setup a monitor. We may want to break this.
354          */
355         chr = qemu_chr_new_noreplay("gdb", device, true, NULL);
356         if (!chr) {
357             return -1;
358         }
359     }
360 
361     if (!gdbserver_state.init) {
362         gdb_init_gdbserver_state();
363 
364         qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
365 
366         /* Initialize a monitor terminal for gdb */
367         mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
368                                    NULL, NULL, &error_abort);
369         monitor_init_hmp(mon_chr, false, &error_abort);
370     } else {
371         qemu_chr_fe_deinit(&gdbserver_system_state.chr, true);
372         mon_chr = gdbserver_system_state.mon_chr;
373         reset_gdbserver_state();
374     }
375 
376     create_processes(&gdbserver_state);
377 
378     if (chr) {
379         qemu_chr_fe_init(&gdbserver_system_state.chr, chr, &error_abort);
380         qemu_chr_fe_set_handlers(&gdbserver_system_state.chr,
381                                  gdb_chr_can_receive,
382                                  gdb_chr_receive, gdb_chr_event,
383                                  NULL, &gdbserver_state, NULL, true);
384     }
385     gdbserver_state.state = chr ? RS_IDLE : RS_INACTIVE;
386     gdbserver_system_state.mon_chr = mon_chr;
387     gdbserver_state.current_syscall_cb = NULL;
388 
389     return 0;
390 }
391 
392 static void register_types(void)
393 {
394     type_register_static(&char_gdb_type_info);
395 }
396 
397 type_init(register_types);
398 
399 /* Tell the remote gdb that the process has exited.  */
400 void gdb_exit(int code)
401 {
402     char buf[4];
403 
404     if (!gdbserver_state.init) {
405         return;
406     }
407 
408     trace_gdbstub_op_exiting((uint8_t)code);
409 
410     snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
411     gdb_put_packet(buf);
412 
413     qemu_chr_fe_deinit(&gdbserver_system_state.chr, true);
414 }
415 
416 /*
417  * Memory access
418  */
419 static int phy_memory_mode;
420 
421 int gdb_target_memory_rw_debug(CPUState *cpu, hwaddr addr,
422                                uint8_t *buf, int len, bool is_write)
423 {
424     CPUClass *cc;
425 
426     if (phy_memory_mode) {
427         if (is_write) {
428             cpu_physical_memory_write(addr, buf, len);
429         } else {
430             cpu_physical_memory_read(addr, buf, len);
431         }
432         return 0;
433     }
434 
435     cc = CPU_GET_CLASS(cpu);
436     if (cc->memory_rw_debug) {
437         return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
438     }
439 
440     return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
441 }
442 
443 
444 /*
445  * Softmmu specific command helpers
446  */
447 
448 void gdb_handle_query_qemu_phy_mem_mode(GArray *params,
449                                         void *user_ctx)
450 {
451     g_string_printf(gdbserver_state.str_buf, "%d", phy_memory_mode);
452     gdb_put_strbuf();
453 }
454 
455 void gdb_handle_set_qemu_phy_mem_mode(GArray *params, void *user_ctx)
456 {
457     if (!params->len) {
458         gdb_put_packet("E22");
459         return;
460     }
461 
462     if (!get_param(params, 0)->val_ul) {
463         phy_memory_mode = 0;
464     } else {
465         phy_memory_mode = 1;
466     }
467     gdb_put_packet("OK");
468 }
469 
470 void gdb_handle_query_rcmd(GArray *params, void *user_ctx)
471 {
472     const guint8 zero = 0;
473     int len;
474 
475     if (!params->len) {
476         gdb_put_packet("E22");
477         return;
478     }
479 
480     len = strlen(get_param(params, 0)->data);
481     if (len % 2) {
482         gdb_put_packet("E01");
483         return;
484     }
485 
486     g_assert(gdbserver_state.mem_buf->len == 0);
487     len = len / 2;
488     gdb_hextomem(gdbserver_state.mem_buf, get_param(params, 0)->data, len);
489     g_byte_array_append(gdbserver_state.mem_buf, &zero, 1);
490     qemu_chr_be_write(gdbserver_system_state.mon_chr,
491                       gdbserver_state.mem_buf->data,
492                       gdbserver_state.mem_buf->len);
493     gdb_put_packet("OK");
494 }
495 
496 /*
497  * Execution state helpers
498  */
499 
500 void gdb_handle_query_attached(GArray *params, void *user_ctx)
501 {
502     gdb_put_packet("1");
503 }
504 
505 void gdb_continue(void)
506 {
507     if (!runstate_needs_reset()) {
508         trace_gdbstub_op_continue();
509         vm_start();
510     }
511 }
512 
513 /*
514  * Resume execution, per CPU actions.
515  */
516 int gdb_continue_partial(char *newstates)
517 {
518     CPUState *cpu;
519     int res = 0;
520     int flag = 0;
521 
522     if (!runstate_needs_reset()) {
523         bool step_requested = false;
524         CPU_FOREACH(cpu) {
525             if (newstates[cpu->cpu_index] == 's') {
526                 step_requested = true;
527                 break;
528             }
529         }
530 
531         if (vm_prepare_start(step_requested)) {
532             return 0;
533         }
534 
535         CPU_FOREACH(cpu) {
536             switch (newstates[cpu->cpu_index]) {
537             case 0:
538             case 1:
539                 break; /* nothing to do here */
540             case 's':
541                 trace_gdbstub_op_stepping(cpu->cpu_index);
542                 cpu_single_step(cpu, gdbserver_state.sstep_flags);
543                 cpu_resume(cpu);
544                 flag = 1;
545                 break;
546             case 'c':
547                 trace_gdbstub_op_continue_cpu(cpu->cpu_index);
548                 cpu_resume(cpu);
549                 flag = 1;
550                 break;
551             default:
552                 res = -1;
553                 break;
554             }
555         }
556     }
557     if (flag) {
558         qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
559     }
560     return res;
561 }
562 
563 /*
564  * Signal Handling - in system mode we only need SIGINT and SIGTRAP; other
565  * signals are not yet supported.
566  */
567 
568 enum {
569     TARGET_SIGINT = 2,
570     TARGET_SIGTRAP = 5
571 };
572 
573 int gdb_signal_to_target(int sig)
574 {
575     switch (sig) {
576     case 2:
577         return TARGET_SIGINT;
578     case 5:
579         return TARGET_SIGTRAP;
580     default:
581         return -1;
582     }
583 }
584 
585 /*
586  * Break/Watch point helpers
587  */
588 
589 bool gdb_supports_guest_debug(void)
590 {
591     const AccelOpsClass *ops = cpus_get_accel();
592     if (ops->supports_guest_debug) {
593         return ops->supports_guest_debug();
594     }
595     return false;
596 }
597 
598 int gdb_breakpoint_insert(CPUState *cs, int type, vaddr addr, vaddr len)
599 {
600     const AccelOpsClass *ops = cpus_get_accel();
601     if (ops->insert_breakpoint) {
602         return ops->insert_breakpoint(cs, type, addr, len);
603     }
604     return -ENOSYS;
605 }
606 
607 int gdb_breakpoint_remove(CPUState *cs, int type, vaddr addr, vaddr len)
608 {
609     const AccelOpsClass *ops = cpus_get_accel();
610     if (ops->remove_breakpoint) {
611         return ops->remove_breakpoint(cs, type, addr, len);
612     }
613     return -ENOSYS;
614 }
615 
616 void gdb_breakpoint_remove_all(CPUState *cs)
617 {
618     const AccelOpsClass *ops = cpus_get_accel();
619     if (ops->remove_all_breakpoints) {
620         ops->remove_all_breakpoints(cs);
621     }
622 }
623