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