xref: /openbmc/qemu/gdbstub/gdbstub.c (revision 4f947b10)
1 /*
2  * gdb server stub
3  *
4  * This implements a subset of the remote protocol as described in:
5  *
6  *   https://sourceware.org/gdb/onlinedocs/gdb/Remote-Protocol.html
7  *
8  * Copyright (c) 2003-2005 Fabrice Bellard
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
22  *
23  * SPDX-License-Identifier: LGPL-2.0+
24  */
25 
26 #include "qemu/osdep.h"
27 #include "qemu/ctype.h"
28 #include "qemu/cutils.h"
29 #include "qemu/module.h"
30 #include "qemu/error-report.h"
31 #include "trace.h"
32 #include "exec/gdbstub.h"
33 #include "gdbstub/commands.h"
34 #include "gdbstub/syscalls.h"
35 #ifdef CONFIG_USER_ONLY
36 #include "accel/tcg/vcpu-state.h"
37 #include "gdbstub/user.h"
38 #else
39 #include "hw/cpu/cluster.h"
40 #include "hw/boards.h"
41 #endif
42 #include "hw/core/cpu.h"
43 
44 #include "sysemu/hw_accel.h"
45 #include "sysemu/runstate.h"
46 #include "exec/replay-core.h"
47 #include "exec/hwaddr.h"
48 
49 #include "internals.h"
50 
51 typedef struct GDBRegisterState {
52     int base_reg;
53     gdb_get_reg_cb get_reg;
54     gdb_set_reg_cb set_reg;
55     const GDBFeature *feature;
56 } GDBRegisterState;
57 
58 GDBState gdbserver_state;
59 
60 void gdb_init_gdbserver_state(void)
61 {
62     g_assert(!gdbserver_state.init);
63     memset(&gdbserver_state, 0, sizeof(GDBState));
64     gdbserver_state.init = true;
65     gdbserver_state.str_buf = g_string_new(NULL);
66     gdbserver_state.mem_buf = g_byte_array_sized_new(MAX_PACKET_LENGTH);
67     gdbserver_state.last_packet = g_byte_array_sized_new(MAX_PACKET_LENGTH + 4);
68 
69     /*
70      * What single-step modes are supported is accelerator dependent.
71      * By default try to use no IRQs and no timers while single
72      * stepping so as to make single stepping like a typical ICE HW step.
73      */
74     gdbserver_state.supported_sstep_flags = accel_supported_gdbstub_sstep_flags();
75     gdbserver_state.sstep_flags = SSTEP_ENABLE | SSTEP_NOIRQ | SSTEP_NOTIMER;
76     gdbserver_state.sstep_flags &= gdbserver_state.supported_sstep_flags;
77 }
78 
79 /* writes 2*len+1 bytes in buf */
80 void gdb_memtohex(GString *buf, const uint8_t *mem, int len)
81 {
82     int i, c;
83     for(i = 0; i < len; i++) {
84         c = mem[i];
85         g_string_append_c(buf, tohex(c >> 4));
86         g_string_append_c(buf, tohex(c & 0xf));
87     }
88     g_string_append_c(buf, '\0');
89 }
90 
91 void gdb_hextomem(GByteArray *mem, const char *buf, int len)
92 {
93     int i;
94 
95     for(i = 0; i < len; i++) {
96         guint8 byte = fromhex(buf[0]) << 4 | fromhex(buf[1]);
97         g_byte_array_append(mem, &byte, 1);
98         buf += 2;
99     }
100 }
101 
102 static void hexdump(const char *buf, int len,
103                     void (*trace_fn)(size_t ofs, char const *text))
104 {
105     char line_buffer[3 * 16 + 4 + 16 + 1];
106 
107     size_t i;
108     for (i = 0; i < len || (i & 0xF); ++i) {
109         size_t byte_ofs = i & 15;
110 
111         if (byte_ofs == 0) {
112             memset(line_buffer, ' ', 3 * 16 + 4 + 16);
113             line_buffer[3 * 16 + 4 + 16] = 0;
114         }
115 
116         size_t col_group = (i >> 2) & 3;
117         size_t hex_col = byte_ofs * 3 + col_group;
118         size_t txt_col = 3 * 16 + 4 + byte_ofs;
119 
120         if (i < len) {
121             char value = buf[i];
122 
123             line_buffer[hex_col + 0] = tohex((value >> 4) & 0xF);
124             line_buffer[hex_col + 1] = tohex((value >> 0) & 0xF);
125             line_buffer[txt_col + 0] = (value >= ' ' && value < 127)
126                     ? value
127                     : '.';
128         }
129 
130         if (byte_ofs == 0xF)
131             trace_fn(i & -16, line_buffer);
132     }
133 }
134 
135 /* return -1 if error, 0 if OK */
136 int gdb_put_packet_binary(const char *buf, int len, bool dump)
137 {
138     int csum, i;
139     uint8_t footer[3];
140 
141     if (dump && trace_event_get_state_backends(TRACE_GDBSTUB_IO_BINARYREPLY)) {
142         hexdump(buf, len, trace_gdbstub_io_binaryreply);
143     }
144 
145     for(;;) {
146         g_byte_array_set_size(gdbserver_state.last_packet, 0);
147         g_byte_array_append(gdbserver_state.last_packet,
148                             (const uint8_t *) "$", 1);
149         g_byte_array_append(gdbserver_state.last_packet,
150                             (const uint8_t *) buf, len);
151         csum = 0;
152         for(i = 0; i < len; i++) {
153             csum += buf[i];
154         }
155         footer[0] = '#';
156         footer[1] = tohex((csum >> 4) & 0xf);
157         footer[2] = tohex((csum) & 0xf);
158         g_byte_array_append(gdbserver_state.last_packet, footer, 3);
159 
160         gdb_put_buffer(gdbserver_state.last_packet->data,
161                    gdbserver_state.last_packet->len);
162 
163         if (gdb_got_immediate_ack()) {
164             break;
165         }
166     }
167     return 0;
168 }
169 
170 /* return -1 if error, 0 if OK */
171 int gdb_put_packet(const char *buf)
172 {
173     trace_gdbstub_io_reply(buf);
174 
175     return gdb_put_packet_binary(buf, strlen(buf), false);
176 }
177 
178 void gdb_put_strbuf(void)
179 {
180     gdb_put_packet(gdbserver_state.str_buf->str);
181 }
182 
183 /* Encode data using the encoding for 'x' packets.  */
184 void gdb_memtox(GString *buf, const char *mem, int len)
185 {
186     char c;
187 
188     while (len--) {
189         c = *(mem++);
190         switch (c) {
191         case '#': case '$': case '*': case '}':
192             g_string_append_c(buf, '}');
193             g_string_append_c(buf, c ^ 0x20);
194             break;
195         default:
196             g_string_append_c(buf, c);
197             break;
198         }
199     }
200 }
201 
202 static uint32_t gdb_get_cpu_pid(CPUState *cpu)
203 {
204 #ifdef CONFIG_USER_ONLY
205     return getpid();
206 #else
207     if (cpu->cluster_index == UNASSIGNED_CLUSTER_INDEX) {
208         /* Return the default process' PID */
209         int index = gdbserver_state.process_num - 1;
210         return gdbserver_state.processes[index].pid;
211     }
212     return cpu->cluster_index + 1;
213 #endif
214 }
215 
216 GDBProcess *gdb_get_process(uint32_t pid)
217 {
218     int i;
219 
220     if (!pid) {
221         /* 0 means any process, we take the first one */
222         return &gdbserver_state.processes[0];
223     }
224 
225     for (i = 0; i < gdbserver_state.process_num; i++) {
226         if (gdbserver_state.processes[i].pid == pid) {
227             return &gdbserver_state.processes[i];
228         }
229     }
230 
231     return NULL;
232 }
233 
234 static GDBProcess *gdb_get_cpu_process(CPUState *cpu)
235 {
236     return gdb_get_process(gdb_get_cpu_pid(cpu));
237 }
238 
239 static CPUState *find_cpu(uint32_t thread_id)
240 {
241     CPUState *cpu;
242 
243     CPU_FOREACH(cpu) {
244         if (gdb_get_cpu_index(cpu) == thread_id) {
245             return cpu;
246         }
247     }
248 
249     return NULL;
250 }
251 
252 CPUState *gdb_get_first_cpu_in_process(GDBProcess *process)
253 {
254     CPUState *cpu;
255 
256     CPU_FOREACH(cpu) {
257         if (gdb_get_cpu_pid(cpu) == process->pid) {
258             return cpu;
259         }
260     }
261 
262     return NULL;
263 }
264 
265 static CPUState *gdb_next_cpu_in_process(CPUState *cpu)
266 {
267     uint32_t pid = gdb_get_cpu_pid(cpu);
268     cpu = CPU_NEXT(cpu);
269 
270     while (cpu) {
271         if (gdb_get_cpu_pid(cpu) == pid) {
272             break;
273         }
274 
275         cpu = CPU_NEXT(cpu);
276     }
277 
278     return cpu;
279 }
280 
281 /* Return the cpu following @cpu, while ignoring unattached processes. */
282 static CPUState *gdb_next_attached_cpu(CPUState *cpu)
283 {
284     cpu = CPU_NEXT(cpu);
285 
286     while (cpu) {
287         if (gdb_get_cpu_process(cpu)->attached) {
288             break;
289         }
290 
291         cpu = CPU_NEXT(cpu);
292     }
293 
294     return cpu;
295 }
296 
297 /* Return the first attached cpu */
298 CPUState *gdb_first_attached_cpu(void)
299 {
300     CPUState *cpu = first_cpu;
301     GDBProcess *process = gdb_get_cpu_process(cpu);
302 
303     if (!process->attached) {
304         return gdb_next_attached_cpu(cpu);
305     }
306 
307     return cpu;
308 }
309 
310 static CPUState *gdb_get_cpu(uint32_t pid, uint32_t tid)
311 {
312     GDBProcess *process;
313     CPUState *cpu;
314 
315     if (!pid && !tid) {
316         /* 0 means any process/thread, we take the first attached one */
317         return gdb_first_attached_cpu();
318     } else if (pid && !tid) {
319         /* any thread in a specific process */
320         process = gdb_get_process(pid);
321 
322         if (process == NULL) {
323             return NULL;
324         }
325 
326         if (!process->attached) {
327             return NULL;
328         }
329 
330         return gdb_get_first_cpu_in_process(process);
331     } else {
332         /* a specific thread */
333         cpu = find_cpu(tid);
334 
335         if (cpu == NULL) {
336             return NULL;
337         }
338 
339         process = gdb_get_cpu_process(cpu);
340 
341         if (pid && process->pid != pid) {
342             return NULL;
343         }
344 
345         if (!process->attached) {
346             return NULL;
347         }
348 
349         return cpu;
350     }
351 }
352 
353 static const char *get_feature_xml(const char *p, const char **newp,
354                                    GDBProcess *process)
355 {
356     CPUState *cpu = gdb_get_first_cpu_in_process(process);
357     CPUClass *cc = CPU_GET_CLASS(cpu);
358     GDBRegisterState *r;
359     size_t len;
360 
361     /*
362      * qXfer:features:read:ANNEX:OFFSET,LENGTH'
363      *                     ^p    ^newp
364      */
365     char *term = strchr(p, ':');
366     *newp = term + 1;
367     len = term - p;
368 
369     /* Is it the main target xml? */
370     if (strncmp(p, "target.xml", len) == 0) {
371         if (!process->target_xml) {
372             g_autoptr(GPtrArray) xml = g_ptr_array_new_with_free_func(g_free);
373 
374             g_ptr_array_add(
375                 xml,
376                 g_strdup("<?xml version=\"1.0\"?>"
377                          "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
378                          "<target>"));
379 
380             if (cc->gdb_arch_name) {
381                 g_ptr_array_add(
382                     xml,
383                     g_markup_printf_escaped("<architecture>%s</architecture>",
384                                             cc->gdb_arch_name(cpu)));
385             }
386             for (guint i = 0; i < cpu->gdb_regs->len; i++) {
387                 r = &g_array_index(cpu->gdb_regs, GDBRegisterState, i);
388                 g_ptr_array_add(
389                     xml,
390                     g_markup_printf_escaped("<xi:include href=\"%s\"/>",
391                                             r->feature->xmlname));
392             }
393             g_ptr_array_add(xml, g_strdup("</target>"));
394             g_ptr_array_add(xml, NULL);
395 
396             process->target_xml = g_strjoinv(NULL, (void *)xml->pdata);
397         }
398         return process->target_xml;
399     }
400     /* Is it one of the features? */
401     for (guint i = 0; i < cpu->gdb_regs->len; i++) {
402         r = &g_array_index(cpu->gdb_regs, GDBRegisterState, i);
403         if (strncmp(p, r->feature->xmlname, len) == 0) {
404             return r->feature->xml;
405         }
406     }
407 
408     /* failed */
409     return NULL;
410 }
411 
412 void gdb_feature_builder_init(GDBFeatureBuilder *builder, GDBFeature *feature,
413                               const char *name, const char *xmlname,
414                               int base_reg)
415 {
416     char *header = g_markup_printf_escaped(
417         "<?xml version=\"1.0\"?>"
418         "<!DOCTYPE feature SYSTEM \"gdb-target.dtd\">"
419         "<feature name=\"%s\">",
420         name);
421 
422     builder->feature = feature;
423     builder->xml = g_ptr_array_new();
424     g_ptr_array_add(builder->xml, header);
425     builder->regs = g_ptr_array_new();
426     builder->base_reg = base_reg;
427     feature->xmlname = xmlname;
428     feature->name = name;
429 }
430 
431 void gdb_feature_builder_append_tag(const GDBFeatureBuilder *builder,
432                                     const char *format, ...)
433 {
434     va_list ap;
435     va_start(ap, format);
436     g_ptr_array_add(builder->xml, g_markup_vprintf_escaped(format, ap));
437     va_end(ap);
438 }
439 
440 void gdb_feature_builder_append_reg(const GDBFeatureBuilder *builder,
441                                     const char *name,
442                                     int bitsize,
443                                     int regnum,
444                                     const char *type,
445                                     const char *group)
446 {
447     if (builder->regs->len <= regnum) {
448         g_ptr_array_set_size(builder->regs, regnum + 1);
449     }
450 
451     builder->regs->pdata[regnum] = (gpointer *)name;
452 
453     if (group) {
454         gdb_feature_builder_append_tag(
455             builder,
456             "<reg name=\"%s\" bitsize=\"%d\" regnum=\"%d\" type=\"%s\" group=\"%s\"/>",
457             name, bitsize, builder->base_reg + regnum, type, group);
458     } else {
459         gdb_feature_builder_append_tag(
460             builder,
461             "<reg name=\"%s\" bitsize=\"%d\" regnum=\"%d\" type=\"%s\"/>",
462             name, bitsize, builder->base_reg + regnum, type);
463     }
464 }
465 
466 void gdb_feature_builder_end(const GDBFeatureBuilder *builder)
467 {
468     g_ptr_array_add(builder->xml, (void *)"</feature>");
469     g_ptr_array_add(builder->xml, NULL);
470 
471     builder->feature->xml = g_strjoinv(NULL, (void *)builder->xml->pdata);
472 
473     for (guint i = 0; i < builder->xml->len - 2; i++) {
474         g_free(g_ptr_array_index(builder->xml, i));
475     }
476 
477     g_ptr_array_free(builder->xml, TRUE);
478 
479     builder->feature->num_regs = builder->regs->len;
480     builder->feature->regs = (void *)g_ptr_array_free(builder->regs, FALSE);
481 }
482 
483 const GDBFeature *gdb_find_static_feature(const char *xmlname)
484 {
485     const GDBFeature *feature;
486 
487     for (feature = gdb_static_features; feature->xmlname; feature++) {
488         if (!strcmp(feature->xmlname, xmlname)) {
489             return feature;
490         }
491     }
492 
493     g_assert_not_reached();
494 }
495 
496 GArray *gdb_get_register_list(CPUState *cpu)
497 {
498     GArray *results = g_array_new(true, true, sizeof(GDBRegDesc));
499 
500     /* registers are only available once the CPU is initialised */
501     if (!cpu->gdb_regs) {
502         return results;
503     }
504 
505     for (int f = 0; f < cpu->gdb_regs->len; f++) {
506         GDBRegisterState *r = &g_array_index(cpu->gdb_regs, GDBRegisterState, f);
507         for (int i = 0; i < r->feature->num_regs; i++) {
508             const char *name = r->feature->regs[i];
509             GDBRegDesc desc = {
510                 r->base_reg + i,
511                 name,
512                 r->feature->name
513             };
514             g_array_append_val(results, desc);
515         }
516     }
517 
518     return results;
519 }
520 
521 int gdb_read_register(CPUState *cpu, GByteArray *buf, int reg)
522 {
523     CPUClass *cc = CPU_GET_CLASS(cpu);
524     GDBRegisterState *r;
525 
526     if (reg < cc->gdb_num_core_regs) {
527         return cc->gdb_read_register(cpu, buf, reg);
528     }
529 
530     for (guint i = 0; i < cpu->gdb_regs->len; i++) {
531         r = &g_array_index(cpu->gdb_regs, GDBRegisterState, i);
532         if (r->base_reg <= reg && reg < r->base_reg + r->feature->num_regs) {
533             return r->get_reg(cpu, buf, reg - r->base_reg);
534         }
535     }
536     return 0;
537 }
538 
539 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
540 {
541     CPUClass *cc = CPU_GET_CLASS(cpu);
542     GDBRegisterState *r;
543 
544     if (reg < cc->gdb_num_core_regs) {
545         return cc->gdb_write_register(cpu, mem_buf, reg);
546     }
547 
548     for (guint i = 0; i < cpu->gdb_regs->len; i++) {
549         r =  &g_array_index(cpu->gdb_regs, GDBRegisterState, i);
550         if (r->base_reg <= reg && reg < r->base_reg + r->feature->num_regs) {
551             return r->set_reg(cpu, mem_buf, reg - r->base_reg);
552         }
553     }
554     return 0;
555 }
556 
557 static void gdb_register_feature(CPUState *cpu, int base_reg,
558                                  gdb_get_reg_cb get_reg, gdb_set_reg_cb set_reg,
559                                  const GDBFeature *feature)
560 {
561     GDBRegisterState s = {
562         .base_reg = base_reg,
563         .get_reg = get_reg,
564         .set_reg = set_reg,
565         .feature = feature
566     };
567 
568     g_array_append_val(cpu->gdb_regs, s);
569 }
570 
571 void gdb_init_cpu(CPUState *cpu)
572 {
573     CPUClass *cc = CPU_GET_CLASS(cpu);
574     const GDBFeature *feature;
575 
576     cpu->gdb_regs = g_array_new(false, false, sizeof(GDBRegisterState));
577 
578     if (cc->gdb_core_xml_file) {
579         feature = gdb_find_static_feature(cc->gdb_core_xml_file);
580         gdb_register_feature(cpu, 0,
581                              cc->gdb_read_register, cc->gdb_write_register,
582                              feature);
583         cpu->gdb_num_regs = cpu->gdb_num_g_regs = feature->num_regs;
584     }
585 
586     if (cc->gdb_num_core_regs) {
587         cpu->gdb_num_regs = cpu->gdb_num_g_regs = cc->gdb_num_core_regs;
588     }
589 }
590 
591 void gdb_register_coprocessor(CPUState *cpu,
592                               gdb_get_reg_cb get_reg, gdb_set_reg_cb set_reg,
593                               const GDBFeature *feature, int g_pos)
594 {
595     GDBRegisterState *s;
596     guint i;
597     int base_reg = cpu->gdb_num_regs;
598 
599     for (i = 0; i < cpu->gdb_regs->len; i++) {
600         /* Check for duplicates.  */
601         s = &g_array_index(cpu->gdb_regs, GDBRegisterState, i);
602         if (s->feature == feature) {
603             return;
604         }
605     }
606 
607     gdb_register_feature(cpu, base_reg, get_reg, set_reg, feature);
608 
609     /* Add to end of list.  */
610     cpu->gdb_num_regs += feature->num_regs;
611     if (g_pos) {
612         if (g_pos != base_reg) {
613             error_report("Error: Bad gdb register numbering for '%s', "
614                          "expected %d got %d", feature->xml, g_pos, base_reg);
615         } else {
616             cpu->gdb_num_g_regs = cpu->gdb_num_regs;
617         }
618     }
619 }
620 
621 void gdb_unregister_coprocessor_all(CPUState *cpu)
622 {
623     /*
624      * Safe to nuke everything. GDBRegisterState::xml is static const char so
625      * it won't be freed
626      */
627     g_array_free(cpu->gdb_regs, true);
628 
629     cpu->gdb_regs = NULL;
630     cpu->gdb_num_regs = 0;
631     cpu->gdb_num_g_regs = 0;
632 }
633 
634 static void gdb_process_breakpoint_remove_all(GDBProcess *p)
635 {
636     CPUState *cpu = gdb_get_first_cpu_in_process(p);
637 
638     while (cpu) {
639         gdb_breakpoint_remove_all(cpu);
640         cpu = gdb_next_cpu_in_process(cpu);
641     }
642 }
643 
644 
645 static void gdb_set_cpu_pc(vaddr pc)
646 {
647     CPUState *cpu = gdbserver_state.c_cpu;
648 
649     cpu_synchronize_state(cpu);
650     cpu_set_pc(cpu, pc);
651 }
652 
653 void gdb_append_thread_id(CPUState *cpu, GString *buf)
654 {
655     if (gdbserver_state.multiprocess) {
656         g_string_append_printf(buf, "p%02x.%02x",
657                                gdb_get_cpu_pid(cpu), gdb_get_cpu_index(cpu));
658     } else {
659         g_string_append_printf(buf, "%02x", gdb_get_cpu_index(cpu));
660     }
661 }
662 
663 static GDBThreadIdKind read_thread_id(const char *buf, const char **end_buf,
664                                       uint32_t *pid, uint32_t *tid)
665 {
666     unsigned long p, t;
667     int ret;
668 
669     if (*buf == 'p') {
670         buf++;
671         ret = qemu_strtoul(buf, &buf, 16, &p);
672 
673         if (ret) {
674             return GDB_READ_THREAD_ERR;
675         }
676 
677         /* Skip '.' */
678         buf++;
679     } else {
680         p = 0;
681     }
682 
683     ret = qemu_strtoul(buf, &buf, 16, &t);
684 
685     if (ret) {
686         return GDB_READ_THREAD_ERR;
687     }
688 
689     *end_buf = buf;
690 
691     if (p == -1) {
692         return GDB_ALL_PROCESSES;
693     }
694 
695     if (pid) {
696         *pid = p;
697     }
698 
699     if (t == -1) {
700         return GDB_ALL_THREADS;
701     }
702 
703     if (tid) {
704         *tid = t;
705     }
706 
707     return GDB_ONE_THREAD;
708 }
709 
710 /**
711  * gdb_handle_vcont - Parses and handles a vCont packet.
712  * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
713  *         a format error, 0 on success.
714  */
715 static int gdb_handle_vcont(const char *p)
716 {
717     int res, signal = 0;
718     char cur_action;
719     unsigned long tmp;
720     uint32_t pid, tid;
721     GDBProcess *process;
722     CPUState *cpu;
723     GDBThreadIdKind kind;
724     unsigned int max_cpus = gdb_get_max_cpus();
725     /* uninitialised CPUs stay 0 */
726     g_autofree char *newstates = g_new0(char, max_cpus);
727 
728     /* mark valid CPUs with 1 */
729     CPU_FOREACH(cpu) {
730         newstates[cpu->cpu_index] = 1;
731     }
732 
733     /*
734      * res keeps track of what error we are returning, with -ENOTSUP meaning
735      * that the command is unknown or unsupported, thus returning an empty
736      * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
737      *  or incorrect parameters passed.
738      */
739     res = 0;
740 
741     /*
742      * target_count and last_target keep track of how many CPUs we are going to
743      * step or resume, and a pointer to the state structure of one of them,
744      * respectively
745      */
746     int target_count = 0;
747     CPUState *last_target = NULL;
748 
749     while (*p) {
750         if (*p++ != ';') {
751             return -ENOTSUP;
752         }
753 
754         cur_action = *p++;
755         if (cur_action == 'C' || cur_action == 'S') {
756             cur_action = qemu_tolower(cur_action);
757             res = qemu_strtoul(p, &p, 16, &tmp);
758             if (res) {
759                 return res;
760             }
761             signal = gdb_signal_to_target(tmp);
762         } else if (cur_action != 'c' && cur_action != 's') {
763             /* unknown/invalid/unsupported command */
764             return -ENOTSUP;
765         }
766 
767         if (*p == '\0' || *p == ';') {
768             /*
769              * No thread specifier, action is on "all threads". The
770              * specification is unclear regarding the process to act on. We
771              * choose all processes.
772              */
773             kind = GDB_ALL_PROCESSES;
774         } else if (*p++ == ':') {
775             kind = read_thread_id(p, &p, &pid, &tid);
776         } else {
777             return -ENOTSUP;
778         }
779 
780         switch (kind) {
781         case GDB_READ_THREAD_ERR:
782             return -EINVAL;
783 
784         case GDB_ALL_PROCESSES:
785             cpu = gdb_first_attached_cpu();
786             while (cpu) {
787                 if (newstates[cpu->cpu_index] == 1) {
788                     newstates[cpu->cpu_index] = cur_action;
789 
790                     target_count++;
791                     last_target = cpu;
792                 }
793 
794                 cpu = gdb_next_attached_cpu(cpu);
795             }
796             break;
797 
798         case GDB_ALL_THREADS:
799             process = gdb_get_process(pid);
800 
801             if (!process->attached) {
802                 return -EINVAL;
803             }
804 
805             cpu = gdb_get_first_cpu_in_process(process);
806             while (cpu) {
807                 if (newstates[cpu->cpu_index] == 1) {
808                     newstates[cpu->cpu_index] = cur_action;
809 
810                     target_count++;
811                     last_target = cpu;
812                 }
813 
814                 cpu = gdb_next_cpu_in_process(cpu);
815             }
816             break;
817 
818         case GDB_ONE_THREAD:
819             cpu = gdb_get_cpu(pid, tid);
820 
821             /* invalid CPU/thread specified */
822             if (!cpu) {
823                 return -EINVAL;
824             }
825 
826             /* only use if no previous match occourred */
827             if (newstates[cpu->cpu_index] == 1) {
828                 newstates[cpu->cpu_index] = cur_action;
829 
830                 target_count++;
831                 last_target = cpu;
832             }
833             break;
834         }
835     }
836 
837     /*
838      * if we're about to resume a specific set of CPUs/threads, make it so that
839      * in case execution gets interrupted, we can send GDB a stop reply with a
840      * correct value. it doesn't really matter which CPU we tell GDB the signal
841      * happened in (VM pauses stop all of them anyway), so long as it is one of
842      * the ones we resumed/single stepped here.
843      */
844     if (target_count > 0) {
845         gdbserver_state.c_cpu = last_target;
846     }
847 
848     gdbserver_state.signal = signal;
849     gdb_continue_partial(newstates);
850     return res;
851 }
852 
853 static const char *cmd_next_param(const char *param, const char delimiter)
854 {
855     static const char all_delimiters[] = ",;:=";
856     char curr_delimiters[2] = {0};
857     const char *delimiters;
858 
859     if (delimiter == '?') {
860         delimiters = all_delimiters;
861     } else if (delimiter == '0') {
862         return strchr(param, '\0');
863     } else if (delimiter == '.' && *param) {
864         return param + 1;
865     } else {
866         curr_delimiters[0] = delimiter;
867         delimiters = curr_delimiters;
868     }
869 
870     param += strcspn(param, delimiters);
871     if (*param) {
872         param++;
873     }
874     return param;
875 }
876 
877 static int cmd_parse_params(const char *data, const char *schema,
878                             GArray *params)
879 {
880     const char *curr_schema, *curr_data;
881 
882     g_assert(schema);
883     g_assert(params->len == 0);
884 
885     curr_schema = schema;
886     curr_data = data;
887     while (curr_schema[0] && curr_schema[1] && *curr_data) {
888         GdbCmdVariant this_param;
889 
890         switch (curr_schema[0]) {
891         case 'l':
892             if (qemu_strtoul(curr_data, &curr_data, 16,
893                              &this_param.val_ul)) {
894                 return -EINVAL;
895             }
896             curr_data = cmd_next_param(curr_data, curr_schema[1]);
897             g_array_append_val(params, this_param);
898             break;
899         case 'L':
900             if (qemu_strtou64(curr_data, &curr_data, 16,
901                               (uint64_t *)&this_param.val_ull)) {
902                 return -EINVAL;
903             }
904             curr_data = cmd_next_param(curr_data, curr_schema[1]);
905             g_array_append_val(params, this_param);
906             break;
907         case 's':
908             this_param.data = curr_data;
909             curr_data = cmd_next_param(curr_data, curr_schema[1]);
910             g_array_append_val(params, this_param);
911             break;
912         case 'o':
913             this_param.opcode = *(uint8_t *)curr_data;
914             curr_data = cmd_next_param(curr_data, curr_schema[1]);
915             g_array_append_val(params, this_param);
916             break;
917         case 't':
918             this_param.thread_id.kind =
919                 read_thread_id(curr_data, &curr_data,
920                                &this_param.thread_id.pid,
921                                &this_param.thread_id.tid);
922             curr_data = cmd_next_param(curr_data, curr_schema[1]);
923             g_array_append_val(params, this_param);
924             break;
925         case '?':
926             curr_data = cmd_next_param(curr_data, curr_schema[1]);
927             break;
928         default:
929             return -EINVAL;
930         }
931         curr_schema += 2;
932     }
933 
934     return 0;
935 }
936 
937 static inline int startswith(const char *string, const char *pattern)
938 {
939   return !strncmp(string, pattern, strlen(pattern));
940 }
941 
942 static bool process_string_cmd(const char *data,
943                                const GdbCmdParseEntry *cmds, int num_cmds)
944 {
945     int i;
946     g_autoptr(GArray) params = g_array_new(false, true, sizeof(GdbCmdVariant));
947 
948     if (!cmds) {
949         return false;
950     }
951 
952     for (i = 0; i < num_cmds; i++) {
953         const GdbCmdParseEntry *cmd = &cmds[i];
954         void *user_ctx = NULL;
955         g_assert(cmd->handler && cmd->cmd);
956 
957         if ((cmd->cmd_startswith && !startswith(data, cmd->cmd)) ||
958             (!cmd->cmd_startswith && strcmp(cmd->cmd, data))) {
959             continue;
960         }
961 
962         if (cmd->schema) {
963             if (cmd_parse_params(&data[strlen(cmd->cmd)],
964                                  cmd->schema, params)) {
965                 return false;
966             }
967         }
968 
969         if (cmd->need_cpu_context) {
970             user_ctx = (void *)gdbserver_state.g_cpu;
971         }
972 
973         gdbserver_state.allow_stop_reply = cmd->allow_stop_reply;
974         cmd->handler(params, user_ctx);
975         return true;
976     }
977 
978     return false;
979 }
980 
981 static void run_cmd_parser(const char *data, const GdbCmdParseEntry *cmd)
982 {
983     if (!data) {
984         return;
985     }
986 
987     g_string_set_size(gdbserver_state.str_buf, 0);
988     g_byte_array_set_size(gdbserver_state.mem_buf, 0);
989 
990     /* In case there was an error during the command parsing we must
991     * send a NULL packet to indicate the command is not supported */
992     if (!process_string_cmd(data, cmd, 1)) {
993         gdb_put_packet("");
994     }
995 }
996 
997 static void handle_detach(GArray *params, void *user_ctx)
998 {
999     GDBProcess *process;
1000     uint32_t pid = 1;
1001 
1002     if (gdbserver_state.multiprocess) {
1003         if (!params->len) {
1004             gdb_put_packet("E22");
1005             return;
1006         }
1007 
1008         pid = gdb_get_cmd_param(params, 0)->val_ul;
1009     }
1010 
1011 #ifdef CONFIG_USER_ONLY
1012     if (gdb_handle_detach_user(pid)) {
1013         return;
1014     }
1015 #endif
1016 
1017     process = gdb_get_process(pid);
1018     gdb_process_breakpoint_remove_all(process);
1019     process->attached = false;
1020 
1021     if (pid == gdb_get_cpu_pid(gdbserver_state.c_cpu)) {
1022         gdbserver_state.c_cpu = gdb_first_attached_cpu();
1023     }
1024 
1025     if (pid == gdb_get_cpu_pid(gdbserver_state.g_cpu)) {
1026         gdbserver_state.g_cpu = gdb_first_attached_cpu();
1027     }
1028 
1029     if (!gdbserver_state.c_cpu) {
1030         /* No more process attached */
1031         gdb_disable_syscalls();
1032         gdb_continue();
1033     }
1034     gdb_put_packet("OK");
1035 }
1036 
1037 static void handle_thread_alive(GArray *params, void *user_ctx)
1038 {
1039     CPUState *cpu;
1040 
1041     if (!params->len) {
1042         gdb_put_packet("E22");
1043         return;
1044     }
1045 
1046     if (gdb_get_cmd_param(params, 0)->thread_id.kind == GDB_READ_THREAD_ERR) {
1047         gdb_put_packet("E22");
1048         return;
1049     }
1050 
1051     cpu = gdb_get_cpu(gdb_get_cmd_param(params, 0)->thread_id.pid,
1052                       gdb_get_cmd_param(params, 0)->thread_id.tid);
1053     if (!cpu) {
1054         gdb_put_packet("E22");
1055         return;
1056     }
1057 
1058     gdb_put_packet("OK");
1059 }
1060 
1061 static void handle_continue(GArray *params, void *user_ctx)
1062 {
1063     if (params->len) {
1064         gdb_set_cpu_pc(gdb_get_cmd_param(params, 0)->val_ull);
1065     }
1066 
1067     gdbserver_state.signal = 0;
1068     gdb_continue();
1069 }
1070 
1071 static void handle_cont_with_sig(GArray *params, void *user_ctx)
1072 {
1073     unsigned long signal = 0;
1074 
1075     /*
1076      * Note: C sig;[addr] is currently unsupported and we simply
1077      *       omit the addr parameter
1078      */
1079     if (params->len) {
1080         signal = gdb_get_cmd_param(params, 0)->val_ul;
1081     }
1082 
1083     gdbserver_state.signal = gdb_signal_to_target(signal);
1084     if (gdbserver_state.signal == -1) {
1085         gdbserver_state.signal = 0;
1086     }
1087     gdb_continue();
1088 }
1089 
1090 static void handle_set_thread(GArray *params, void *user_ctx)
1091 {
1092     uint32_t pid, tid;
1093     CPUState *cpu;
1094 
1095     if (params->len != 2) {
1096         gdb_put_packet("E22");
1097         return;
1098     }
1099 
1100     if (gdb_get_cmd_param(params, 1)->thread_id.kind == GDB_READ_THREAD_ERR) {
1101         gdb_put_packet("E22");
1102         return;
1103     }
1104 
1105     if (gdb_get_cmd_param(params, 1)->thread_id.kind != GDB_ONE_THREAD) {
1106         gdb_put_packet("OK");
1107         return;
1108     }
1109 
1110     pid = gdb_get_cmd_param(params, 1)->thread_id.pid;
1111     tid = gdb_get_cmd_param(params, 1)->thread_id.tid;
1112 #ifdef CONFIG_USER_ONLY
1113     if (gdb_handle_set_thread_user(pid, tid)) {
1114         return;
1115     }
1116 #endif
1117     cpu = gdb_get_cpu(pid, tid);
1118     if (!cpu) {
1119         gdb_put_packet("E22");
1120         return;
1121     }
1122 
1123     /*
1124      * Note: This command is deprecated and modern gdb's will be using the
1125      *       vCont command instead.
1126      */
1127     switch (gdb_get_cmd_param(params, 0)->opcode) {
1128     case 'c':
1129         gdbserver_state.c_cpu = cpu;
1130         gdb_put_packet("OK");
1131         break;
1132     case 'g':
1133         gdbserver_state.g_cpu = cpu;
1134         gdb_put_packet("OK");
1135         break;
1136     default:
1137         gdb_put_packet("E22");
1138         break;
1139     }
1140 }
1141 
1142 static void handle_insert_bp(GArray *params, void *user_ctx)
1143 {
1144     int res;
1145 
1146     if (params->len != 3) {
1147         gdb_put_packet("E22");
1148         return;
1149     }
1150 
1151     res = gdb_breakpoint_insert(gdbserver_state.c_cpu,
1152                                 gdb_get_cmd_param(params, 0)->val_ul,
1153                                 gdb_get_cmd_param(params, 1)->val_ull,
1154                                 gdb_get_cmd_param(params, 2)->val_ull);
1155     if (res >= 0) {
1156         gdb_put_packet("OK");
1157         return;
1158     } else if (res == -ENOSYS) {
1159         gdb_put_packet("");
1160         return;
1161     }
1162 
1163     gdb_put_packet("E22");
1164 }
1165 
1166 static void handle_remove_bp(GArray *params, void *user_ctx)
1167 {
1168     int res;
1169 
1170     if (params->len != 3) {
1171         gdb_put_packet("E22");
1172         return;
1173     }
1174 
1175     res = gdb_breakpoint_remove(gdbserver_state.c_cpu,
1176                                 gdb_get_cmd_param(params, 0)->val_ul,
1177                                 gdb_get_cmd_param(params, 1)->val_ull,
1178                                 gdb_get_cmd_param(params, 2)->val_ull);
1179     if (res >= 0) {
1180         gdb_put_packet("OK");
1181         return;
1182     } else if (res == -ENOSYS) {
1183         gdb_put_packet("");
1184         return;
1185     }
1186 
1187     gdb_put_packet("E22");
1188 }
1189 
1190 /*
1191  * handle_set/get_reg
1192  *
1193  * Older gdb are really dumb, and don't use 'G/g' if 'P/p' is available.
1194  * This works, but can be very slow. Anything new enough to understand
1195  * XML also knows how to use this properly. However to use this we
1196  * need to define a local XML file as well as be talking to a
1197  * reasonably modern gdb. Responding with an empty packet will cause
1198  * the remote gdb to fallback to older methods.
1199  */
1200 
1201 static void handle_set_reg(GArray *params, void *user_ctx)
1202 {
1203     int reg_size;
1204 
1205     if (params->len != 2) {
1206         gdb_put_packet("E22");
1207         return;
1208     }
1209 
1210     reg_size = strlen(gdb_get_cmd_param(params, 1)->data) / 2;
1211     gdb_hextomem(gdbserver_state.mem_buf, gdb_get_cmd_param(params, 1)->data, reg_size);
1212     gdb_write_register(gdbserver_state.g_cpu, gdbserver_state.mem_buf->data,
1213                        gdb_get_cmd_param(params, 0)->val_ull);
1214     gdb_put_packet("OK");
1215 }
1216 
1217 static void handle_get_reg(GArray *params, void *user_ctx)
1218 {
1219     int reg_size;
1220 
1221     if (!params->len) {
1222         gdb_put_packet("E14");
1223         return;
1224     }
1225 
1226     reg_size = gdb_read_register(gdbserver_state.g_cpu,
1227                                  gdbserver_state.mem_buf,
1228                                  gdb_get_cmd_param(params, 0)->val_ull);
1229     if (!reg_size) {
1230         gdb_put_packet("E14");
1231         return;
1232     } else {
1233         g_byte_array_set_size(gdbserver_state.mem_buf, reg_size);
1234     }
1235 
1236     gdb_memtohex(gdbserver_state.str_buf,
1237                  gdbserver_state.mem_buf->data, reg_size);
1238     gdb_put_strbuf();
1239 }
1240 
1241 static void handle_write_mem(GArray *params, void *user_ctx)
1242 {
1243     if (params->len != 3) {
1244         gdb_put_packet("E22");
1245         return;
1246     }
1247 
1248     /* gdb_hextomem() reads 2*len bytes */
1249     if (gdb_get_cmd_param(params, 1)->val_ull >
1250         strlen(gdb_get_cmd_param(params, 2)->data) / 2) {
1251         gdb_put_packet("E22");
1252         return;
1253     }
1254 
1255     gdb_hextomem(gdbserver_state.mem_buf, gdb_get_cmd_param(params, 2)->data,
1256                  gdb_get_cmd_param(params, 1)->val_ull);
1257     if (gdb_target_memory_rw_debug(gdbserver_state.g_cpu,
1258                                    gdb_get_cmd_param(params, 0)->val_ull,
1259                                    gdbserver_state.mem_buf->data,
1260                                    gdbserver_state.mem_buf->len, true)) {
1261         gdb_put_packet("E14");
1262         return;
1263     }
1264 
1265     gdb_put_packet("OK");
1266 }
1267 
1268 static void handle_read_mem(GArray *params, void *user_ctx)
1269 {
1270     if (params->len != 2) {
1271         gdb_put_packet("E22");
1272         return;
1273     }
1274 
1275     /* gdb_memtohex() doubles the required space */
1276     if (gdb_get_cmd_param(params, 1)->val_ull > MAX_PACKET_LENGTH / 2) {
1277         gdb_put_packet("E22");
1278         return;
1279     }
1280 
1281     g_byte_array_set_size(gdbserver_state.mem_buf,
1282                           gdb_get_cmd_param(params, 1)->val_ull);
1283 
1284     if (gdb_target_memory_rw_debug(gdbserver_state.g_cpu,
1285                                    gdb_get_cmd_param(params, 0)->val_ull,
1286                                    gdbserver_state.mem_buf->data,
1287                                    gdbserver_state.mem_buf->len, false)) {
1288         gdb_put_packet("E14");
1289         return;
1290     }
1291 
1292     gdb_memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data,
1293              gdbserver_state.mem_buf->len);
1294     gdb_put_strbuf();
1295 }
1296 
1297 static void handle_write_all_regs(GArray *params, void *user_ctx)
1298 {
1299     int reg_id;
1300     size_t len;
1301     uint8_t *registers;
1302     int reg_size;
1303 
1304     if (!params->len) {
1305         return;
1306     }
1307 
1308     cpu_synchronize_state(gdbserver_state.g_cpu);
1309     len = strlen(gdb_get_cmd_param(params, 0)->data) / 2;
1310     gdb_hextomem(gdbserver_state.mem_buf, gdb_get_cmd_param(params, 0)->data, len);
1311     registers = gdbserver_state.mem_buf->data;
1312     for (reg_id = 0;
1313          reg_id < gdbserver_state.g_cpu->gdb_num_g_regs && len > 0;
1314          reg_id++) {
1315         reg_size = gdb_write_register(gdbserver_state.g_cpu, registers, reg_id);
1316         len -= reg_size;
1317         registers += reg_size;
1318     }
1319     gdb_put_packet("OK");
1320 }
1321 
1322 static void handle_read_all_regs(GArray *params, void *user_ctx)
1323 {
1324     int reg_id;
1325     size_t len;
1326 
1327     cpu_synchronize_state(gdbserver_state.g_cpu);
1328     g_byte_array_set_size(gdbserver_state.mem_buf, 0);
1329     len = 0;
1330     for (reg_id = 0; reg_id < gdbserver_state.g_cpu->gdb_num_g_regs; reg_id++) {
1331         len += gdb_read_register(gdbserver_state.g_cpu,
1332                                  gdbserver_state.mem_buf,
1333                                  reg_id);
1334     }
1335     g_assert(len == gdbserver_state.mem_buf->len);
1336 
1337     gdb_memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data, len);
1338     gdb_put_strbuf();
1339 }
1340 
1341 
1342 static void handle_step(GArray *params, void *user_ctx)
1343 {
1344     if (params->len) {
1345         gdb_set_cpu_pc(gdb_get_cmd_param(params, 0)->val_ull);
1346     }
1347 
1348     cpu_single_step(gdbserver_state.c_cpu, gdbserver_state.sstep_flags);
1349     gdb_continue();
1350 }
1351 
1352 static void handle_backward(GArray *params, void *user_ctx)
1353 {
1354     if (!gdb_can_reverse()) {
1355         gdb_put_packet("E22");
1356     }
1357     if (params->len == 1) {
1358         switch (gdb_get_cmd_param(params, 0)->opcode) {
1359         case 's':
1360             if (replay_reverse_step()) {
1361                 gdb_continue();
1362             } else {
1363                 gdb_put_packet("E14");
1364             }
1365             return;
1366         case 'c':
1367             if (replay_reverse_continue()) {
1368                 gdb_continue();
1369             } else {
1370                 gdb_put_packet("E14");
1371             }
1372             return;
1373         }
1374     }
1375 
1376     /* Default invalid command */
1377     gdb_put_packet("");
1378 }
1379 
1380 static void handle_v_cont_query(GArray *params, void *user_ctx)
1381 {
1382     gdb_put_packet("vCont;c;C;s;S");
1383 }
1384 
1385 static void handle_v_cont(GArray *params, void *user_ctx)
1386 {
1387     int res;
1388 
1389     if (!params->len) {
1390         return;
1391     }
1392 
1393     res = gdb_handle_vcont(gdb_get_cmd_param(params, 0)->data);
1394     if ((res == -EINVAL) || (res == -ERANGE)) {
1395         gdb_put_packet("E22");
1396     } else if (res) {
1397         gdb_put_packet("");
1398     }
1399 }
1400 
1401 static void handle_v_attach(GArray *params, void *user_ctx)
1402 {
1403     GDBProcess *process;
1404     CPUState *cpu;
1405 
1406     g_string_assign(gdbserver_state.str_buf, "E22");
1407     if (!params->len) {
1408         goto cleanup;
1409     }
1410 
1411     process = gdb_get_process(gdb_get_cmd_param(params, 0)->val_ul);
1412     if (!process) {
1413         goto cleanup;
1414     }
1415 
1416     cpu = gdb_get_first_cpu_in_process(process);
1417     if (!cpu) {
1418         goto cleanup;
1419     }
1420 
1421     process->attached = true;
1422     gdbserver_state.g_cpu = cpu;
1423     gdbserver_state.c_cpu = cpu;
1424 
1425     if (gdbserver_state.allow_stop_reply) {
1426         g_string_printf(gdbserver_state.str_buf, "T%02xthread:", GDB_SIGNAL_TRAP);
1427         gdb_append_thread_id(cpu, gdbserver_state.str_buf);
1428         g_string_append_c(gdbserver_state.str_buf, ';');
1429         gdbserver_state.allow_stop_reply = false;
1430 cleanup:
1431         gdb_put_strbuf();
1432     }
1433 }
1434 
1435 static void handle_v_kill(GArray *params, void *user_ctx)
1436 {
1437     /* Kill the target */
1438     gdb_put_packet("OK");
1439     error_report("QEMU: Terminated via GDBstub");
1440     gdb_exit(0);
1441     gdb_qemu_exit(0);
1442 }
1443 
1444 static const GdbCmdParseEntry gdb_v_commands_table[] = {
1445     /* Order is important if has same prefix */
1446     {
1447         .handler = handle_v_cont_query,
1448         .cmd = "Cont?",
1449         .cmd_startswith = true
1450     },
1451     {
1452         .handler = handle_v_cont,
1453         .cmd = "Cont",
1454         .cmd_startswith = true,
1455         .allow_stop_reply = true,
1456         .schema = "s0"
1457     },
1458     {
1459         .handler = handle_v_attach,
1460         .cmd = "Attach;",
1461         .cmd_startswith = true,
1462         .allow_stop_reply = true,
1463         .schema = "l0"
1464     },
1465     {
1466         .handler = handle_v_kill,
1467         .cmd = "Kill;",
1468         .cmd_startswith = true
1469     },
1470 #ifdef CONFIG_USER_ONLY
1471     /*
1472      * Host I/O Packets. See [1] for details.
1473      * [1] https://sourceware.org/gdb/onlinedocs/gdb/Host-I_002fO-Packets.html
1474      */
1475     {
1476         .handler = gdb_handle_v_file_open,
1477         .cmd = "File:open:",
1478         .cmd_startswith = true,
1479         .schema = "s,L,L0"
1480     },
1481     {
1482         .handler = gdb_handle_v_file_close,
1483         .cmd = "File:close:",
1484         .cmd_startswith = true,
1485         .schema = "l0"
1486     },
1487     {
1488         .handler = gdb_handle_v_file_pread,
1489         .cmd = "File:pread:",
1490         .cmd_startswith = true,
1491         .schema = "l,L,L0"
1492     },
1493     {
1494         .handler = gdb_handle_v_file_readlink,
1495         .cmd = "File:readlink:",
1496         .cmd_startswith = true,
1497         .schema = "s0"
1498     },
1499 #endif
1500 };
1501 
1502 static void handle_v_commands(GArray *params, void *user_ctx)
1503 {
1504     if (!params->len) {
1505         return;
1506     }
1507 
1508     if (!process_string_cmd(gdb_get_cmd_param(params, 0)->data,
1509                             gdb_v_commands_table,
1510                             ARRAY_SIZE(gdb_v_commands_table))) {
1511         gdb_put_packet("");
1512     }
1513 }
1514 
1515 static void handle_query_qemu_sstepbits(GArray *params, void *user_ctx)
1516 {
1517     g_string_printf(gdbserver_state.str_buf, "ENABLE=%x", SSTEP_ENABLE);
1518 
1519     if (gdbserver_state.supported_sstep_flags & SSTEP_NOIRQ) {
1520         g_string_append_printf(gdbserver_state.str_buf, ",NOIRQ=%x",
1521                                SSTEP_NOIRQ);
1522     }
1523 
1524     if (gdbserver_state.supported_sstep_flags & SSTEP_NOTIMER) {
1525         g_string_append_printf(gdbserver_state.str_buf, ",NOTIMER=%x",
1526                                SSTEP_NOTIMER);
1527     }
1528 
1529     gdb_put_strbuf();
1530 }
1531 
1532 static void handle_set_qemu_sstep(GArray *params, void *user_ctx)
1533 {
1534     int new_sstep_flags;
1535 
1536     if (!params->len) {
1537         return;
1538     }
1539 
1540     new_sstep_flags = gdb_get_cmd_param(params, 0)->val_ul;
1541 
1542     if (new_sstep_flags  & ~gdbserver_state.supported_sstep_flags) {
1543         gdb_put_packet("E22");
1544         return;
1545     }
1546 
1547     gdbserver_state.sstep_flags = new_sstep_flags;
1548     gdb_put_packet("OK");
1549 }
1550 
1551 static void handle_query_qemu_sstep(GArray *params, void *user_ctx)
1552 {
1553     g_string_printf(gdbserver_state.str_buf, "0x%x",
1554                     gdbserver_state.sstep_flags);
1555     gdb_put_strbuf();
1556 }
1557 
1558 static void handle_query_curr_tid(GArray *params, void *user_ctx)
1559 {
1560     CPUState *cpu;
1561     GDBProcess *process;
1562 
1563     /*
1564      * "Current thread" remains vague in the spec, so always return
1565      * the first thread of the current process (gdb returns the
1566      * first thread).
1567      */
1568     process = gdb_get_cpu_process(gdbserver_state.g_cpu);
1569     cpu = gdb_get_first_cpu_in_process(process);
1570     g_string_assign(gdbserver_state.str_buf, "QC");
1571     gdb_append_thread_id(cpu, gdbserver_state.str_buf);
1572     gdb_put_strbuf();
1573 }
1574 
1575 static void handle_query_threads(GArray *params, void *user_ctx)
1576 {
1577     if (!gdbserver_state.query_cpu) {
1578         gdb_put_packet("l");
1579         return;
1580     }
1581 
1582     g_string_assign(gdbserver_state.str_buf, "m");
1583     gdb_append_thread_id(gdbserver_state.query_cpu, gdbserver_state.str_buf);
1584     gdb_put_strbuf();
1585     gdbserver_state.query_cpu = gdb_next_attached_cpu(gdbserver_state.query_cpu);
1586 }
1587 
1588 static void handle_query_first_threads(GArray *params, void *user_ctx)
1589 {
1590     gdbserver_state.query_cpu = gdb_first_attached_cpu();
1591     handle_query_threads(params, user_ctx);
1592 }
1593 
1594 static void handle_query_thread_extra(GArray *params, void *user_ctx)
1595 {
1596     g_autoptr(GString) rs = g_string_new(NULL);
1597     CPUState *cpu;
1598 
1599     if (!params->len ||
1600         gdb_get_cmd_param(params, 0)->thread_id.kind == GDB_READ_THREAD_ERR) {
1601         gdb_put_packet("E22");
1602         return;
1603     }
1604 
1605     cpu = gdb_get_cpu(gdb_get_cmd_param(params, 0)->thread_id.pid,
1606                       gdb_get_cmd_param(params, 0)->thread_id.tid);
1607     if (!cpu) {
1608         return;
1609     }
1610 
1611     cpu_synchronize_state(cpu);
1612 
1613     if (gdbserver_state.multiprocess && (gdbserver_state.process_num > 1)) {
1614         /* Print the CPU model and name in multiprocess mode */
1615         ObjectClass *oc = object_get_class(OBJECT(cpu));
1616         const char *cpu_model = object_class_get_name(oc);
1617         const char *cpu_name =
1618             object_get_canonical_path_component(OBJECT(cpu));
1619         g_string_printf(rs, "%s %s [%s]", cpu_model, cpu_name,
1620                         cpu->halted ? "halted " : "running");
1621     } else {
1622         g_string_printf(rs, "CPU#%d [%s]", cpu->cpu_index,
1623                         cpu->halted ? "halted " : "running");
1624     }
1625     trace_gdbstub_op_extra_info(rs->str);
1626     gdb_memtohex(gdbserver_state.str_buf, (uint8_t *)rs->str, rs->len);
1627     gdb_put_strbuf();
1628 }
1629 
1630 static char *extended_qsupported_features;
1631 void gdb_extend_qsupported_features(char *qsupported_features)
1632 {
1633     /*
1634      * We don't support different sets of CPU gdb features on different CPUs yet
1635      * so assert the feature strings are the same on all CPUs, or is set only
1636      * once (1 CPU).
1637      */
1638     g_assert(extended_qsupported_features == NULL ||
1639              g_strcmp0(extended_qsupported_features, qsupported_features) == 0);
1640 
1641     extended_qsupported_features = qsupported_features;
1642 }
1643 
1644 static void handle_query_supported(GArray *params, void *user_ctx)
1645 {
1646     CPUClass *cc;
1647 
1648     g_string_printf(gdbserver_state.str_buf, "PacketSize=%x", MAX_PACKET_LENGTH);
1649     cc = CPU_GET_CLASS(first_cpu);
1650     if (cc->gdb_core_xml_file) {
1651         g_string_append(gdbserver_state.str_buf, ";qXfer:features:read+");
1652     }
1653 
1654     if (gdb_can_reverse()) {
1655         g_string_append(gdbserver_state.str_buf,
1656             ";ReverseStep+;ReverseContinue+");
1657     }
1658 
1659 #if defined(CONFIG_USER_ONLY)
1660 #if defined(CONFIG_LINUX)
1661     if (get_task_state(gdbserver_state.c_cpu)) {
1662         g_string_append(gdbserver_state.str_buf, ";qXfer:auxv:read+");
1663     }
1664     g_string_append(gdbserver_state.str_buf, ";QCatchSyscalls+");
1665 
1666     g_string_append(gdbserver_state.str_buf, ";qXfer:siginfo:read+");
1667 #endif
1668     g_string_append(gdbserver_state.str_buf, ";qXfer:exec-file:read+");
1669 #endif
1670 
1671     if (params->len) {
1672         const char *gdb_supported = gdb_get_cmd_param(params, 0)->data;
1673 
1674         if (strstr(gdb_supported, "multiprocess+")) {
1675             gdbserver_state.multiprocess = true;
1676         }
1677 #if defined(CONFIG_USER_ONLY)
1678         gdb_handle_query_supported_user(gdb_supported);
1679 #endif
1680     }
1681 
1682     g_string_append(gdbserver_state.str_buf, ";vContSupported+;multiprocess+");
1683 
1684     if (extended_qsupported_features) {
1685         g_string_append(gdbserver_state.str_buf, extended_qsupported_features);
1686     }
1687 
1688     gdb_put_strbuf();
1689 }
1690 
1691 static void handle_query_xfer_features(GArray *params, void *user_ctx)
1692 {
1693     GDBProcess *process;
1694     CPUClass *cc;
1695     unsigned long len, total_len, addr;
1696     const char *xml;
1697     const char *p;
1698 
1699     if (params->len < 3) {
1700         gdb_put_packet("E22");
1701         return;
1702     }
1703 
1704     process = gdb_get_cpu_process(gdbserver_state.g_cpu);
1705     cc = CPU_GET_CLASS(gdbserver_state.g_cpu);
1706     if (!cc->gdb_core_xml_file) {
1707         gdb_put_packet("");
1708         return;
1709     }
1710 
1711     p = gdb_get_cmd_param(params, 0)->data;
1712     xml = get_feature_xml(p, &p, process);
1713     if (!xml) {
1714         gdb_put_packet("E00");
1715         return;
1716     }
1717 
1718     addr = gdb_get_cmd_param(params, 1)->val_ul;
1719     len = gdb_get_cmd_param(params, 2)->val_ul;
1720     total_len = strlen(xml);
1721     if (addr > total_len) {
1722         gdb_put_packet("E00");
1723         return;
1724     }
1725 
1726     if (len > (MAX_PACKET_LENGTH - 5) / 2) {
1727         len = (MAX_PACKET_LENGTH - 5) / 2;
1728     }
1729 
1730     if (len < total_len - addr) {
1731         g_string_assign(gdbserver_state.str_buf, "m");
1732         gdb_memtox(gdbserver_state.str_buf, xml + addr, len);
1733     } else {
1734         g_string_assign(gdbserver_state.str_buf, "l");
1735         gdb_memtox(gdbserver_state.str_buf, xml + addr, total_len - addr);
1736     }
1737 
1738     gdb_put_packet_binary(gdbserver_state.str_buf->str,
1739                       gdbserver_state.str_buf->len, true);
1740 }
1741 
1742 static void handle_query_qemu_supported(GArray *params, void *user_ctx)
1743 {
1744     g_string_printf(gdbserver_state.str_buf, "sstepbits;sstep");
1745 #ifndef CONFIG_USER_ONLY
1746     g_string_append(gdbserver_state.str_buf, ";PhyMemMode");
1747 #endif
1748     gdb_put_strbuf();
1749 }
1750 
1751 static const GdbCmdParseEntry gdb_gen_query_set_common_table[] = {
1752     /* Order is important if has same prefix */
1753     {
1754         .handler = handle_query_qemu_sstepbits,
1755         .cmd = "qemu.sstepbits",
1756     },
1757     {
1758         .handler = handle_query_qemu_sstep,
1759         .cmd = "qemu.sstep",
1760     },
1761     {
1762         .handler = handle_set_qemu_sstep,
1763         .cmd = "qemu.sstep=",
1764         .cmd_startswith = true,
1765         .schema = "l0"
1766     },
1767 };
1768 
1769 /* Compares if a set of command parsers is equal to another set of parsers. */
1770 static bool cmp_cmds(GdbCmdParseEntry *c, GdbCmdParseEntry *d, int size)
1771 {
1772     for (int i = 0; i < size; i++) {
1773         if (!(c[i].handler == d[i].handler &&
1774             g_strcmp0(c[i].cmd, d[i].cmd) == 0 &&
1775             c[i].cmd_startswith == d[i].cmd_startswith &&
1776             g_strcmp0(c[i].schema, d[i].schema) == 0)) {
1777 
1778             /* Sets are different. */
1779             return false;
1780         }
1781     }
1782 
1783     /* Sets are equal, i.e. contain the same command parsers. */
1784     return true;
1785 }
1786 
1787 static GdbCmdParseEntry *extended_query_table;
1788 static int extended_query_table_size;
1789 void gdb_extend_query_table(GdbCmdParseEntry *table, int size)
1790 {
1791     /*
1792      * We don't support different sets of CPU gdb features on different CPUs yet
1793      * so assert query table is the same on all CPUs, or is set only once
1794      * (1 CPU).
1795      */
1796     g_assert(extended_query_table == NULL ||
1797              (extended_query_table_size == size &&
1798               cmp_cmds(extended_query_table, table, size)));
1799 
1800     extended_query_table = table;
1801     extended_query_table_size = size;
1802 }
1803 
1804 static const GdbCmdParseEntry gdb_gen_query_table[] = {
1805     {
1806         .handler = handle_query_curr_tid,
1807         .cmd = "C",
1808     },
1809     {
1810         .handler = handle_query_threads,
1811         .cmd = "sThreadInfo",
1812     },
1813     {
1814         .handler = handle_query_first_threads,
1815         .cmd = "fThreadInfo",
1816     },
1817     {
1818         .handler = handle_query_thread_extra,
1819         .cmd = "ThreadExtraInfo,",
1820         .cmd_startswith = true,
1821         .schema = "t0"
1822     },
1823 #ifdef CONFIG_USER_ONLY
1824     {
1825         .handler = gdb_handle_query_offsets,
1826         .cmd = "Offsets",
1827     },
1828 #else
1829     {
1830         .handler = gdb_handle_query_rcmd,
1831         .cmd = "Rcmd,",
1832         .cmd_startswith = true,
1833         .schema = "s0"
1834     },
1835 #endif
1836     {
1837         .handler = handle_query_supported,
1838         .cmd = "Supported:",
1839         .cmd_startswith = true,
1840         .schema = "s0"
1841     },
1842     {
1843         .handler = handle_query_supported,
1844         .cmd = "Supported",
1845         .schema = "s0"
1846     },
1847     {
1848         .handler = handle_query_xfer_features,
1849         .cmd = "Xfer:features:read:",
1850         .cmd_startswith = true,
1851         .schema = "s:l,l0"
1852     },
1853 #if defined(CONFIG_USER_ONLY)
1854 #if defined(CONFIG_LINUX)
1855     {
1856         .handler = gdb_handle_query_xfer_auxv,
1857         .cmd = "Xfer:auxv:read::",
1858         .cmd_startswith = true,
1859         .schema = "l,l0"
1860     },
1861     {
1862         .handler = gdb_handle_query_xfer_siginfo,
1863         .cmd = "Xfer:siginfo:read::",
1864         .cmd_startswith = true,
1865         .schema = "l,l0"
1866      },
1867 #endif
1868     {
1869         .handler = gdb_handle_query_xfer_exec_file,
1870         .cmd = "Xfer:exec-file:read:",
1871         .cmd_startswith = true,
1872         .schema = "l:l,l0"
1873     },
1874 #endif
1875     {
1876         .handler = gdb_handle_query_attached,
1877         .cmd = "Attached:",
1878         .cmd_startswith = true
1879     },
1880     {
1881         .handler = gdb_handle_query_attached,
1882         .cmd = "Attached",
1883     },
1884     {
1885         .handler = handle_query_qemu_supported,
1886         .cmd = "qemu.Supported",
1887     },
1888 #ifndef CONFIG_USER_ONLY
1889     {
1890         .handler = gdb_handle_query_qemu_phy_mem_mode,
1891         .cmd = "qemu.PhyMemMode",
1892     },
1893 #endif
1894 };
1895 
1896 static GdbCmdParseEntry *extended_set_table;
1897 static int extended_set_table_size;
1898 void gdb_extend_set_table(GdbCmdParseEntry *table, int size)
1899 {
1900     /*
1901      * We don't support different sets of CPU gdb features on different CPUs yet
1902      * so assert set table is the same on all CPUs, or is set only once (1 CPU).
1903      */
1904     g_assert(extended_set_table == NULL ||
1905              (extended_set_table_size == size &&
1906               cmp_cmds(extended_set_table, table, size)));
1907 
1908     extended_set_table = table;
1909     extended_set_table_size = size;
1910 }
1911 
1912 static const GdbCmdParseEntry gdb_gen_set_table[] = {
1913     /* Order is important if has same prefix */
1914     {
1915         .handler = handle_set_qemu_sstep,
1916         .cmd = "qemu.sstep:",
1917         .cmd_startswith = true,
1918         .schema = "l0"
1919     },
1920 #ifndef CONFIG_USER_ONLY
1921     {
1922         .handler = gdb_handle_set_qemu_phy_mem_mode,
1923         .cmd = "qemu.PhyMemMode:",
1924         .cmd_startswith = true,
1925         .schema = "l0"
1926     },
1927 #endif
1928 #if defined(CONFIG_USER_ONLY)
1929     {
1930         .handler = gdb_handle_set_catch_syscalls,
1931         .cmd = "CatchSyscalls:",
1932         .cmd_startswith = true,
1933         .schema = "s0",
1934     },
1935 #endif
1936 };
1937 
1938 static void handle_gen_query(GArray *params, void *user_ctx)
1939 {
1940     if (!params->len) {
1941         return;
1942     }
1943 
1944     if (process_string_cmd(gdb_get_cmd_param(params, 0)->data,
1945                            gdb_gen_query_set_common_table,
1946                            ARRAY_SIZE(gdb_gen_query_set_common_table))) {
1947         return;
1948     }
1949 
1950     if (process_string_cmd(gdb_get_cmd_param(params, 0)->data,
1951                            gdb_gen_query_table,
1952                            ARRAY_SIZE(gdb_gen_query_table))) {
1953         return;
1954     }
1955 
1956     if (extended_query_table &&
1957         process_string_cmd(gdb_get_cmd_param(params, 0)->data,
1958                            extended_query_table,
1959                            extended_query_table_size)) {
1960         return;
1961     }
1962 
1963     /* Can't handle query, return Empty response. */
1964     gdb_put_packet("");
1965 }
1966 
1967 static void handle_gen_set(GArray *params, void *user_ctx)
1968 {
1969     if (!params->len) {
1970         return;
1971     }
1972 
1973     if (process_string_cmd(gdb_get_cmd_param(params, 0)->data,
1974                            gdb_gen_query_set_common_table,
1975                            ARRAY_SIZE(gdb_gen_query_set_common_table))) {
1976         return;
1977     }
1978 
1979     if (process_string_cmd(gdb_get_cmd_param(params, 0)->data,
1980                            gdb_gen_set_table,
1981                            ARRAY_SIZE(gdb_gen_set_table))) {
1982         return;
1983     }
1984 
1985     if (extended_set_table &&
1986         process_string_cmd(gdb_get_cmd_param(params, 0)->data,
1987                            extended_set_table,
1988                            extended_set_table_size)) {
1989         return;
1990     }
1991 
1992     /* Can't handle set, return Empty response. */
1993     gdb_put_packet("");
1994 }
1995 
1996 static void handle_target_halt(GArray *params, void *user_ctx)
1997 {
1998     if (gdbserver_state.allow_stop_reply) {
1999         g_string_printf(gdbserver_state.str_buf, "T%02xthread:", GDB_SIGNAL_TRAP);
2000         gdb_append_thread_id(gdbserver_state.c_cpu, gdbserver_state.str_buf);
2001         g_string_append_c(gdbserver_state.str_buf, ';');
2002         gdb_put_strbuf();
2003         gdbserver_state.allow_stop_reply = false;
2004     }
2005     /*
2006      * Remove all the breakpoints when this query is issued,
2007      * because gdb is doing an initial connect and the state
2008      * should be cleaned up.
2009      */
2010     gdb_breakpoint_remove_all(gdbserver_state.c_cpu);
2011 }
2012 
2013 static int gdb_handle_packet(const char *line_buf)
2014 {
2015     const GdbCmdParseEntry *cmd_parser = NULL;
2016 
2017     trace_gdbstub_io_command(line_buf);
2018 
2019     switch (line_buf[0]) {
2020     case '!':
2021         gdb_put_packet("OK");
2022         break;
2023     case '?':
2024         {
2025             static const GdbCmdParseEntry target_halted_cmd_desc = {
2026                 .handler = handle_target_halt,
2027                 .cmd = "?",
2028                 .cmd_startswith = true,
2029                 .allow_stop_reply = true,
2030             };
2031             cmd_parser = &target_halted_cmd_desc;
2032         }
2033         break;
2034     case 'c':
2035         {
2036             static const GdbCmdParseEntry continue_cmd_desc = {
2037                 .handler = handle_continue,
2038                 .cmd = "c",
2039                 .cmd_startswith = true,
2040                 .allow_stop_reply = true,
2041                 .schema = "L0"
2042             };
2043             cmd_parser = &continue_cmd_desc;
2044         }
2045         break;
2046     case 'C':
2047         {
2048             static const GdbCmdParseEntry cont_with_sig_cmd_desc = {
2049                 .handler = handle_cont_with_sig,
2050                 .cmd = "C",
2051                 .cmd_startswith = true,
2052                 .allow_stop_reply = true,
2053                 .schema = "l0"
2054             };
2055             cmd_parser = &cont_with_sig_cmd_desc;
2056         }
2057         break;
2058     case 'v':
2059         {
2060             static const GdbCmdParseEntry v_cmd_desc = {
2061                 .handler = handle_v_commands,
2062                 .cmd = "v",
2063                 .cmd_startswith = true,
2064                 .schema = "s0"
2065             };
2066             cmd_parser = &v_cmd_desc;
2067         }
2068         break;
2069     case 'k':
2070         /* Kill the target */
2071         error_report("QEMU: Terminated via GDBstub");
2072         gdb_exit(0);
2073         gdb_qemu_exit(0);
2074         break;
2075     case 'D':
2076         {
2077             static const GdbCmdParseEntry detach_cmd_desc = {
2078                 .handler = handle_detach,
2079                 .cmd = "D",
2080                 .cmd_startswith = true,
2081                 .schema = "?.l0"
2082             };
2083             cmd_parser = &detach_cmd_desc;
2084         }
2085         break;
2086     case 's':
2087         {
2088             static const GdbCmdParseEntry step_cmd_desc = {
2089                 .handler = handle_step,
2090                 .cmd = "s",
2091                 .cmd_startswith = true,
2092                 .allow_stop_reply = true,
2093                 .schema = "L0"
2094             };
2095             cmd_parser = &step_cmd_desc;
2096         }
2097         break;
2098     case 'b':
2099         {
2100             static const GdbCmdParseEntry backward_cmd_desc = {
2101                 .handler = handle_backward,
2102                 .cmd = "b",
2103                 .cmd_startswith = true,
2104                 .allow_stop_reply = true,
2105                 .schema = "o0"
2106             };
2107             cmd_parser = &backward_cmd_desc;
2108         }
2109         break;
2110     case 'F':
2111         {
2112             static const GdbCmdParseEntry file_io_cmd_desc = {
2113                 .handler = gdb_handle_file_io,
2114                 .cmd = "F",
2115                 .cmd_startswith = true,
2116                 .schema = "L,L,o0"
2117             };
2118             cmd_parser = &file_io_cmd_desc;
2119         }
2120         break;
2121     case 'g':
2122         {
2123             static const GdbCmdParseEntry read_all_regs_cmd_desc = {
2124                 .handler = handle_read_all_regs,
2125                 .cmd = "g",
2126                 .cmd_startswith = true
2127             };
2128             cmd_parser = &read_all_regs_cmd_desc;
2129         }
2130         break;
2131     case 'G':
2132         {
2133             static const GdbCmdParseEntry write_all_regs_cmd_desc = {
2134                 .handler = handle_write_all_regs,
2135                 .cmd = "G",
2136                 .cmd_startswith = true,
2137                 .schema = "s0"
2138             };
2139             cmd_parser = &write_all_regs_cmd_desc;
2140         }
2141         break;
2142     case 'm':
2143         {
2144             static const GdbCmdParseEntry read_mem_cmd_desc = {
2145                 .handler = handle_read_mem,
2146                 .cmd = "m",
2147                 .cmd_startswith = true,
2148                 .schema = "L,L0"
2149             };
2150             cmd_parser = &read_mem_cmd_desc;
2151         }
2152         break;
2153     case 'M':
2154         {
2155             static const GdbCmdParseEntry write_mem_cmd_desc = {
2156                 .handler = handle_write_mem,
2157                 .cmd = "M",
2158                 .cmd_startswith = true,
2159                 .schema = "L,L:s0"
2160             };
2161             cmd_parser = &write_mem_cmd_desc;
2162         }
2163         break;
2164     case 'p':
2165         {
2166             static const GdbCmdParseEntry get_reg_cmd_desc = {
2167                 .handler = handle_get_reg,
2168                 .cmd = "p",
2169                 .cmd_startswith = true,
2170                 .schema = "L0"
2171             };
2172             cmd_parser = &get_reg_cmd_desc;
2173         }
2174         break;
2175     case 'P':
2176         {
2177             static const GdbCmdParseEntry set_reg_cmd_desc = {
2178                 .handler = handle_set_reg,
2179                 .cmd = "P",
2180                 .cmd_startswith = true,
2181                 .schema = "L?s0"
2182             };
2183             cmd_parser = &set_reg_cmd_desc;
2184         }
2185         break;
2186     case 'Z':
2187         {
2188             static const GdbCmdParseEntry insert_bp_cmd_desc = {
2189                 .handler = handle_insert_bp,
2190                 .cmd = "Z",
2191                 .cmd_startswith = true,
2192                 .schema = "l?L?L0"
2193             };
2194             cmd_parser = &insert_bp_cmd_desc;
2195         }
2196         break;
2197     case 'z':
2198         {
2199             static const GdbCmdParseEntry remove_bp_cmd_desc = {
2200                 .handler = handle_remove_bp,
2201                 .cmd = "z",
2202                 .cmd_startswith = true,
2203                 .schema = "l?L?L0"
2204             };
2205             cmd_parser = &remove_bp_cmd_desc;
2206         }
2207         break;
2208     case 'H':
2209         {
2210             static const GdbCmdParseEntry set_thread_cmd_desc = {
2211                 .handler = handle_set_thread,
2212                 .cmd = "H",
2213                 .cmd_startswith = true,
2214                 .schema = "o.t0"
2215             };
2216             cmd_parser = &set_thread_cmd_desc;
2217         }
2218         break;
2219     case 'T':
2220         {
2221             static const GdbCmdParseEntry thread_alive_cmd_desc = {
2222                 .handler = handle_thread_alive,
2223                 .cmd = "T",
2224                 .cmd_startswith = true,
2225                 .schema = "t0"
2226             };
2227             cmd_parser = &thread_alive_cmd_desc;
2228         }
2229         break;
2230     case 'q':
2231         {
2232             static const GdbCmdParseEntry gen_query_cmd_desc = {
2233                 .handler = handle_gen_query,
2234                 .cmd = "q",
2235                 .cmd_startswith = true,
2236                 .schema = "s0"
2237             };
2238             cmd_parser = &gen_query_cmd_desc;
2239         }
2240         break;
2241     case 'Q':
2242         {
2243             static const GdbCmdParseEntry gen_set_cmd_desc = {
2244                 .handler = handle_gen_set,
2245                 .cmd = "Q",
2246                 .cmd_startswith = true,
2247                 .schema = "s0"
2248             };
2249             cmd_parser = &gen_set_cmd_desc;
2250         }
2251         break;
2252     default:
2253         /* put empty packet */
2254         gdb_put_packet("");
2255         break;
2256     }
2257 
2258     if (cmd_parser) {
2259         run_cmd_parser(line_buf, cmd_parser);
2260     }
2261 
2262     return RS_IDLE;
2263 }
2264 
2265 void gdb_set_stop_cpu(CPUState *cpu)
2266 {
2267     GDBProcess *p = gdb_get_cpu_process(cpu);
2268 
2269     if (!p->attached) {
2270         /*
2271          * Having a stop CPU corresponding to a process that is not attached
2272          * confuses GDB. So we ignore the request.
2273          */
2274         return;
2275     }
2276 
2277     gdbserver_state.c_cpu = cpu;
2278     gdbserver_state.g_cpu = cpu;
2279 }
2280 
2281 void gdb_read_byte(uint8_t ch)
2282 {
2283     uint8_t reply;
2284 
2285     gdbserver_state.allow_stop_reply = false;
2286 #ifndef CONFIG_USER_ONLY
2287     if (gdbserver_state.last_packet->len) {
2288         /* Waiting for a response to the last packet.  If we see the start
2289            of a new command then abandon the previous response.  */
2290         if (ch == '-') {
2291             trace_gdbstub_err_got_nack();
2292             gdb_put_buffer(gdbserver_state.last_packet->data,
2293                        gdbserver_state.last_packet->len);
2294         } else if (ch == '+') {
2295             trace_gdbstub_io_got_ack();
2296         } else {
2297             trace_gdbstub_io_got_unexpected(ch);
2298         }
2299 
2300         if (ch == '+' || ch == '$') {
2301             g_byte_array_set_size(gdbserver_state.last_packet, 0);
2302         }
2303         if (ch != '$')
2304             return;
2305     }
2306     if (runstate_is_running()) {
2307         /*
2308          * When the CPU is running, we cannot do anything except stop
2309          * it when receiving a char. This is expected on a Ctrl-C in the
2310          * gdb client. Because we are in all-stop mode, gdb sends a
2311          * 0x03 byte which is not a usual packet, so we handle it specially
2312          * here, but it does expect a stop reply.
2313          */
2314         if (ch != 0x03) {
2315             trace_gdbstub_err_unexpected_runpkt(ch);
2316         } else {
2317             gdbserver_state.allow_stop_reply = true;
2318         }
2319         vm_stop(RUN_STATE_PAUSED);
2320     } else
2321 #endif
2322     {
2323         switch(gdbserver_state.state) {
2324         case RS_IDLE:
2325             if (ch == '$') {
2326                 /* start of command packet */
2327                 gdbserver_state.line_buf_index = 0;
2328                 gdbserver_state.line_sum = 0;
2329                 gdbserver_state.state = RS_GETLINE;
2330             } else if (ch == '+') {
2331                 /*
2332                  * do nothing, gdb may preemptively send out ACKs on
2333                  * initial connection
2334                  */
2335             } else {
2336                 trace_gdbstub_err_garbage(ch);
2337             }
2338             break;
2339         case RS_GETLINE:
2340             if (ch == '}') {
2341                 /* start escape sequence */
2342                 gdbserver_state.state = RS_GETLINE_ESC;
2343                 gdbserver_state.line_sum += ch;
2344             } else if (ch == '*') {
2345                 /* start run length encoding sequence */
2346                 gdbserver_state.state = RS_GETLINE_RLE;
2347                 gdbserver_state.line_sum += ch;
2348             } else if (ch == '#') {
2349                 /* end of command, start of checksum*/
2350                 gdbserver_state.state = RS_CHKSUM1;
2351             } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
2352                 trace_gdbstub_err_overrun();
2353                 gdbserver_state.state = RS_IDLE;
2354             } else {
2355                 /* unescaped command character */
2356                 gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch;
2357                 gdbserver_state.line_sum += ch;
2358             }
2359             break;
2360         case RS_GETLINE_ESC:
2361             if (ch == '#') {
2362                 /* unexpected end of command in escape sequence */
2363                 gdbserver_state.state = RS_CHKSUM1;
2364             } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
2365                 /* command buffer overrun */
2366                 trace_gdbstub_err_overrun();
2367                 gdbserver_state.state = RS_IDLE;
2368             } else {
2369                 /* parse escaped character and leave escape state */
2370                 gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch ^ 0x20;
2371                 gdbserver_state.line_sum += ch;
2372                 gdbserver_state.state = RS_GETLINE;
2373             }
2374             break;
2375         case RS_GETLINE_RLE:
2376             /*
2377              * Run-length encoding is explained in "Debugging with GDB /
2378              * Appendix E GDB Remote Serial Protocol / Overview".
2379              */
2380             if (ch < ' ' || ch == '#' || ch == '$' || ch > 126) {
2381                 /* invalid RLE count encoding */
2382                 trace_gdbstub_err_invalid_repeat(ch);
2383                 gdbserver_state.state = RS_GETLINE;
2384             } else {
2385                 /* decode repeat length */
2386                 int repeat = ch - ' ' + 3;
2387                 if (gdbserver_state.line_buf_index + repeat >= sizeof(gdbserver_state.line_buf) - 1) {
2388                     /* that many repeats would overrun the command buffer */
2389                     trace_gdbstub_err_overrun();
2390                     gdbserver_state.state = RS_IDLE;
2391                 } else if (gdbserver_state.line_buf_index < 1) {
2392                     /* got a repeat but we have nothing to repeat */
2393                     trace_gdbstub_err_invalid_rle();
2394                     gdbserver_state.state = RS_GETLINE;
2395                 } else {
2396                     /* repeat the last character */
2397                     memset(gdbserver_state.line_buf + gdbserver_state.line_buf_index,
2398                            gdbserver_state.line_buf[gdbserver_state.line_buf_index - 1], repeat);
2399                     gdbserver_state.line_buf_index += repeat;
2400                     gdbserver_state.line_sum += ch;
2401                     gdbserver_state.state = RS_GETLINE;
2402                 }
2403             }
2404             break;
2405         case RS_CHKSUM1:
2406             /* get high hex digit of checksum */
2407             if (!isxdigit(ch)) {
2408                 trace_gdbstub_err_checksum_invalid(ch);
2409                 gdbserver_state.state = RS_GETLINE;
2410                 break;
2411             }
2412             gdbserver_state.line_buf[gdbserver_state.line_buf_index] = '\0';
2413             gdbserver_state.line_csum = fromhex(ch) << 4;
2414             gdbserver_state.state = RS_CHKSUM2;
2415             break;
2416         case RS_CHKSUM2:
2417             /* get low hex digit of checksum */
2418             if (!isxdigit(ch)) {
2419                 trace_gdbstub_err_checksum_invalid(ch);
2420                 gdbserver_state.state = RS_GETLINE;
2421                 break;
2422             }
2423             gdbserver_state.line_csum |= fromhex(ch);
2424 
2425             if (gdbserver_state.line_csum != (gdbserver_state.line_sum & 0xff)) {
2426                 trace_gdbstub_err_checksum_incorrect(gdbserver_state.line_sum, gdbserver_state.line_csum);
2427                 /* send NAK reply */
2428                 reply = '-';
2429                 gdb_put_buffer(&reply, 1);
2430                 gdbserver_state.state = RS_IDLE;
2431             } else {
2432                 /* send ACK reply */
2433                 reply = '+';
2434                 gdb_put_buffer(&reply, 1);
2435                 gdbserver_state.state = gdb_handle_packet(gdbserver_state.line_buf);
2436             }
2437             break;
2438         default:
2439             abort();
2440         }
2441     }
2442 }
2443 
2444 /*
2445  * Create the process that will contain all the "orphan" CPUs (that are not
2446  * part of a CPU cluster). Note that if this process contains no CPUs, it won't
2447  * be attachable and thus will be invisible to the user.
2448  */
2449 void gdb_create_default_process(GDBState *s)
2450 {
2451     GDBProcess *process;
2452     int pid;
2453 
2454 #ifdef CONFIG_USER_ONLY
2455     assert(gdbserver_state.process_num == 0);
2456     pid = getpid();
2457 #else
2458     if (gdbserver_state.process_num) {
2459         pid = s->processes[s->process_num - 1].pid;
2460     } else {
2461         pid = 0;
2462     }
2463     /* We need an available PID slot for this process */
2464     assert(pid < UINT32_MAX);
2465     pid++;
2466 #endif
2467 
2468     s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
2469     process = &s->processes[s->process_num - 1];
2470     process->pid = pid;
2471     process->attached = false;
2472     process->target_xml = NULL;
2473 }
2474 
2475