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