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