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