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