xref: /qemu/gdbstub/user.c (revision 5136598e2667f35ef3dc1d757616a266bd5eb3a2)
1 /*
2  * gdbstub user-mode helper routines.
3  *
4  * We know for user-mode we are using TCG so we can call stuff directly.
5  *
6  * Copyright (c) 2003-2005 Fabrice Bellard
7  * Copyright (c) 2022 Linaro Ltd
8  *
9  * SPDX-License-Identifier: LGPL-2.0-or-later
10  */
11 
12 #include "qemu/osdep.h"
13 #include "qemu/bitops.h"
14 #include "qemu/cutils.h"
15 #include "qemu/sockets.h"
16 #include "qapi/error.h"
17 #include "exec/hwaddr.h"
18 #include "exec/tb-flush.h"
19 #include "exec/gdbstub.h"
20 #include "gdbstub/commands.h"
21 #include "gdbstub/syscalls.h"
22 #include "gdbstub/user.h"
23 #include "gdbstub/enums.h"
24 #include "hw/core/cpu.h"
25 #include "user/signal.h"
26 #include "trace.h"
27 #include "internals.h"
28 
29 #define GDB_NR_SYSCALLS 1024
30 typedef unsigned long GDBSyscallsMask[BITS_TO_LONGS(GDB_NR_SYSCALLS)];
31 
32 /*
33  * Forked child talks to its parent in order to let GDB enforce the
34  * follow-fork-mode. This happens inside a start_exclusive() section, so that
35  * the other threads, which may be forking too, do not interfere. The
36  * implementation relies on GDB not sending $vCont until it has detached
37  * either from the parent (follow-fork-mode child) or from the child
38  * (follow-fork-mode parent).
39  *
40  * The parent and the child share the GDB socket; at any given time only one
41  * of them is allowed to use it, as is reflected in the respective fork_state.
42  * This is negotiated via the fork_sockets pair as a reaction to $Hg.
43  *
44  * Below is a short summary of the possible state transitions:
45  *
46  *     ENABLED                     : Terminal state.
47  *     DISABLED                    : Terminal state.
48  *     ACTIVE                      : Parent initial state.
49  *     INACTIVE                    : Child initial state.
50  *     ACTIVE       -> DEACTIVATING: On $Hg.
51  *     ACTIVE       -> ENABLING    : On $D.
52  *     ACTIVE       -> DISABLING   : On $D.
53  *     ACTIVE       -> DISABLED    : On communication error.
54  *     DEACTIVATING -> INACTIVE    : On gdb_read_byte() return.
55  *     DEACTIVATING -> DISABLED    : On communication error.
56  *     INACTIVE     -> ACTIVE      : On $Hg in the peer.
57  *     INACTIVE     -> ENABLE      : On $D in the peer.
58  *     INACTIVE     -> DISABLE     : On $D in the peer.
59  *     INACTIVE     -> DISABLED    : On communication error.
60  *     ENABLING     -> ENABLED     : On gdb_read_byte() return.
61  *     ENABLING     -> DISABLED    : On communication error.
62  *     DISABLING    -> DISABLED    : On gdb_read_byte() return.
63  */
64 enum GDBForkState {
65     /* Fully owning the GDB socket. */
66     GDB_FORK_ENABLED,
67     /* Working with the GDB socket; the peer is inactive. */
68     GDB_FORK_ACTIVE,
69     /* Handing off the GDB socket to the peer. */
70     GDB_FORK_DEACTIVATING,
71     /* The peer is working with the GDB socket. */
72     GDB_FORK_INACTIVE,
73     /* Asking the peer to close its GDB socket fd. */
74     GDB_FORK_ENABLING,
75     /* Asking the peer to take over, closing our GDB socket fd. */
76     GDB_FORK_DISABLING,
77     /* The peer has taken over, our GDB socket fd is closed. */
78     GDB_FORK_DISABLED,
79 };
80 
81 enum GDBForkMessage {
82     GDB_FORK_ACTIVATE = 'a',
83     GDB_FORK_ENABLE = 'e',
84     GDB_FORK_DISABLE = 'd',
85 };
86 
87 /* User-mode specific state */
88 typedef struct {
89     int fd;
90     char *socket_path;
91     int running_state;
92     /*
93      * Store syscalls mask without memory allocation in order to avoid
94      * implementing synchronization.
95      */
96     bool catch_all_syscalls;
97     GDBSyscallsMask catch_syscalls_mask;
98     bool fork_events;
99     enum GDBForkState fork_state;
100     int fork_sockets[2];
101     pid_t fork_peer_pid, fork_peer_tid;
102     uint8_t siginfo[MAX_SIGINFO_LENGTH];
103     unsigned long siginfo_len;
104 } GDBUserState;
105 
106 static GDBUserState gdbserver_user_state;
107 
gdb_get_char(void)108 int gdb_get_char(void)
109 {
110     uint8_t ch;
111     int ret;
112 
113     for (;;) {
114         ret = recv(gdbserver_user_state.fd, &ch, 1, 0);
115         if (ret < 0) {
116             if (errno == ECONNRESET) {
117                 gdbserver_user_state.fd = -1;
118             }
119             if (errno != EINTR) {
120                 return -1;
121             }
122         } else if (ret == 0) {
123             close(gdbserver_user_state.fd);
124             gdbserver_user_state.fd = -1;
125             return -1;
126         } else {
127             break;
128         }
129     }
130     return ch;
131 }
132 
gdb_got_immediate_ack(void)133 bool gdb_got_immediate_ack(void)
134 {
135     int i;
136 
137     i = gdb_get_char();
138     if (i < 0) {
139         /* no response, continue anyway */
140         return true;
141     }
142 
143     if (i == '+') {
144         /* received correctly, continue */
145         return true;
146     }
147 
148     /* anything else, including '-' then try again */
149     return false;
150 }
151 
gdb_put_buffer(const uint8_t * buf,int len)152 void gdb_put_buffer(const uint8_t *buf, int len)
153 {
154     int ret;
155 
156     while (len > 0) {
157         ret = send(gdbserver_user_state.fd, buf, len, 0);
158         if (ret < 0) {
159             if (errno != EINTR) {
160                 return;
161             }
162         } else {
163             buf += ret;
164             len -= ret;
165         }
166     }
167 }
168 
169 /* Tell the remote gdb that the process has exited.  */
gdb_exit(int code)170 void gdb_exit(int code)
171 {
172     char buf[4];
173 
174     if (!gdbserver_state.init) {
175         return;
176     }
177     if (gdbserver_user_state.socket_path) {
178         unlink(gdbserver_user_state.socket_path);
179     }
180     if (gdbserver_user_state.fd < 0) {
181         return;
182     }
183 
184     trace_gdbstub_op_exiting((uint8_t)code);
185 
186     if (gdbserver_state.allow_stop_reply) {
187         snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
188         gdb_put_packet(buf);
189         gdbserver_state.allow_stop_reply = false;
190     }
191 
192 }
193 
gdb_qemu_exit(int code)194 void gdb_qemu_exit(int code)
195 {
196     exit(code);
197 }
198 
gdb_handlesig(CPUState * cpu,int sig,const char * reason,void * siginfo,int siginfo_len)199 int gdb_handlesig(CPUState *cpu, int sig, const char *reason, void *siginfo,
200                   int siginfo_len)
201 {
202     char buf[256];
203     int n;
204 
205     if (!gdbserver_state.init || gdbserver_user_state.fd < 0) {
206         return sig;
207     }
208 
209     if (siginfo) {
210         /*
211          * Save target-specific siginfo.
212          *
213          * siginfo size, i.e. siginfo_len, is asserted at compile-time to fit in
214          * gdbserver_user_state.siginfo, usually in the source file calling
215          * gdb_handlesig. See, for instance, {linux,bsd}-user/signal.c.
216          */
217         memcpy(gdbserver_user_state.siginfo, siginfo, siginfo_len);
218         gdbserver_user_state.siginfo_len = siginfo_len;
219     }
220 
221     /* disable single step if it was enabled */
222     cpu_single_step(cpu, 0);
223     tb_flush(cpu);
224 
225     if (sig != 0) {
226         gdb_set_stop_cpu(cpu);
227         if (gdbserver_state.allow_stop_reply) {
228             g_string_printf(gdbserver_state.str_buf,
229                             "T%02xthread:", gdb_target_signal_to_gdb(sig));
230             gdb_append_thread_id(cpu, gdbserver_state.str_buf);
231             g_string_append_c(gdbserver_state.str_buf, ';');
232             if (reason) {
233                 g_string_append(gdbserver_state.str_buf, reason);
234             }
235             gdb_put_strbuf();
236             gdbserver_state.allow_stop_reply = false;
237         }
238     }
239     /*
240      * gdb_put_packet() might have detected that the peer terminated the
241      * connection.
242      */
243     if (gdbserver_user_state.fd < 0) {
244         return sig;
245     }
246 
247     sig = 0;
248     gdbserver_state.state = RS_IDLE;
249     gdbserver_user_state.running_state = 0;
250     while (gdbserver_user_state.running_state == 0) {
251         n = read(gdbserver_user_state.fd, buf, 256);
252         if (n > 0) {
253             int i;
254 
255             for (i = 0; i < n; i++) {
256                 gdb_read_byte(buf[i]);
257             }
258         } else {
259             /*
260              * XXX: Connection closed.  Should probably wait for another
261              * connection before continuing.
262              */
263             if (n == 0) {
264                 close(gdbserver_user_state.fd);
265             }
266             gdbserver_user_state.fd = -1;
267             return sig;
268         }
269     }
270     sig = gdbserver_state.signal;
271     gdbserver_state.signal = 0;
272     return sig;
273 }
274 
275 /* Tell the remote gdb that the process has exited due to SIG.  */
gdb_signalled(CPUArchState * env,int sig)276 void gdb_signalled(CPUArchState *env, int sig)
277 {
278     char buf[4];
279 
280     if (!gdbserver_state.init || gdbserver_user_state.fd < 0 ||
281         !gdbserver_state.allow_stop_reply) {
282         return;
283     }
284 
285     snprintf(buf, sizeof(buf), "X%02x", gdb_target_signal_to_gdb(sig));
286     gdb_put_packet(buf);
287     gdbserver_state.allow_stop_reply = false;
288 }
289 
gdb_accept_init(int fd)290 static void gdb_accept_init(int fd)
291 {
292     gdb_init_gdbserver_state();
293     gdb_create_default_process(&gdbserver_state);
294     gdbserver_state.processes[0].attached = true;
295     gdbserver_state.c_cpu = gdb_first_attached_cpu();
296     gdbserver_state.g_cpu = gdbserver_state.c_cpu;
297     gdbserver_user_state.fd = fd;
298 }
299 
gdb_accept_socket(int gdb_fd)300 static bool gdb_accept_socket(int gdb_fd)
301 {
302     int fd;
303 
304     for (;;) {
305         fd = accept(gdb_fd, NULL, NULL);
306         if (fd < 0 && errno != EINTR) {
307             perror("accept socket");
308             return false;
309         } else if (fd >= 0) {
310             qemu_set_cloexec(fd);
311             break;
312         }
313     }
314 
315     gdb_accept_init(fd);
316     return true;
317 }
318 
gdbserver_open_socket(const char * path,Error ** errp)319 static int gdbserver_open_socket(const char *path, Error **errp)
320 {
321     g_autoptr(GString) buf = g_string_new("");
322     char *pid_placeholder;
323 
324     pid_placeholder = strstr(path, "%d");
325     if (pid_placeholder != NULL) {
326         g_string_append_len(buf, path, pid_placeholder - path);
327         g_string_append_printf(buf, "%d", qemu_get_thread_id());
328         g_string_append(buf, pid_placeholder + 2);
329         path = buf->str;
330     }
331 
332     return unix_listen(path, errp);
333 }
334 
gdb_accept_tcp(int gdb_fd)335 static bool gdb_accept_tcp(int gdb_fd)
336 {
337     struct sockaddr_in sockaddr = {};
338     socklen_t len;
339     int fd;
340 
341     for (;;) {
342         len = sizeof(sockaddr);
343         fd = accept(gdb_fd, (struct sockaddr *)&sockaddr, &len);
344         if (fd < 0 && errno != EINTR) {
345             perror("accept");
346             return false;
347         } else if (fd >= 0) {
348             qemu_set_cloexec(fd);
349             break;
350         }
351     }
352 
353     /* set short latency */
354     if (socket_set_nodelay(fd)) {
355         perror("setsockopt");
356         close(fd);
357         return false;
358     }
359 
360     gdb_accept_init(fd);
361     return true;
362 }
363 
gdbserver_open_port(int port,Error ** errp)364 static int gdbserver_open_port(int port, Error **errp)
365 {
366     struct sockaddr_in sockaddr;
367     int fd, ret;
368 
369     fd = socket(PF_INET, SOCK_STREAM, 0);
370     if (fd < 0) {
371         error_setg_errno(errp, errno, "Failed to create socket");
372         return -1;
373     }
374     qemu_set_cloexec(fd);
375 
376     socket_set_fast_reuse(fd);
377 
378     sockaddr.sin_family = AF_INET;
379     sockaddr.sin_port = htons(port);
380     sockaddr.sin_addr.s_addr = 0;
381     ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
382     if (ret < 0) {
383         error_setg_errno(errp, errno, "Failed to bind socket");
384         close(fd);
385         return -1;
386     }
387     ret = listen(fd, 1);
388     if (ret < 0) {
389         error_setg_errno(errp, errno, "Failed to listen to socket");
390         close(fd);
391         return -1;
392     }
393 
394     return fd;
395 }
396 
gdbserver_accept(int port,int gdb_fd,const char * path)397 static bool gdbserver_accept(int port, int gdb_fd, const char *path)
398 {
399     bool ret;
400 
401     if (port > 0) {
402         ret = gdb_accept_tcp(gdb_fd);
403     } else {
404         ret = gdb_accept_socket(gdb_fd);
405         if (ret) {
406             gdbserver_user_state.socket_path = g_strdup(path);
407         }
408     }
409 
410     if (!ret) {
411         close(gdb_fd);
412     }
413 
414     return ret;
415 }
416 
417 struct {
418     int port;
419     int gdb_fd;
420     char *path;
421 } gdbserver_args;
422 
do_gdb_handlesig(CPUState * cs,run_on_cpu_data arg)423 static void do_gdb_handlesig(CPUState *cs, run_on_cpu_data arg)
424 {
425     int sig;
426 
427     sig = target_to_host_signal(gdb_handlesig(cs, 0, NULL, NULL, 0));
428     if (sig >= 1 && sig < NSIG) {
429         qemu_kill_thread(gdb_get_cpu_index(cs), sig);
430     }
431 }
432 
gdbserver_accept_thread(void * arg)433 static void *gdbserver_accept_thread(void *arg)
434 {
435     if (gdbserver_accept(gdbserver_args.port, gdbserver_args.gdb_fd,
436                          gdbserver_args.path)) {
437         CPUState *cs = first_cpu;
438 
439         async_safe_run_on_cpu(cs, do_gdb_handlesig, RUN_ON_CPU_NULL);
440         qemu_kill_thread(gdb_get_cpu_index(cs), host_interrupt_signal);
441     }
442 
443     g_free(gdbserver_args.path);
444     gdbserver_args.path = NULL;
445 
446     return NULL;
447 }
448 
449 #define USAGE "\nUsage: -g {port|path}[,suspend={y|n}]"
450 
gdbserver_start(const char * args,Error ** errp)451 bool gdbserver_start(const char *args, Error **errp)
452 {
453     g_auto(GStrv) argv = g_strsplit(args, ",", 0);
454     const char *port_or_path = NULL;
455     bool suspend = true;
456     int gdb_fd, port;
457     GStrv arg;
458 
459     for (arg = argv; *arg; arg++) {
460         g_auto(GStrv) tokens = g_strsplit(*arg, "=", 2);
461 
462         if (g_strcmp0(tokens[0], "suspend") == 0) {
463             if (tokens[1] == NULL) {
464                 error_setg(errp,
465                            "gdbstub: missing \"suspend\" option value" USAGE);
466                 return false;
467             } else if (!qapi_bool_parse(tokens[0], tokens[1],
468                                         &suspend, errp)) {
469                 return false;
470             }
471         } else {
472             if (port_or_path) {
473                 error_setg(errp, "gdbstub: unknown option \"%s\"" USAGE, *arg);
474                 return false;
475             }
476             port_or_path = *arg;
477         }
478     }
479     if (!port_or_path) {
480         error_setg(errp, "gdbstub: port or path not specified" USAGE);
481         return false;
482     }
483 
484     port = g_ascii_strtoull(port_or_path, NULL, 10);
485     if (port > 0) {
486         gdb_fd = gdbserver_open_port(port, errp);
487     } else {
488         gdb_fd = gdbserver_open_socket(port_or_path, errp);
489     }
490     if (gdb_fd < 0) {
491         return false;
492     }
493 
494     if (suspend) {
495         if (gdbserver_accept(port, gdb_fd, port_or_path)) {
496             gdb_handlesig(first_cpu, 0, NULL, NULL, 0);
497             return true;
498         } else {
499             error_setg(errp, "gdbstub: failed to accept connection");
500             return false;
501         }
502     } else {
503         QemuThread thread;
504 
505         gdbserver_args.port = port;
506         gdbserver_args.gdb_fd = gdb_fd;
507         gdbserver_args.path = g_strdup(port_or_path);
508         qemu_thread_create(&thread, "gdb-accept",
509                            &gdbserver_accept_thread, NULL,
510                            QEMU_THREAD_DETACHED);
511         return true;
512     }
513 }
514 
gdbserver_fork_start(void)515 void gdbserver_fork_start(void)
516 {
517     if (!gdbserver_state.init || gdbserver_user_state.fd < 0) {
518         return;
519     }
520     if (!gdbserver_user_state.fork_events ||
521             qemu_socketpair(AF_UNIX, SOCK_STREAM, 0,
522                             gdbserver_user_state.fork_sockets) < 0) {
523         gdbserver_user_state.fork_state = GDB_FORK_DISABLED;
524         return;
525     }
526     gdbserver_user_state.fork_state = GDB_FORK_INACTIVE;
527     gdbserver_user_state.fork_peer_pid = getpid();
528     gdbserver_user_state.fork_peer_tid = qemu_get_thread_id();
529 }
530 
disable_gdbstub(CPUState * thread_cpu)531 static void disable_gdbstub(CPUState *thread_cpu)
532 {
533     CPUState *cpu;
534 
535     close(gdbserver_user_state.fd);
536     gdbserver_user_state.fd = -1;
537     CPU_FOREACH(cpu) {
538         cpu_breakpoint_remove_all(cpu, BP_GDB);
539         /* no cpu_watchpoint_remove_all for user-mode */
540         cpu_single_step(cpu, 0);
541     }
542     tb_flush(thread_cpu);
543 }
544 
gdbserver_fork_end(CPUState * cpu,pid_t pid)545 void gdbserver_fork_end(CPUState *cpu, pid_t pid)
546 {
547     char b;
548     int fd;
549 
550     if (!gdbserver_state.init || gdbserver_user_state.fd < 0) {
551         return;
552     }
553 
554     if (pid == -1) {
555         if (gdbserver_user_state.fork_state != GDB_FORK_DISABLED) {
556             g_assert(gdbserver_user_state.fork_state == GDB_FORK_INACTIVE);
557             close(gdbserver_user_state.fork_sockets[0]);
558             close(gdbserver_user_state.fork_sockets[1]);
559         }
560         return;
561     }
562 
563     if (gdbserver_user_state.fork_state == GDB_FORK_DISABLED) {
564         if (pid == 0) {
565             disable_gdbstub(cpu);
566         }
567         return;
568     }
569 
570     if (pid == 0) {
571         close(gdbserver_user_state.fork_sockets[0]);
572         fd = gdbserver_user_state.fork_sockets[1];
573         g_assert(gdbserver_state.process_num == 1);
574         g_assert(gdbserver_state.processes[0].pid ==
575                      gdbserver_user_state.fork_peer_pid);
576         g_assert(gdbserver_state.processes[0].attached);
577         gdbserver_state.processes[0].pid = getpid();
578     } else {
579         close(gdbserver_user_state.fork_sockets[1]);
580         fd = gdbserver_user_state.fork_sockets[0];
581         gdbserver_user_state.fork_state = GDB_FORK_ACTIVE;
582         gdbserver_user_state.fork_peer_pid = pid;
583         gdbserver_user_state.fork_peer_tid = pid;
584 
585         if (!gdbserver_state.allow_stop_reply) {
586             goto fail;
587         }
588         g_string_printf(gdbserver_state.str_buf,
589                         "T%02xfork:p%02x.%02x;thread:p%02x.%02x;",
590                         gdb_target_signal_to_gdb(gdb_target_sigtrap()),
591                         pid, pid, (int)getpid(), qemu_get_thread_id());
592         gdb_put_strbuf();
593     }
594 
595     gdbserver_state.state = RS_IDLE;
596     gdbserver_state.allow_stop_reply = false;
597     gdbserver_user_state.running_state = 0;
598     for (;;) {
599         switch (gdbserver_user_state.fork_state) {
600         case GDB_FORK_ENABLED:
601             if (gdbserver_user_state.running_state) {
602                 close(fd);
603                 return;
604             }
605             QEMU_FALLTHROUGH;
606         case GDB_FORK_ACTIVE:
607             if (read(gdbserver_user_state.fd, &b, 1) != 1) {
608                 goto fail;
609             }
610             gdb_read_byte(b);
611             break;
612         case GDB_FORK_DEACTIVATING:
613             b = GDB_FORK_ACTIVATE;
614             if (write(fd, &b, 1) != 1) {
615                 goto fail;
616             }
617             gdbserver_user_state.fork_state = GDB_FORK_INACTIVE;
618             break;
619         case GDB_FORK_INACTIVE:
620             if (read(fd, &b, 1) != 1) {
621                 goto fail;
622             }
623             switch (b) {
624             case GDB_FORK_ACTIVATE:
625                 gdbserver_user_state.fork_state = GDB_FORK_ACTIVE;
626                 break;
627             case GDB_FORK_ENABLE:
628                 gdbserver_user_state.fork_state = GDB_FORK_ENABLED;
629                 break;
630             case GDB_FORK_DISABLE:
631                 gdbserver_user_state.fork_state = GDB_FORK_DISABLED;
632                 break;
633             default:
634                 g_assert_not_reached();
635             }
636             break;
637         case GDB_FORK_ENABLING:
638             b = GDB_FORK_DISABLE;
639             if (write(fd, &b, 1) != 1) {
640                 goto fail;
641             }
642             gdbserver_user_state.fork_state = GDB_FORK_ENABLED;
643             break;
644         case GDB_FORK_DISABLING:
645             b = GDB_FORK_ENABLE;
646             if (write(fd, &b, 1) != 1) {
647                 goto fail;
648             }
649             gdbserver_user_state.fork_state = GDB_FORK_DISABLED;
650             break;
651         case GDB_FORK_DISABLED:
652             close(fd);
653             disable_gdbstub(cpu);
654             return;
655         default:
656             g_assert_not_reached();
657         }
658     }
659 
660 fail:
661     close(fd);
662     if (pid == 0) {
663         disable_gdbstub(cpu);
664     }
665 }
666 
gdb_handle_query_supported_user(const char * gdb_supported)667 void gdb_handle_query_supported_user(const char *gdb_supported)
668 {
669     if (strstr(gdb_supported, "fork-events+")) {
670         gdbserver_user_state.fork_events = true;
671     }
672     g_string_append(gdbserver_state.str_buf, ";fork-events+");
673 }
674 
gdb_handle_set_thread_user(uint32_t pid,uint32_t tid)675 bool gdb_handle_set_thread_user(uint32_t pid, uint32_t tid)
676 {
677     if (gdbserver_user_state.fork_state == GDB_FORK_ACTIVE &&
678             pid == gdbserver_user_state.fork_peer_pid &&
679             tid == gdbserver_user_state.fork_peer_tid) {
680         gdbserver_user_state.fork_state = GDB_FORK_DEACTIVATING;
681         gdb_put_packet("OK");
682         return true;
683     }
684     return false;
685 }
686 
gdb_handle_detach_user(uint32_t pid)687 bool gdb_handle_detach_user(uint32_t pid)
688 {
689     bool enable;
690 
691     if (gdbserver_user_state.fork_state == GDB_FORK_ACTIVE) {
692         enable = pid == gdbserver_user_state.fork_peer_pid;
693         if (enable || pid == getpid()) {
694             gdbserver_user_state.fork_state = enable ? GDB_FORK_ENABLING :
695                                                        GDB_FORK_DISABLING;
696             gdb_put_packet("OK");
697             return true;
698         }
699     }
700     return false;
701 }
702 
703 /*
704  * Execution state helpers
705  */
706 
gdb_handle_query_attached(GArray * params,void * user_ctx)707 void gdb_handle_query_attached(GArray *params, void *user_ctx)
708 {
709     gdb_put_packet("0");
710 }
711 
gdb_continue(void)712 void gdb_continue(void)
713 {
714     gdbserver_user_state.running_state = 1;
715     trace_gdbstub_op_continue();
716 }
717 
718 /*
719  * Resume execution, for user-mode emulation it's equivalent to
720  * gdb_continue.
721  */
gdb_continue_partial(char * newstates)722 int gdb_continue_partial(char *newstates)
723 {
724     CPUState *cpu;
725     int res = 0;
726     /*
727      * This is not exactly accurate, but it's an improvement compared to the
728      * previous situation, where only one CPU would be single-stepped.
729      */
730     CPU_FOREACH(cpu) {
731         if (newstates[cpu->cpu_index] == 's') {
732             trace_gdbstub_op_stepping(cpu->cpu_index);
733             cpu_single_step(cpu, gdbserver_state.sstep_flags);
734         }
735     }
736     gdbserver_user_state.running_state = 1;
737     return res;
738 }
739 
740 /*
741  * Memory access helpers
742  */
gdb_target_memory_rw_debug(CPUState * cpu,hwaddr addr,uint8_t * buf,int len,bool is_write)743 int gdb_target_memory_rw_debug(CPUState *cpu, hwaddr addr,
744                                uint8_t *buf, int len, bool is_write)
745 {
746     if (cpu->cc->memory_rw_debug) {
747         return cpu->cc->memory_rw_debug(cpu, addr, buf, len, is_write);
748     }
749     return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
750 }
751 
752 /*
753  * cpu helpers
754  */
755 
gdb_get_max_cpus(void)756 unsigned int gdb_get_max_cpus(void)
757 {
758     CPUState *cpu;
759     unsigned int max_cpus = 1;
760 
761     CPU_FOREACH(cpu) {
762         max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
763     }
764 
765     return max_cpus;
766 }
767 
768 /* replay not supported for user-mode */
gdb_can_reverse(void)769 bool gdb_can_reverse(void)
770 {
771     return false;
772 }
773 
774 /*
775  * Break/Watch point helpers
776  */
777 
gdb_supports_guest_debug(void)778 bool gdb_supports_guest_debug(void)
779 {
780     /* user-mode == TCG == supported */
781     return true;
782 }
783 
gdb_breakpoint_insert(CPUState * cs,int type,vaddr addr,vaddr len)784 int gdb_breakpoint_insert(CPUState *cs, int type, vaddr addr, vaddr len)
785 {
786     CPUState *cpu;
787     int err = 0;
788 
789     switch (type) {
790     case GDB_BREAKPOINT_SW:
791     case GDB_BREAKPOINT_HW:
792         CPU_FOREACH(cpu) {
793             err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
794             if (err) {
795                 break;
796             }
797         }
798         return err;
799     default:
800         /* user-mode doesn't support watchpoints */
801         return -ENOSYS;
802     }
803 }
804 
gdb_breakpoint_remove(CPUState * cs,int type,vaddr addr,vaddr len)805 int gdb_breakpoint_remove(CPUState *cs, int type, vaddr addr, vaddr len)
806 {
807     CPUState *cpu;
808     int err = 0;
809 
810     switch (type) {
811     case GDB_BREAKPOINT_SW:
812     case GDB_BREAKPOINT_HW:
813         CPU_FOREACH(cpu) {
814             err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
815             if (err) {
816                 break;
817             }
818         }
819         return err;
820     default:
821         /* user-mode doesn't support watchpoints */
822         return -ENOSYS;
823     }
824 }
825 
gdb_breakpoint_remove_all(CPUState * cs)826 void gdb_breakpoint_remove_all(CPUState *cs)
827 {
828     cpu_breakpoint_remove_all(cs, BP_GDB);
829 }
830 
831 /*
832  * For user-mode syscall support we send the system call immediately
833  * and then return control to gdb for it to process the syscall request.
834  * Since the protocol requires that gdb hands control back to us
835  * using a "here are the results" F packet, we don't need to check
836  * gdb_handlesig's return value (which is the signal to deliver if
837  * execution was resumed via a continue packet).
838  */
gdb_syscall_handling(const char * syscall_packet)839 void gdb_syscall_handling(const char *syscall_packet)
840 {
841     gdb_put_packet(syscall_packet);
842     gdb_handlesig(gdbserver_state.c_cpu, 0, NULL, NULL, 0);
843 }
844 
should_catch_syscall(int num)845 static bool should_catch_syscall(int num)
846 {
847     if (gdbserver_user_state.catch_all_syscalls) {
848         return true;
849     }
850     if (num < 0 || num >= GDB_NR_SYSCALLS) {
851         return false;
852     }
853     return test_bit(num, gdbserver_user_state.catch_syscalls_mask);
854 }
855 
gdb_syscall_entry(CPUState * cs,int num)856 void gdb_syscall_entry(CPUState *cs, int num)
857 {
858     if (should_catch_syscall(num)) {
859         g_autofree char *reason = g_strdup_printf("syscall_entry:%x;", num);
860         gdb_handlesig(cs, gdb_target_sigtrap(), reason, NULL, 0);
861     }
862 }
863 
gdb_syscall_return(CPUState * cs,int num)864 void gdb_syscall_return(CPUState *cs, int num)
865 {
866     if (should_catch_syscall(num)) {
867         g_autofree char *reason = g_strdup_printf("syscall_return:%x;", num);
868         gdb_handlesig(cs, gdb_target_sigtrap(), reason, NULL, 0);
869     }
870 }
871 
gdb_handle_set_catch_syscalls(GArray * params,void * user_ctx)872 void gdb_handle_set_catch_syscalls(GArray *params, void *user_ctx)
873 {
874     const char *param = gdb_get_cmd_param(params, 0)->data;
875     GDBSyscallsMask catch_syscalls_mask;
876     bool catch_all_syscalls;
877     unsigned int num;
878     const char *p;
879 
880     /* "0" means not catching any syscalls. */
881     if (strcmp(param, "0") == 0) {
882         gdbserver_user_state.catch_all_syscalls = false;
883         memset(gdbserver_user_state.catch_syscalls_mask, 0,
884                sizeof(gdbserver_user_state.catch_syscalls_mask));
885         gdb_put_packet("OK");
886         return;
887     }
888 
889     /* "1" means catching all syscalls. */
890     if (strcmp(param, "1") == 0) {
891         gdbserver_user_state.catch_all_syscalls = true;
892         gdb_put_packet("OK");
893         return;
894     }
895 
896     /*
897      * "1;..." means catching only the specified syscalls.
898      * The syscall list must not be empty.
899      */
900     if (param[0] == '1' && param[1] == ';') {
901         catch_all_syscalls = false;
902         memset(catch_syscalls_mask, 0, sizeof(catch_syscalls_mask));
903         for (p = &param[2];; p++) {
904             if (qemu_strtoui(p, &p, 16, &num) || (*p && *p != ';')) {
905                 goto err;
906             }
907             if (num >= GDB_NR_SYSCALLS) {
908                 /*
909                  * Fall back to reporting all syscalls. Reporting extra
910                  * syscalls is inefficient, but the spec explicitly allows it.
911                  * Keep parsing in case there is a syntax error ahead.
912                  */
913                 catch_all_syscalls = true;
914             } else {
915                 set_bit(num, catch_syscalls_mask);
916             }
917             if (!*p) {
918                 break;
919             }
920         }
921         gdbserver_user_state.catch_all_syscalls = catch_all_syscalls;
922         if (!catch_all_syscalls) {
923             memcpy(gdbserver_user_state.catch_syscalls_mask,
924                    catch_syscalls_mask, sizeof(catch_syscalls_mask));
925         }
926         gdb_put_packet("OK");
927         return;
928     }
929 
930 err:
931     gdb_put_packet("E00");
932 }
933 
gdb_handle_query_xfer_siginfo(GArray * params,void * user_ctx)934 void gdb_handle_query_xfer_siginfo(GArray *params, void *user_ctx)
935 {
936     unsigned long offset, len;
937     uint8_t *siginfo_offset;
938 
939     offset = gdb_get_cmd_param(params, 0)->val_ul;
940     len = gdb_get_cmd_param(params, 1)->val_ul;
941 
942     if (offset + len > gdbserver_user_state.siginfo_len) {
943         /* Invalid offset and/or requested length. */
944         gdb_put_packet("E01");
945         return;
946     }
947 
948     siginfo_offset = (uint8_t *)gdbserver_user_state.siginfo + offset;
949 
950     /* Reply */
951     g_string_assign(gdbserver_state.str_buf, "l");
952     gdb_memtox(gdbserver_state.str_buf, (const char *)siginfo_offset, len);
953     gdb_put_packet_binary(gdbserver_state.str_buf->str,
954                           gdbserver_state.str_buf->len, true);
955 }
956