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