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