OSDN Git Service

gdbstub: clean-up vcont handling to avoid goto
[qmiga/qemu.git] / gdbstub / gdbstub.c
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     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     g_autofree char *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             return -ENOTSUP;
600         }
601
602         cur_action = *p++;
603         if (cur_action == 'C' || cur_action == 'S') {
604             cur_action = qemu_tolower(cur_action);
605             res = qemu_strtoul(p, &p, 16, &tmp);
606             if (res) {
607                 return res;
608             }
609             signal = gdb_signal_to_target(tmp);
610         } else if (cur_action != 'c' && cur_action != 's') {
611             /* unknown/invalid/unsupported command */
612             return -ENOTSUP;
613         }
614
615         if (*p == '\0' || *p == ';') {
616             /*
617              * No thread specifier, action is on "all threads". The
618              * specification is unclear regarding the process to act on. We
619              * choose all processes.
620              */
621             kind = GDB_ALL_PROCESSES;
622         } else if (*p++ == ':') {
623             kind = read_thread_id(p, &p, &pid, &tid);
624         } else {
625             return -ENOTSUP;
626         }
627
628         switch (kind) {
629         case GDB_READ_THREAD_ERR:
630             return -EINVAL;
631
632         case GDB_ALL_PROCESSES:
633             cpu = gdb_first_attached_cpu();
634             while (cpu) {
635                 if (newstates[cpu->cpu_index] == 1) {
636                     newstates[cpu->cpu_index] = cur_action;
637                 }
638
639                 cpu = gdb_next_attached_cpu(cpu);
640             }
641             break;
642
643         case GDB_ALL_THREADS:
644             process = gdb_get_process(pid);
645
646             if (!process->attached) {
647                 return -EINVAL;
648             }
649
650             cpu = get_first_cpu_in_process(process);
651             while (cpu) {
652                 if (newstates[cpu->cpu_index] == 1) {
653                     newstates[cpu->cpu_index] = cur_action;
654                 }
655
656                 cpu = gdb_next_cpu_in_process(cpu);
657             }
658             break;
659
660         case GDB_ONE_THREAD:
661             cpu = gdb_get_cpu(pid, tid);
662
663             /* invalid CPU/thread specified */
664             if (!cpu) {
665                 return -EINVAL;
666             }
667
668             /* only use if no previous match occourred */
669             if (newstates[cpu->cpu_index] == 1) {
670                 newstates[cpu->cpu_index] = cur_action;
671             }
672             break;
673         }
674     }
675
676     gdbserver_state.signal = signal;
677     gdb_continue_partial(newstates);
678     return res;
679 }
680
681 static const char *cmd_next_param(const char *param, const char delimiter)
682 {
683     static const char all_delimiters[] = ",;:=";
684     char curr_delimiters[2] = {0};
685     const char *delimiters;
686
687     if (delimiter == '?') {
688         delimiters = all_delimiters;
689     } else if (delimiter == '0') {
690         return strchr(param, '\0');
691     } else if (delimiter == '.' && *param) {
692         return param + 1;
693     } else {
694         curr_delimiters[0] = delimiter;
695         delimiters = curr_delimiters;
696     }
697
698     param += strcspn(param, delimiters);
699     if (*param) {
700         param++;
701     }
702     return param;
703 }
704
705 static int cmd_parse_params(const char *data, const char *schema,
706                             GArray *params)
707 {
708     const char *curr_schema, *curr_data;
709
710     g_assert(schema);
711     g_assert(params->len == 0);
712
713     curr_schema = schema;
714     curr_data = data;
715     while (curr_schema[0] && curr_schema[1] && *curr_data) {
716         GdbCmdVariant this_param;
717
718         switch (curr_schema[0]) {
719         case 'l':
720             if (qemu_strtoul(curr_data, &curr_data, 16,
721                              &this_param.val_ul)) {
722                 return -EINVAL;
723             }
724             curr_data = cmd_next_param(curr_data, curr_schema[1]);
725             g_array_append_val(params, this_param);
726             break;
727         case 'L':
728             if (qemu_strtou64(curr_data, &curr_data, 16,
729                               (uint64_t *)&this_param.val_ull)) {
730                 return -EINVAL;
731             }
732             curr_data = cmd_next_param(curr_data, curr_schema[1]);
733             g_array_append_val(params, this_param);
734             break;
735         case 's':
736             this_param.data = curr_data;
737             curr_data = cmd_next_param(curr_data, curr_schema[1]);
738             g_array_append_val(params, this_param);
739             break;
740         case 'o':
741             this_param.opcode = *(uint8_t *)curr_data;
742             curr_data = cmd_next_param(curr_data, curr_schema[1]);
743             g_array_append_val(params, this_param);
744             break;
745         case 't':
746             this_param.thread_id.kind =
747                 read_thread_id(curr_data, &curr_data,
748                                &this_param.thread_id.pid,
749                                &this_param.thread_id.tid);
750             curr_data = cmd_next_param(curr_data, curr_schema[1]);
751             g_array_append_val(params, this_param);
752             break;
753         case '?':
754             curr_data = cmd_next_param(curr_data, curr_schema[1]);
755             break;
756         default:
757             return -EINVAL;
758         }
759         curr_schema += 2;
760     }
761
762     return 0;
763 }
764
765 typedef void (*GdbCmdHandler)(GArray *params, void *user_ctx);
766
767 /*
768  * cmd_startswith -> cmd is compared using startswith
769  *
770  * allow_stop_reply -> true iff the gdbstub can respond to this command with a
771  *   "stop reply" packet. The list of commands that accept such response is
772  *   defined at the GDB Remote Serial Protocol documentation. see:
773  *   https://sourceware.org/gdb/onlinedocs/gdb/Stop-Reply-Packets.html#Stop-Reply-Packets.
774  *
775  * schema definitions:
776  * Each schema parameter entry consists of 2 chars,
777  * the first char represents the parameter type handling
778  * the second char represents the delimiter for the next parameter
779  *
780  * Currently supported schema types:
781  * 'l' -> unsigned long (stored in .val_ul)
782  * 'L' -> unsigned long long (stored in .val_ull)
783  * 's' -> string (stored in .data)
784  * 'o' -> single char (stored in .opcode)
785  * 't' -> thread id (stored in .thread_id)
786  * '?' -> skip according to delimiter
787  *
788  * Currently supported delimiters:
789  * '?' -> Stop at any delimiter (",;:=\0")
790  * '0' -> Stop at "\0"
791  * '.' -> Skip 1 char unless reached "\0"
792  * Any other value is treated as the delimiter value itself
793  */
794 typedef struct GdbCmdParseEntry {
795     GdbCmdHandler handler;
796     const char *cmd;
797     bool cmd_startswith;
798     const char *schema;
799     bool allow_stop_reply;
800 } GdbCmdParseEntry;
801
802 static inline int startswith(const char *string, const char *pattern)
803 {
804   return !strncmp(string, pattern, strlen(pattern));
805 }
806
807 static int process_string_cmd(void *user_ctx, const char *data,
808                               const GdbCmdParseEntry *cmds, int num_cmds)
809 {
810     int i;
811     g_autoptr(GArray) params = g_array_new(false, true, sizeof(GdbCmdVariant));
812
813     if (!cmds) {
814         return -1;
815     }
816
817     for (i = 0; i < num_cmds; i++) {
818         const GdbCmdParseEntry *cmd = &cmds[i];
819         g_assert(cmd->handler && cmd->cmd);
820
821         if ((cmd->cmd_startswith && !startswith(data, cmd->cmd)) ||
822             (!cmd->cmd_startswith && strcmp(cmd->cmd, data))) {
823             continue;
824         }
825
826         if (cmd->schema) {
827             if (cmd_parse_params(&data[strlen(cmd->cmd)],
828                                  cmd->schema, params)) {
829                 return -1;
830             }
831         }
832
833         gdbserver_state.allow_stop_reply = cmd->allow_stop_reply;
834         cmd->handler(params, user_ctx);
835         return 0;
836     }
837
838     return -1;
839 }
840
841 static void run_cmd_parser(const char *data, const GdbCmdParseEntry *cmd)
842 {
843     if (!data) {
844         return;
845     }
846
847     g_string_set_size(gdbserver_state.str_buf, 0);
848     g_byte_array_set_size(gdbserver_state.mem_buf, 0);
849
850     /* In case there was an error during the command parsing we must
851     * send a NULL packet to indicate the command is not supported */
852     if (process_string_cmd(NULL, data, cmd, 1)) {
853         gdb_put_packet("");
854     }
855 }
856
857 static void handle_detach(GArray *params, void *user_ctx)
858 {
859     GDBProcess *process;
860     uint32_t pid = 1;
861
862     if (gdbserver_state.multiprocess) {
863         if (!params->len) {
864             gdb_put_packet("E22");
865             return;
866         }
867
868         pid = get_param(params, 0)->val_ul;
869     }
870
871     process = gdb_get_process(pid);
872     gdb_process_breakpoint_remove_all(process);
873     process->attached = false;
874
875     if (pid == gdb_get_cpu_pid(gdbserver_state.c_cpu)) {
876         gdbserver_state.c_cpu = gdb_first_attached_cpu();
877     }
878
879     if (pid == gdb_get_cpu_pid(gdbserver_state.g_cpu)) {
880         gdbserver_state.g_cpu = gdb_first_attached_cpu();
881     }
882
883     if (!gdbserver_state.c_cpu) {
884         /* No more process attached */
885         gdb_disable_syscalls();
886         gdb_continue();
887     }
888     gdb_put_packet("OK");
889 }
890
891 static void handle_thread_alive(GArray *params, void *user_ctx)
892 {
893     CPUState *cpu;
894
895     if (!params->len) {
896         gdb_put_packet("E22");
897         return;
898     }
899
900     if (get_param(params, 0)->thread_id.kind == GDB_READ_THREAD_ERR) {
901         gdb_put_packet("E22");
902         return;
903     }
904
905     cpu = gdb_get_cpu(get_param(params, 0)->thread_id.pid,
906                       get_param(params, 0)->thread_id.tid);
907     if (!cpu) {
908         gdb_put_packet("E22");
909         return;
910     }
911
912     gdb_put_packet("OK");
913 }
914
915 static void handle_continue(GArray *params, void *user_ctx)
916 {
917     if (params->len) {
918         gdb_set_cpu_pc(get_param(params, 0)->val_ull);
919     }
920
921     gdbserver_state.signal = 0;
922     gdb_continue();
923 }
924
925 static void handle_cont_with_sig(GArray *params, void *user_ctx)
926 {
927     unsigned long signal = 0;
928
929     /*
930      * Note: C sig;[addr] is currently unsupported and we simply
931      *       omit the addr parameter
932      */
933     if (params->len) {
934         signal = get_param(params, 0)->val_ul;
935     }
936
937     gdbserver_state.signal = gdb_signal_to_target(signal);
938     if (gdbserver_state.signal == -1) {
939         gdbserver_state.signal = 0;
940     }
941     gdb_continue();
942 }
943
944 static void handle_set_thread(GArray *params, void *user_ctx)
945 {
946     CPUState *cpu;
947
948     if (params->len != 2) {
949         gdb_put_packet("E22");
950         return;
951     }
952
953     if (get_param(params, 1)->thread_id.kind == GDB_READ_THREAD_ERR) {
954         gdb_put_packet("E22");
955         return;
956     }
957
958     if (get_param(params, 1)->thread_id.kind != GDB_ONE_THREAD) {
959         gdb_put_packet("OK");
960         return;
961     }
962
963     cpu = gdb_get_cpu(get_param(params, 1)->thread_id.pid,
964                       get_param(params, 1)->thread_id.tid);
965     if (!cpu) {
966         gdb_put_packet("E22");
967         return;
968     }
969
970     /*
971      * Note: This command is deprecated and modern gdb's will be using the
972      *       vCont command instead.
973      */
974     switch (get_param(params, 0)->opcode) {
975     case 'c':
976         gdbserver_state.c_cpu = cpu;
977         gdb_put_packet("OK");
978         break;
979     case 'g':
980         gdbserver_state.g_cpu = cpu;
981         gdb_put_packet("OK");
982         break;
983     default:
984         gdb_put_packet("E22");
985         break;
986     }
987 }
988
989 static void handle_insert_bp(GArray *params, void *user_ctx)
990 {
991     int res;
992
993     if (params->len != 3) {
994         gdb_put_packet("E22");
995         return;
996     }
997
998     res = gdb_breakpoint_insert(gdbserver_state.c_cpu,
999                                 get_param(params, 0)->val_ul,
1000                                 get_param(params, 1)->val_ull,
1001                                 get_param(params, 2)->val_ull);
1002     if (res >= 0) {
1003         gdb_put_packet("OK");
1004         return;
1005     } else if (res == -ENOSYS) {
1006         gdb_put_packet("");
1007         return;
1008     }
1009
1010     gdb_put_packet("E22");
1011 }
1012
1013 static void handle_remove_bp(GArray *params, void *user_ctx)
1014 {
1015     int res;
1016
1017     if (params->len != 3) {
1018         gdb_put_packet("E22");
1019         return;
1020     }
1021
1022     res = gdb_breakpoint_remove(gdbserver_state.c_cpu,
1023                                 get_param(params, 0)->val_ul,
1024                                 get_param(params, 1)->val_ull,
1025                                 get_param(params, 2)->val_ull);
1026     if (res >= 0) {
1027         gdb_put_packet("OK");
1028         return;
1029     } else if (res == -ENOSYS) {
1030         gdb_put_packet("");
1031         return;
1032     }
1033
1034     gdb_put_packet("E22");
1035 }
1036
1037 /*
1038  * handle_set/get_reg
1039  *
1040  * Older gdb are really dumb, and don't use 'G/g' if 'P/p' is available.
1041  * This works, but can be very slow. Anything new enough to understand
1042  * XML also knows how to use this properly. However to use this we
1043  * need to define a local XML file as well as be talking to a
1044  * reasonably modern gdb. Responding with an empty packet will cause
1045  * the remote gdb to fallback to older methods.
1046  */
1047
1048 static void handle_set_reg(GArray *params, void *user_ctx)
1049 {
1050     int reg_size;
1051
1052     if (!gdb_has_xml) {
1053         gdb_put_packet("");
1054         return;
1055     }
1056
1057     if (params->len != 2) {
1058         gdb_put_packet("E22");
1059         return;
1060     }
1061
1062     reg_size = strlen(get_param(params, 1)->data) / 2;
1063     gdb_hextomem(gdbserver_state.mem_buf, get_param(params, 1)->data, reg_size);
1064     gdb_write_register(gdbserver_state.g_cpu, gdbserver_state.mem_buf->data,
1065                        get_param(params, 0)->val_ull);
1066     gdb_put_packet("OK");
1067 }
1068
1069 static void handle_get_reg(GArray *params, void *user_ctx)
1070 {
1071     int reg_size;
1072
1073     if (!gdb_has_xml) {
1074         gdb_put_packet("");
1075         return;
1076     }
1077
1078     if (!params->len) {
1079         gdb_put_packet("E14");
1080         return;
1081     }
1082
1083     reg_size = gdb_read_register(gdbserver_state.g_cpu,
1084                                  gdbserver_state.mem_buf,
1085                                  get_param(params, 0)->val_ull);
1086     if (!reg_size) {
1087         gdb_put_packet("E14");
1088         return;
1089     } else {
1090         g_byte_array_set_size(gdbserver_state.mem_buf, reg_size);
1091     }
1092
1093     gdb_memtohex(gdbserver_state.str_buf,
1094                  gdbserver_state.mem_buf->data, reg_size);
1095     gdb_put_strbuf();
1096 }
1097
1098 static void handle_write_mem(GArray *params, void *user_ctx)
1099 {
1100     if (params->len != 3) {
1101         gdb_put_packet("E22");
1102         return;
1103     }
1104
1105     /* gdb_hextomem() reads 2*len bytes */
1106     if (get_param(params, 1)->val_ull >
1107         strlen(get_param(params, 2)->data) / 2) {
1108         gdb_put_packet("E22");
1109         return;
1110     }
1111
1112     gdb_hextomem(gdbserver_state.mem_buf, get_param(params, 2)->data,
1113                  get_param(params, 1)->val_ull);
1114     if (gdb_target_memory_rw_debug(gdbserver_state.g_cpu,
1115                                    get_param(params, 0)->val_ull,
1116                                    gdbserver_state.mem_buf->data,
1117                                    gdbserver_state.mem_buf->len, true)) {
1118         gdb_put_packet("E14");
1119         return;
1120     }
1121
1122     gdb_put_packet("OK");
1123 }
1124
1125 static void handle_read_mem(GArray *params, void *user_ctx)
1126 {
1127     if (params->len != 2) {
1128         gdb_put_packet("E22");
1129         return;
1130     }
1131
1132     /* gdb_memtohex() doubles the required space */
1133     if (get_param(params, 1)->val_ull > MAX_PACKET_LENGTH / 2) {
1134         gdb_put_packet("E22");
1135         return;
1136     }
1137
1138     g_byte_array_set_size(gdbserver_state.mem_buf,
1139                           get_param(params, 1)->val_ull);
1140
1141     if (gdb_target_memory_rw_debug(gdbserver_state.g_cpu,
1142                                    get_param(params, 0)->val_ull,
1143                                    gdbserver_state.mem_buf->data,
1144                                    gdbserver_state.mem_buf->len, false)) {
1145         gdb_put_packet("E14");
1146         return;
1147     }
1148
1149     gdb_memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data,
1150              gdbserver_state.mem_buf->len);
1151     gdb_put_strbuf();
1152 }
1153
1154 static void handle_write_all_regs(GArray *params, void *user_ctx)
1155 {
1156     int reg_id;
1157     size_t len;
1158     uint8_t *registers;
1159     int reg_size;
1160
1161     if (!params->len) {
1162         return;
1163     }
1164
1165     cpu_synchronize_state(gdbserver_state.g_cpu);
1166     len = strlen(get_param(params, 0)->data) / 2;
1167     gdb_hextomem(gdbserver_state.mem_buf, get_param(params, 0)->data, len);
1168     registers = gdbserver_state.mem_buf->data;
1169     for (reg_id = 0;
1170          reg_id < gdbserver_state.g_cpu->gdb_num_g_regs && len > 0;
1171          reg_id++) {
1172         reg_size = gdb_write_register(gdbserver_state.g_cpu, registers, reg_id);
1173         len -= reg_size;
1174         registers += reg_size;
1175     }
1176     gdb_put_packet("OK");
1177 }
1178
1179 static void handle_read_all_regs(GArray *params, void *user_ctx)
1180 {
1181     int reg_id;
1182     size_t len;
1183
1184     cpu_synchronize_state(gdbserver_state.g_cpu);
1185     g_byte_array_set_size(gdbserver_state.mem_buf, 0);
1186     len = 0;
1187     for (reg_id = 0; reg_id < gdbserver_state.g_cpu->gdb_num_g_regs; reg_id++) {
1188         len += gdb_read_register(gdbserver_state.g_cpu,
1189                                  gdbserver_state.mem_buf,
1190                                  reg_id);
1191     }
1192     g_assert(len == gdbserver_state.mem_buf->len);
1193
1194     gdb_memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data, len);
1195     gdb_put_strbuf();
1196 }
1197
1198
1199 static void handle_step(GArray *params, void *user_ctx)
1200 {
1201     if (params->len) {
1202         gdb_set_cpu_pc(get_param(params, 0)->val_ull);
1203     }
1204
1205     cpu_single_step(gdbserver_state.c_cpu, gdbserver_state.sstep_flags);
1206     gdb_continue();
1207 }
1208
1209 static void handle_backward(GArray *params, void *user_ctx)
1210 {
1211     if (!gdb_can_reverse()) {
1212         gdb_put_packet("E22");
1213     }
1214     if (params->len == 1) {
1215         switch (get_param(params, 0)->opcode) {
1216         case 's':
1217             if (replay_reverse_step()) {
1218                 gdb_continue();
1219             } else {
1220                 gdb_put_packet("E14");
1221             }
1222             return;
1223         case 'c':
1224             if (replay_reverse_continue()) {
1225                 gdb_continue();
1226             } else {
1227                 gdb_put_packet("E14");
1228             }
1229             return;
1230         }
1231     }
1232
1233     /* Default invalid command */
1234     gdb_put_packet("");
1235 }
1236
1237 static void handle_v_cont_query(GArray *params, void *user_ctx)
1238 {
1239     gdb_put_packet("vCont;c;C;s;S");
1240 }
1241
1242 static void handle_v_cont(GArray *params, void *user_ctx)
1243 {
1244     int res;
1245
1246     if (!params->len) {
1247         return;
1248     }
1249
1250     res = gdb_handle_vcont(get_param(params, 0)->data);
1251     if ((res == -EINVAL) || (res == -ERANGE)) {
1252         gdb_put_packet("E22");
1253     } else if (res) {
1254         gdb_put_packet("");
1255     }
1256 }
1257
1258 static void handle_v_attach(GArray *params, void *user_ctx)
1259 {
1260     GDBProcess *process;
1261     CPUState *cpu;
1262
1263     g_string_assign(gdbserver_state.str_buf, "E22");
1264     if (!params->len) {
1265         goto cleanup;
1266     }
1267
1268     process = gdb_get_process(get_param(params, 0)->val_ul);
1269     if (!process) {
1270         goto cleanup;
1271     }
1272
1273     cpu = get_first_cpu_in_process(process);
1274     if (!cpu) {
1275         goto cleanup;
1276     }
1277
1278     process->attached = true;
1279     gdbserver_state.g_cpu = cpu;
1280     gdbserver_state.c_cpu = cpu;
1281
1282     if (gdbserver_state.allow_stop_reply) {
1283         g_string_printf(gdbserver_state.str_buf, "T%02xthread:", GDB_SIGNAL_TRAP);
1284         gdb_append_thread_id(cpu, gdbserver_state.str_buf);
1285         g_string_append_c(gdbserver_state.str_buf, ';');
1286         gdbserver_state.allow_stop_reply = false;
1287 cleanup:
1288         gdb_put_strbuf();
1289     }
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         .allow_stop_reply = true,
1313         .schema = "s0"
1314     },
1315     {
1316         .handler = handle_v_attach,
1317         .cmd = "Attach;",
1318         .cmd_startswith = 1,
1319         .allow_stop_reply = true,
1320         .schema = "l0"
1321     },
1322     {
1323         .handler = handle_v_kill,
1324         .cmd = "Kill;",
1325         .cmd_startswith = 1
1326     },
1327 };
1328
1329 static void handle_v_commands(GArray *params, void *user_ctx)
1330 {
1331     if (!params->len) {
1332         return;
1333     }
1334
1335     if (process_string_cmd(NULL, get_param(params, 0)->data,
1336                            gdb_v_commands_table,
1337                            ARRAY_SIZE(gdb_v_commands_table))) {
1338         gdb_put_packet("");
1339     }
1340 }
1341
1342 static void handle_query_qemu_sstepbits(GArray *params, void *user_ctx)
1343 {
1344     g_string_printf(gdbserver_state.str_buf, "ENABLE=%x", SSTEP_ENABLE);
1345
1346     if (gdbserver_state.supported_sstep_flags & SSTEP_NOIRQ) {
1347         g_string_append_printf(gdbserver_state.str_buf, ",NOIRQ=%x",
1348                                SSTEP_NOIRQ);
1349     }
1350
1351     if (gdbserver_state.supported_sstep_flags & SSTEP_NOTIMER) {
1352         g_string_append_printf(gdbserver_state.str_buf, ",NOTIMER=%x",
1353                                SSTEP_NOTIMER);
1354     }
1355
1356     gdb_put_strbuf();
1357 }
1358
1359 static void handle_set_qemu_sstep(GArray *params, void *user_ctx)
1360 {
1361     int new_sstep_flags;
1362
1363     if (!params->len) {
1364         return;
1365     }
1366
1367     new_sstep_flags = get_param(params, 0)->val_ul;
1368
1369     if (new_sstep_flags  & ~gdbserver_state.supported_sstep_flags) {
1370         gdb_put_packet("E22");
1371         return;
1372     }
1373
1374     gdbserver_state.sstep_flags = new_sstep_flags;
1375     gdb_put_packet("OK");
1376 }
1377
1378 static void handle_query_qemu_sstep(GArray *params, void *user_ctx)
1379 {
1380     g_string_printf(gdbserver_state.str_buf, "0x%x",
1381                     gdbserver_state.sstep_flags);
1382     gdb_put_strbuf();
1383 }
1384
1385 static void handle_query_curr_tid(GArray *params, void *user_ctx)
1386 {
1387     CPUState *cpu;
1388     GDBProcess *process;
1389
1390     /*
1391      * "Current thread" remains vague in the spec, so always return
1392      * the first thread of the current process (gdb returns the
1393      * first thread).
1394      */
1395     process = gdb_get_cpu_process(gdbserver_state.g_cpu);
1396     cpu = get_first_cpu_in_process(process);
1397     g_string_assign(gdbserver_state.str_buf, "QC");
1398     gdb_append_thread_id(cpu, gdbserver_state.str_buf);
1399     gdb_put_strbuf();
1400 }
1401
1402 static void handle_query_threads(GArray *params, void *user_ctx)
1403 {
1404     if (!gdbserver_state.query_cpu) {
1405         gdb_put_packet("l");
1406         return;
1407     }
1408
1409     g_string_assign(gdbserver_state.str_buf, "m");
1410     gdb_append_thread_id(gdbserver_state.query_cpu, gdbserver_state.str_buf);
1411     gdb_put_strbuf();
1412     gdbserver_state.query_cpu = gdb_next_attached_cpu(gdbserver_state.query_cpu);
1413 }
1414
1415 static void handle_query_first_threads(GArray *params, void *user_ctx)
1416 {
1417     gdbserver_state.query_cpu = gdb_first_attached_cpu();
1418     handle_query_threads(params, user_ctx);
1419 }
1420
1421 static void handle_query_thread_extra(GArray *params, void *user_ctx)
1422 {
1423     g_autoptr(GString) rs = g_string_new(NULL);
1424     CPUState *cpu;
1425
1426     if (!params->len ||
1427         get_param(params, 0)->thread_id.kind == GDB_READ_THREAD_ERR) {
1428         gdb_put_packet("E22");
1429         return;
1430     }
1431
1432     cpu = gdb_get_cpu(get_param(params, 0)->thread_id.pid,
1433                       get_param(params, 0)->thread_id.tid);
1434     if (!cpu) {
1435         return;
1436     }
1437
1438     cpu_synchronize_state(cpu);
1439
1440     if (gdbserver_state.multiprocess && (gdbserver_state.process_num > 1)) {
1441         /* Print the CPU model and name in multiprocess mode */
1442         ObjectClass *oc = object_get_class(OBJECT(cpu));
1443         const char *cpu_model = object_class_get_name(oc);
1444         const char *cpu_name =
1445             object_get_canonical_path_component(OBJECT(cpu));
1446         g_string_printf(rs, "%s %s [%s]", cpu_model, cpu_name,
1447                         cpu->halted ? "halted " : "running");
1448     } else {
1449         g_string_printf(rs, "CPU#%d [%s]", cpu->cpu_index,
1450                         cpu->halted ? "halted " : "running");
1451     }
1452     trace_gdbstub_op_extra_info(rs->str);
1453     gdb_memtohex(gdbserver_state.str_buf, (uint8_t *)rs->str, rs->len);
1454     gdb_put_strbuf();
1455 }
1456
1457 static void handle_query_supported(GArray *params, void *user_ctx)
1458 {
1459     CPUClass *cc;
1460
1461     g_string_printf(gdbserver_state.str_buf, "PacketSize=%x", MAX_PACKET_LENGTH);
1462     cc = CPU_GET_CLASS(first_cpu);
1463     if (cc->gdb_core_xml_file) {
1464         g_string_append(gdbserver_state.str_buf, ";qXfer:features:read+");
1465     }
1466
1467     if (gdb_can_reverse()) {
1468         g_string_append(gdbserver_state.str_buf,
1469             ";ReverseStep+;ReverseContinue+");
1470     }
1471
1472 #if defined(CONFIG_USER_ONLY) && defined(CONFIG_LINUX)
1473     if (gdbserver_state.c_cpu->opaque) {
1474         g_string_append(gdbserver_state.str_buf, ";qXfer:auxv:read+");
1475     }
1476 #endif
1477
1478     if (params->len &&
1479         strstr(get_param(params, 0)->data, "multiprocess+")) {
1480         gdbserver_state.multiprocess = true;
1481     }
1482
1483     g_string_append(gdbserver_state.str_buf, ";vContSupported+;multiprocess+");
1484     gdb_put_strbuf();
1485 }
1486
1487 static void handle_query_xfer_features(GArray *params, void *user_ctx)
1488 {
1489     GDBProcess *process;
1490     CPUClass *cc;
1491     unsigned long len, total_len, addr;
1492     const char *xml;
1493     const char *p;
1494
1495     if (params->len < 3) {
1496         gdb_put_packet("E22");
1497         return;
1498     }
1499
1500     process = gdb_get_cpu_process(gdbserver_state.g_cpu);
1501     cc = CPU_GET_CLASS(gdbserver_state.g_cpu);
1502     if (!cc->gdb_core_xml_file) {
1503         gdb_put_packet("");
1504         return;
1505     }
1506
1507     gdb_has_xml = true;
1508     p = get_param(params, 0)->data;
1509     xml = get_feature_xml(p, &p, process);
1510     if (!xml) {
1511         gdb_put_packet("E00");
1512         return;
1513     }
1514
1515     addr = get_param(params, 1)->val_ul;
1516     len = get_param(params, 2)->val_ul;
1517     total_len = strlen(xml);
1518     if (addr > total_len) {
1519         gdb_put_packet("E00");
1520         return;
1521     }
1522
1523     if (len > (MAX_PACKET_LENGTH - 5) / 2) {
1524         len = (MAX_PACKET_LENGTH - 5) / 2;
1525     }
1526
1527     if (len < total_len - addr) {
1528         g_string_assign(gdbserver_state.str_buf, "m");
1529         gdb_memtox(gdbserver_state.str_buf, xml + addr, len);
1530     } else {
1531         g_string_assign(gdbserver_state.str_buf, "l");
1532         gdb_memtox(gdbserver_state.str_buf, xml + addr, total_len - addr);
1533     }
1534
1535     gdb_put_packet_binary(gdbserver_state.str_buf->str,
1536                       gdbserver_state.str_buf->len, true);
1537 }
1538
1539 static void handle_query_qemu_supported(GArray *params, void *user_ctx)
1540 {
1541     g_string_printf(gdbserver_state.str_buf, "sstepbits;sstep");
1542 #ifndef CONFIG_USER_ONLY
1543     g_string_append(gdbserver_state.str_buf, ";PhyMemMode");
1544 #endif
1545     gdb_put_strbuf();
1546 }
1547
1548 static const GdbCmdParseEntry gdb_gen_query_set_common_table[] = {
1549     /* Order is important if has same prefix */
1550     {
1551         .handler = handle_query_qemu_sstepbits,
1552         .cmd = "qemu.sstepbits",
1553     },
1554     {
1555         .handler = handle_query_qemu_sstep,
1556         .cmd = "qemu.sstep",
1557     },
1558     {
1559         .handler = handle_set_qemu_sstep,
1560         .cmd = "qemu.sstep=",
1561         .cmd_startswith = 1,
1562         .schema = "l0"
1563     },
1564 };
1565
1566 static const GdbCmdParseEntry gdb_gen_query_table[] = {
1567     {
1568         .handler = handle_query_curr_tid,
1569         .cmd = "C",
1570     },
1571     {
1572         .handler = handle_query_threads,
1573         .cmd = "sThreadInfo",
1574     },
1575     {
1576         .handler = handle_query_first_threads,
1577         .cmd = "fThreadInfo",
1578     },
1579     {
1580         .handler = handle_query_thread_extra,
1581         .cmd = "ThreadExtraInfo,",
1582         .cmd_startswith = 1,
1583         .schema = "t0"
1584     },
1585 #ifdef CONFIG_USER_ONLY
1586     {
1587         .handler = gdb_handle_query_offsets,
1588         .cmd = "Offsets",
1589     },
1590 #else
1591     {
1592         .handler = gdb_handle_query_rcmd,
1593         .cmd = "Rcmd,",
1594         .cmd_startswith = 1,
1595         .schema = "s0"
1596     },
1597 #endif
1598     {
1599         .handler = handle_query_supported,
1600         .cmd = "Supported:",
1601         .cmd_startswith = 1,
1602         .schema = "s0"
1603     },
1604     {
1605         .handler = handle_query_supported,
1606         .cmd = "Supported",
1607         .schema = "s0"
1608     },
1609     {
1610         .handler = handle_query_xfer_features,
1611         .cmd = "Xfer:features:read:",
1612         .cmd_startswith = 1,
1613         .schema = "s:l,l0"
1614     },
1615 #if defined(CONFIG_USER_ONLY) && defined(CONFIG_LINUX)
1616     {
1617         .handler = gdb_handle_query_xfer_auxv,
1618         .cmd = "Xfer:auxv:read::",
1619         .cmd_startswith = 1,
1620         .schema = "l,l0"
1621     },
1622 #endif
1623     {
1624         .handler = gdb_handle_query_attached,
1625         .cmd = "Attached:",
1626         .cmd_startswith = 1
1627     },
1628     {
1629         .handler = gdb_handle_query_attached,
1630         .cmd = "Attached",
1631     },
1632     {
1633         .handler = handle_query_qemu_supported,
1634         .cmd = "qemu.Supported",
1635     },
1636 #ifndef CONFIG_USER_ONLY
1637     {
1638         .handler = gdb_handle_query_qemu_phy_mem_mode,
1639         .cmd = "qemu.PhyMemMode",
1640     },
1641 #endif
1642 };
1643
1644 static const GdbCmdParseEntry gdb_gen_set_table[] = {
1645     /* Order is important if has same prefix */
1646     {
1647         .handler = handle_set_qemu_sstep,
1648         .cmd = "qemu.sstep:",
1649         .cmd_startswith = 1,
1650         .schema = "l0"
1651     },
1652 #ifndef CONFIG_USER_ONLY
1653     {
1654         .handler = gdb_handle_set_qemu_phy_mem_mode,
1655         .cmd = "qemu.PhyMemMode:",
1656         .cmd_startswith = 1,
1657         .schema = "l0"
1658     },
1659 #endif
1660 };
1661
1662 static void handle_gen_query(GArray *params, void *user_ctx)
1663 {
1664     if (!params->len) {
1665         return;
1666     }
1667
1668     if (!process_string_cmd(NULL, get_param(params, 0)->data,
1669                             gdb_gen_query_set_common_table,
1670                             ARRAY_SIZE(gdb_gen_query_set_common_table))) {
1671         return;
1672     }
1673
1674     if (process_string_cmd(NULL, get_param(params, 0)->data,
1675                            gdb_gen_query_table,
1676                            ARRAY_SIZE(gdb_gen_query_table))) {
1677         gdb_put_packet("");
1678     }
1679 }
1680
1681 static void handle_gen_set(GArray *params, void *user_ctx)
1682 {
1683     if (!params->len) {
1684         return;
1685     }
1686
1687     if (!process_string_cmd(NULL, get_param(params, 0)->data,
1688                             gdb_gen_query_set_common_table,
1689                             ARRAY_SIZE(gdb_gen_query_set_common_table))) {
1690         return;
1691     }
1692
1693     if (process_string_cmd(NULL, get_param(params, 0)->data,
1694                            gdb_gen_set_table,
1695                            ARRAY_SIZE(gdb_gen_set_table))) {
1696         gdb_put_packet("");
1697     }
1698 }
1699
1700 static void handle_target_halt(GArray *params, void *user_ctx)
1701 {
1702     if (gdbserver_state.allow_stop_reply) {
1703         g_string_printf(gdbserver_state.str_buf, "T%02xthread:", GDB_SIGNAL_TRAP);
1704         gdb_append_thread_id(gdbserver_state.c_cpu, gdbserver_state.str_buf);
1705         g_string_append_c(gdbserver_state.str_buf, ';');
1706         gdb_put_strbuf();
1707         gdbserver_state.allow_stop_reply = false;
1708     }
1709     /*
1710      * Remove all the breakpoints when this query is issued,
1711      * because gdb is doing an initial connect and the state
1712      * should be cleaned up.
1713      */
1714     gdb_breakpoint_remove_all(gdbserver_state.c_cpu);
1715 }
1716
1717 static int gdb_handle_packet(const char *line_buf)
1718 {
1719     const GdbCmdParseEntry *cmd_parser = NULL;
1720
1721     trace_gdbstub_io_command(line_buf);
1722
1723     switch (line_buf[0]) {
1724     case '!':
1725         gdb_put_packet("OK");
1726         break;
1727     case '?':
1728         {
1729             static const GdbCmdParseEntry target_halted_cmd_desc = {
1730                 .handler = handle_target_halt,
1731                 .cmd = "?",
1732                 .cmd_startswith = 1,
1733                 .allow_stop_reply = true,
1734             };
1735             cmd_parser = &target_halted_cmd_desc;
1736         }
1737         break;
1738     case 'c':
1739         {
1740             static const GdbCmdParseEntry continue_cmd_desc = {
1741                 .handler = handle_continue,
1742                 .cmd = "c",
1743                 .cmd_startswith = 1,
1744                 .allow_stop_reply = true,
1745                 .schema = "L0"
1746             };
1747             cmd_parser = &continue_cmd_desc;
1748         }
1749         break;
1750     case 'C':
1751         {
1752             static const GdbCmdParseEntry cont_with_sig_cmd_desc = {
1753                 .handler = handle_cont_with_sig,
1754                 .cmd = "C",
1755                 .cmd_startswith = 1,
1756                 .allow_stop_reply = true,
1757                 .schema = "l0"
1758             };
1759             cmd_parser = &cont_with_sig_cmd_desc;
1760         }
1761         break;
1762     case 'v':
1763         {
1764             static const GdbCmdParseEntry v_cmd_desc = {
1765                 .handler = handle_v_commands,
1766                 .cmd = "v",
1767                 .cmd_startswith = 1,
1768                 .schema = "s0"
1769             };
1770             cmd_parser = &v_cmd_desc;
1771         }
1772         break;
1773     case 'k':
1774         /* Kill the target */
1775         error_report("QEMU: Terminated via GDBstub");
1776         gdb_exit(0);
1777         exit(0);
1778     case 'D':
1779         {
1780             static const GdbCmdParseEntry detach_cmd_desc = {
1781                 .handler = handle_detach,
1782                 .cmd = "D",
1783                 .cmd_startswith = 1,
1784                 .schema = "?.l0"
1785             };
1786             cmd_parser = &detach_cmd_desc;
1787         }
1788         break;
1789     case 's':
1790         {
1791             static const GdbCmdParseEntry step_cmd_desc = {
1792                 .handler = handle_step,
1793                 .cmd = "s",
1794                 .cmd_startswith = 1,
1795                 .allow_stop_reply = true,
1796                 .schema = "L0"
1797             };
1798             cmd_parser = &step_cmd_desc;
1799         }
1800         break;
1801     case 'b':
1802         {
1803             static const GdbCmdParseEntry backward_cmd_desc = {
1804                 .handler = handle_backward,
1805                 .cmd = "b",
1806                 .cmd_startswith = 1,
1807                 .allow_stop_reply = true,
1808                 .schema = "o0"
1809             };
1810             cmd_parser = &backward_cmd_desc;
1811         }
1812         break;
1813     case 'F':
1814         {
1815             static const GdbCmdParseEntry file_io_cmd_desc = {
1816                 .handler = gdb_handle_file_io,
1817                 .cmd = "F",
1818                 .cmd_startswith = 1,
1819                 .schema = "L,L,o0"
1820             };
1821             cmd_parser = &file_io_cmd_desc;
1822         }
1823         break;
1824     case 'g':
1825         {
1826             static const GdbCmdParseEntry read_all_regs_cmd_desc = {
1827                 .handler = handle_read_all_regs,
1828                 .cmd = "g",
1829                 .cmd_startswith = 1
1830             };
1831             cmd_parser = &read_all_regs_cmd_desc;
1832         }
1833         break;
1834     case 'G':
1835         {
1836             static const GdbCmdParseEntry write_all_regs_cmd_desc = {
1837                 .handler = handle_write_all_regs,
1838                 .cmd = "G",
1839                 .cmd_startswith = 1,
1840                 .schema = "s0"
1841             };
1842             cmd_parser = &write_all_regs_cmd_desc;
1843         }
1844         break;
1845     case 'm':
1846         {
1847             static const GdbCmdParseEntry read_mem_cmd_desc = {
1848                 .handler = handle_read_mem,
1849                 .cmd = "m",
1850                 .cmd_startswith = 1,
1851                 .schema = "L,L0"
1852             };
1853             cmd_parser = &read_mem_cmd_desc;
1854         }
1855         break;
1856     case 'M':
1857         {
1858             static const GdbCmdParseEntry write_mem_cmd_desc = {
1859                 .handler = handle_write_mem,
1860                 .cmd = "M",
1861                 .cmd_startswith = 1,
1862                 .schema = "L,L:s0"
1863             };
1864             cmd_parser = &write_mem_cmd_desc;
1865         }
1866         break;
1867     case 'p':
1868         {
1869             static const GdbCmdParseEntry get_reg_cmd_desc = {
1870                 .handler = handle_get_reg,
1871                 .cmd = "p",
1872                 .cmd_startswith = 1,
1873                 .schema = "L0"
1874             };
1875             cmd_parser = &get_reg_cmd_desc;
1876         }
1877         break;
1878     case 'P':
1879         {
1880             static const GdbCmdParseEntry set_reg_cmd_desc = {
1881                 .handler = handle_set_reg,
1882                 .cmd = "P",
1883                 .cmd_startswith = 1,
1884                 .schema = "L?s0"
1885             };
1886             cmd_parser = &set_reg_cmd_desc;
1887         }
1888         break;
1889     case 'Z':
1890         {
1891             static const GdbCmdParseEntry insert_bp_cmd_desc = {
1892                 .handler = handle_insert_bp,
1893                 .cmd = "Z",
1894                 .cmd_startswith = 1,
1895                 .schema = "l?L?L0"
1896             };
1897             cmd_parser = &insert_bp_cmd_desc;
1898         }
1899         break;
1900     case 'z':
1901         {
1902             static const GdbCmdParseEntry remove_bp_cmd_desc = {
1903                 .handler = handle_remove_bp,
1904                 .cmd = "z",
1905                 .cmd_startswith = 1,
1906                 .schema = "l?L?L0"
1907             };
1908             cmd_parser = &remove_bp_cmd_desc;
1909         }
1910         break;
1911     case 'H':
1912         {
1913             static const GdbCmdParseEntry set_thread_cmd_desc = {
1914                 .handler = handle_set_thread,
1915                 .cmd = "H",
1916                 .cmd_startswith = 1,
1917                 .schema = "o.t0"
1918             };
1919             cmd_parser = &set_thread_cmd_desc;
1920         }
1921         break;
1922     case 'T':
1923         {
1924             static const GdbCmdParseEntry thread_alive_cmd_desc = {
1925                 .handler = handle_thread_alive,
1926                 .cmd = "T",
1927                 .cmd_startswith = 1,
1928                 .schema = "t0"
1929             };
1930             cmd_parser = &thread_alive_cmd_desc;
1931         }
1932         break;
1933     case 'q':
1934         {
1935             static const GdbCmdParseEntry gen_query_cmd_desc = {
1936                 .handler = handle_gen_query,
1937                 .cmd = "q",
1938                 .cmd_startswith = 1,
1939                 .schema = "s0"
1940             };
1941             cmd_parser = &gen_query_cmd_desc;
1942         }
1943         break;
1944     case 'Q':
1945         {
1946             static const GdbCmdParseEntry gen_set_cmd_desc = {
1947                 .handler = handle_gen_set,
1948                 .cmd = "Q",
1949                 .cmd_startswith = 1,
1950                 .schema = "s0"
1951             };
1952             cmd_parser = &gen_set_cmd_desc;
1953         }
1954         break;
1955     default:
1956         /* put empty packet */
1957         gdb_put_packet("");
1958         break;
1959     }
1960
1961     if (cmd_parser) {
1962         run_cmd_parser(line_buf, cmd_parser);
1963     }
1964
1965     return RS_IDLE;
1966 }
1967
1968 void gdb_set_stop_cpu(CPUState *cpu)
1969 {
1970     GDBProcess *p = gdb_get_cpu_process(cpu);
1971
1972     if (!p->attached) {
1973         /*
1974          * Having a stop CPU corresponding to a process that is not attached
1975          * confuses GDB. So we ignore the request.
1976          */
1977         return;
1978     }
1979
1980     gdbserver_state.c_cpu = cpu;
1981     gdbserver_state.g_cpu = cpu;
1982 }
1983
1984 void gdb_read_byte(uint8_t ch)
1985 {
1986     uint8_t reply;
1987
1988     gdbserver_state.allow_stop_reply = false;
1989 #ifndef CONFIG_USER_ONLY
1990     if (gdbserver_state.last_packet->len) {
1991         /* Waiting for a response to the last packet.  If we see the start
1992            of a new command then abandon the previous response.  */
1993         if (ch == '-') {
1994             trace_gdbstub_err_got_nack();
1995             gdb_put_buffer(gdbserver_state.last_packet->data,
1996                        gdbserver_state.last_packet->len);
1997         } else if (ch == '+') {
1998             trace_gdbstub_io_got_ack();
1999         } else {
2000             trace_gdbstub_io_got_unexpected(ch);
2001         }
2002
2003         if (ch == '+' || ch == '$') {
2004             g_byte_array_set_size(gdbserver_state.last_packet, 0);
2005         }
2006         if (ch != '$')
2007             return;
2008     }
2009     if (runstate_is_running()) {
2010         /* when the CPU is running, we cannot do anything except stop
2011            it when receiving a char */
2012         vm_stop(RUN_STATE_PAUSED);
2013     } else
2014 #endif
2015     {
2016         switch(gdbserver_state.state) {
2017         case RS_IDLE:
2018             if (ch == '$') {
2019                 /* start of command packet */
2020                 gdbserver_state.line_buf_index = 0;
2021                 gdbserver_state.line_sum = 0;
2022                 gdbserver_state.state = RS_GETLINE;
2023             } else {
2024                 trace_gdbstub_err_garbage(ch);
2025             }
2026             break;
2027         case RS_GETLINE:
2028             if (ch == '}') {
2029                 /* start escape sequence */
2030                 gdbserver_state.state = RS_GETLINE_ESC;
2031                 gdbserver_state.line_sum += ch;
2032             } else if (ch == '*') {
2033                 /* start run length encoding sequence */
2034                 gdbserver_state.state = RS_GETLINE_RLE;
2035                 gdbserver_state.line_sum += ch;
2036             } else if (ch == '#') {
2037                 /* end of command, start of checksum*/
2038                 gdbserver_state.state = RS_CHKSUM1;
2039             } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
2040                 trace_gdbstub_err_overrun();
2041                 gdbserver_state.state = RS_IDLE;
2042             } else {
2043                 /* unescaped command character */
2044                 gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch;
2045                 gdbserver_state.line_sum += ch;
2046             }
2047             break;
2048         case RS_GETLINE_ESC:
2049             if (ch == '#') {
2050                 /* unexpected end of command in escape sequence */
2051                 gdbserver_state.state = RS_CHKSUM1;
2052             } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
2053                 /* command buffer overrun */
2054                 trace_gdbstub_err_overrun();
2055                 gdbserver_state.state = RS_IDLE;
2056             } else {
2057                 /* parse escaped character and leave escape state */
2058                 gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch ^ 0x20;
2059                 gdbserver_state.line_sum += ch;
2060                 gdbserver_state.state = RS_GETLINE;
2061             }
2062             break;
2063         case RS_GETLINE_RLE:
2064             /*
2065              * Run-length encoding is explained in "Debugging with GDB /
2066              * Appendix E GDB Remote Serial Protocol / Overview".
2067              */
2068             if (ch < ' ' || ch == '#' || ch == '$' || ch > 126) {
2069                 /* invalid RLE count encoding */
2070                 trace_gdbstub_err_invalid_repeat(ch);
2071                 gdbserver_state.state = RS_GETLINE;
2072             } else {
2073                 /* decode repeat length */
2074                 int repeat = ch - ' ' + 3;
2075                 if (gdbserver_state.line_buf_index + repeat >= sizeof(gdbserver_state.line_buf) - 1) {
2076                     /* that many repeats would overrun the command buffer */
2077                     trace_gdbstub_err_overrun();
2078                     gdbserver_state.state = RS_IDLE;
2079                 } else if (gdbserver_state.line_buf_index < 1) {
2080                     /* got a repeat but we have nothing to repeat */
2081                     trace_gdbstub_err_invalid_rle();
2082                     gdbserver_state.state = RS_GETLINE;
2083                 } else {
2084                     /* repeat the last character */
2085                     memset(gdbserver_state.line_buf + gdbserver_state.line_buf_index,
2086                            gdbserver_state.line_buf[gdbserver_state.line_buf_index - 1], repeat);
2087                     gdbserver_state.line_buf_index += repeat;
2088                     gdbserver_state.line_sum += ch;
2089                     gdbserver_state.state = RS_GETLINE;
2090                 }
2091             }
2092             break;
2093         case RS_CHKSUM1:
2094             /* get high 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_buf[gdbserver_state.line_buf_index] = '\0';
2101             gdbserver_state.line_csum = fromhex(ch) << 4;
2102             gdbserver_state.state = RS_CHKSUM2;
2103             break;
2104         case RS_CHKSUM2:
2105             /* get low hex digit of checksum */
2106             if (!isxdigit(ch)) {
2107                 trace_gdbstub_err_checksum_invalid(ch);
2108                 gdbserver_state.state = RS_GETLINE;
2109                 break;
2110             }
2111             gdbserver_state.line_csum |= fromhex(ch);
2112
2113             if (gdbserver_state.line_csum != (gdbserver_state.line_sum & 0xff)) {
2114                 trace_gdbstub_err_checksum_incorrect(gdbserver_state.line_sum, gdbserver_state.line_csum);
2115                 /* send NAK reply */
2116                 reply = '-';
2117                 gdb_put_buffer(&reply, 1);
2118                 gdbserver_state.state = RS_IDLE;
2119             } else {
2120                 /* send ACK reply */
2121                 reply = '+';
2122                 gdb_put_buffer(&reply, 1);
2123                 gdbserver_state.state = gdb_handle_packet(gdbserver_state.line_buf);
2124             }
2125             break;
2126         default:
2127             abort();
2128         }
2129     }
2130 }
2131
2132 /*
2133  * Create the process that will contain all the "orphan" CPUs (that are not
2134  * part of a CPU cluster). Note that if this process contains no CPUs, it won't
2135  * be attachable and thus will be invisible to the user.
2136  */
2137 void gdb_create_default_process(GDBState *s)
2138 {
2139     GDBProcess *process;
2140     int max_pid = 0;
2141
2142     if (gdbserver_state.process_num) {
2143         max_pid = s->processes[s->process_num - 1].pid;
2144     }
2145
2146     s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
2147     process = &s->processes[s->process_num - 1];
2148
2149     /* We need an available PID slot for this process */
2150     assert(max_pid < UINT32_MAX);
2151
2152     process->pid = max_pid + 1;
2153     process->attached = false;
2154     process->target_xml[0] = '\0';
2155 }
2156