OSDN Git Service

edk2: switch to release builds
[qmiga/qemu.git] / 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-common.h"
28 #include "qapi/error.h"
29 #include "qemu/error-report.h"
30 #include "qemu/ctype.h"
31 #include "qemu/cutils.h"
32 #include "qemu/module.h"
33 #include "trace/trace-root.h"
34 #include "exec/gdbstub.h"
35 #ifdef CONFIG_USER_ONLY
36 #include "qemu.h"
37 #else
38 #include "monitor/monitor.h"
39 #include "chardev/char.h"
40 #include "chardev/char-fe.h"
41 #include "hw/cpu/cluster.h"
42 #include "hw/boards.h"
43 #endif
44
45 #define MAX_PACKET_LENGTH 4096
46
47 #include "qemu/sockets.h"
48 #include "sysemu/hw_accel.h"
49 #include "sysemu/kvm.h"
50 #include "sysemu/runstate.h"
51 #include "semihosting/semihost.h"
52 #include "exec/exec-all.h"
53 #include "sysemu/replay.h"
54
55 #ifdef CONFIG_USER_ONLY
56 #define GDB_ATTACHED "0"
57 #else
58 #define GDB_ATTACHED "1"
59 #endif
60
61 #ifndef CONFIG_USER_ONLY
62 static int phy_memory_mode;
63 #endif
64
65 static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
66                                          uint8_t *buf, int len, bool is_write)
67 {
68     CPUClass *cc;
69
70 #ifndef CONFIG_USER_ONLY
71     if (phy_memory_mode) {
72         if (is_write) {
73             cpu_physical_memory_write(addr, buf, len);
74         } else {
75             cpu_physical_memory_read(addr, buf, len);
76         }
77         return 0;
78     }
79 #endif
80
81     cc = CPU_GET_CLASS(cpu);
82     if (cc->memory_rw_debug) {
83         return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
84     }
85     return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
86 }
87
88 /* Return the GDB index for a given vCPU state.
89  *
90  * For user mode this is simply the thread id. In system mode GDB
91  * numbers CPUs from 1 as 0 is reserved as an "any cpu" index.
92  */
93 static inline int cpu_gdb_index(CPUState *cpu)
94 {
95 #if defined(CONFIG_USER_ONLY)
96     TaskState *ts = (TaskState *) cpu->opaque;
97     return ts ? ts->ts_tid : -1;
98 #else
99     return cpu->cpu_index + 1;
100 #endif
101 }
102
103 enum {
104     GDB_SIGNAL_0 = 0,
105     GDB_SIGNAL_INT = 2,
106     GDB_SIGNAL_QUIT = 3,
107     GDB_SIGNAL_TRAP = 5,
108     GDB_SIGNAL_ABRT = 6,
109     GDB_SIGNAL_ALRM = 14,
110     GDB_SIGNAL_IO = 23,
111     GDB_SIGNAL_XCPU = 24,
112     GDB_SIGNAL_UNKNOWN = 143
113 };
114
115 #ifdef CONFIG_USER_ONLY
116
117 /* Map target signal numbers to GDB protocol signal numbers and vice
118  * versa.  For user emulation's currently supported systems, we can
119  * assume most signals are defined.
120  */
121
122 static int gdb_signal_table[] = {
123     0,
124     TARGET_SIGHUP,
125     TARGET_SIGINT,
126     TARGET_SIGQUIT,
127     TARGET_SIGILL,
128     TARGET_SIGTRAP,
129     TARGET_SIGABRT,
130     -1, /* SIGEMT */
131     TARGET_SIGFPE,
132     TARGET_SIGKILL,
133     TARGET_SIGBUS,
134     TARGET_SIGSEGV,
135     TARGET_SIGSYS,
136     TARGET_SIGPIPE,
137     TARGET_SIGALRM,
138     TARGET_SIGTERM,
139     TARGET_SIGURG,
140     TARGET_SIGSTOP,
141     TARGET_SIGTSTP,
142     TARGET_SIGCONT,
143     TARGET_SIGCHLD,
144     TARGET_SIGTTIN,
145     TARGET_SIGTTOU,
146     TARGET_SIGIO,
147     TARGET_SIGXCPU,
148     TARGET_SIGXFSZ,
149     TARGET_SIGVTALRM,
150     TARGET_SIGPROF,
151     TARGET_SIGWINCH,
152     -1, /* SIGLOST */
153     TARGET_SIGUSR1,
154     TARGET_SIGUSR2,
155 #ifdef TARGET_SIGPWR
156     TARGET_SIGPWR,
157 #else
158     -1,
159 #endif
160     -1, /* SIGPOLL */
161     -1,
162     -1,
163     -1,
164     -1,
165     -1,
166     -1,
167     -1,
168     -1,
169     -1,
170     -1,
171     -1,
172 #ifdef __SIGRTMIN
173     __SIGRTMIN + 1,
174     __SIGRTMIN + 2,
175     __SIGRTMIN + 3,
176     __SIGRTMIN + 4,
177     __SIGRTMIN + 5,
178     __SIGRTMIN + 6,
179     __SIGRTMIN + 7,
180     __SIGRTMIN + 8,
181     __SIGRTMIN + 9,
182     __SIGRTMIN + 10,
183     __SIGRTMIN + 11,
184     __SIGRTMIN + 12,
185     __SIGRTMIN + 13,
186     __SIGRTMIN + 14,
187     __SIGRTMIN + 15,
188     __SIGRTMIN + 16,
189     __SIGRTMIN + 17,
190     __SIGRTMIN + 18,
191     __SIGRTMIN + 19,
192     __SIGRTMIN + 20,
193     __SIGRTMIN + 21,
194     __SIGRTMIN + 22,
195     __SIGRTMIN + 23,
196     __SIGRTMIN + 24,
197     __SIGRTMIN + 25,
198     __SIGRTMIN + 26,
199     __SIGRTMIN + 27,
200     __SIGRTMIN + 28,
201     __SIGRTMIN + 29,
202     __SIGRTMIN + 30,
203     __SIGRTMIN + 31,
204     -1, /* SIGCANCEL */
205     __SIGRTMIN,
206     __SIGRTMIN + 32,
207     __SIGRTMIN + 33,
208     __SIGRTMIN + 34,
209     __SIGRTMIN + 35,
210     __SIGRTMIN + 36,
211     __SIGRTMIN + 37,
212     __SIGRTMIN + 38,
213     __SIGRTMIN + 39,
214     __SIGRTMIN + 40,
215     __SIGRTMIN + 41,
216     __SIGRTMIN + 42,
217     __SIGRTMIN + 43,
218     __SIGRTMIN + 44,
219     __SIGRTMIN + 45,
220     __SIGRTMIN + 46,
221     __SIGRTMIN + 47,
222     __SIGRTMIN + 48,
223     __SIGRTMIN + 49,
224     __SIGRTMIN + 50,
225     __SIGRTMIN + 51,
226     __SIGRTMIN + 52,
227     __SIGRTMIN + 53,
228     __SIGRTMIN + 54,
229     __SIGRTMIN + 55,
230     __SIGRTMIN + 56,
231     __SIGRTMIN + 57,
232     __SIGRTMIN + 58,
233     __SIGRTMIN + 59,
234     __SIGRTMIN + 60,
235     __SIGRTMIN + 61,
236     __SIGRTMIN + 62,
237     __SIGRTMIN + 63,
238     __SIGRTMIN + 64,
239     __SIGRTMIN + 65,
240     __SIGRTMIN + 66,
241     __SIGRTMIN + 67,
242     __SIGRTMIN + 68,
243     __SIGRTMIN + 69,
244     __SIGRTMIN + 70,
245     __SIGRTMIN + 71,
246     __SIGRTMIN + 72,
247     __SIGRTMIN + 73,
248     __SIGRTMIN + 74,
249     __SIGRTMIN + 75,
250     __SIGRTMIN + 76,
251     __SIGRTMIN + 77,
252     __SIGRTMIN + 78,
253     __SIGRTMIN + 79,
254     __SIGRTMIN + 80,
255     __SIGRTMIN + 81,
256     __SIGRTMIN + 82,
257     __SIGRTMIN + 83,
258     __SIGRTMIN + 84,
259     __SIGRTMIN + 85,
260     __SIGRTMIN + 86,
261     __SIGRTMIN + 87,
262     __SIGRTMIN + 88,
263     __SIGRTMIN + 89,
264     __SIGRTMIN + 90,
265     __SIGRTMIN + 91,
266     __SIGRTMIN + 92,
267     __SIGRTMIN + 93,
268     __SIGRTMIN + 94,
269     __SIGRTMIN + 95,
270     -1, /* SIGINFO */
271     -1, /* UNKNOWN */
272     -1, /* DEFAULT */
273     -1,
274     -1,
275     -1,
276     -1,
277     -1,
278     -1
279 #endif
280 };
281 #else
282 /* In system mode we only need SIGINT and SIGTRAP; other signals
283    are not yet supported.  */
284
285 enum {
286     TARGET_SIGINT = 2,
287     TARGET_SIGTRAP = 5
288 };
289
290 static int gdb_signal_table[] = {
291     -1,
292     -1,
293     TARGET_SIGINT,
294     -1,
295     -1,
296     TARGET_SIGTRAP
297 };
298 #endif
299
300 #ifdef CONFIG_USER_ONLY
301 static int target_signal_to_gdb (int sig)
302 {
303     int i;
304     for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
305         if (gdb_signal_table[i] == sig)
306             return i;
307     return GDB_SIGNAL_UNKNOWN;
308 }
309 #endif
310
311 static int gdb_signal_to_target (int sig)
312 {
313     if (sig < ARRAY_SIZE (gdb_signal_table))
314         return gdb_signal_table[sig];
315     else
316         return -1;
317 }
318
319 typedef struct GDBRegisterState {
320     int base_reg;
321     int num_regs;
322     gdb_get_reg_cb get_reg;
323     gdb_set_reg_cb set_reg;
324     const char *xml;
325     struct GDBRegisterState *next;
326 } GDBRegisterState;
327
328 typedef struct GDBProcess {
329     uint32_t pid;
330     bool attached;
331
332     char target_xml[1024];
333 } GDBProcess;
334
335 enum RSState {
336     RS_INACTIVE,
337     RS_IDLE,
338     RS_GETLINE,
339     RS_GETLINE_ESC,
340     RS_GETLINE_RLE,
341     RS_CHKSUM1,
342     RS_CHKSUM2,
343 };
344 typedef struct GDBState {
345     bool init;       /* have we been initialised? */
346     CPUState *c_cpu; /* current CPU for step/continue ops */
347     CPUState *g_cpu; /* current CPU for other ops */
348     CPUState *query_cpu; /* for q{f|s}ThreadInfo */
349     enum RSState state; /* parsing state */
350     char line_buf[MAX_PACKET_LENGTH];
351     int line_buf_index;
352     int line_sum; /* running checksum */
353     int line_csum; /* checksum at the end of the packet */
354     GByteArray *last_packet;
355     int signal;
356 #ifdef CONFIG_USER_ONLY
357     int fd;
358     char *socket_path;
359     int running_state;
360 #else
361     CharBackend chr;
362     Chardev *mon_chr;
363 #endif
364     bool multiprocess;
365     GDBProcess *processes;
366     int process_num;
367     char syscall_buf[256];
368     gdb_syscall_complete_cb current_syscall_cb;
369     GString *str_buf;
370     GByteArray *mem_buf;
371     int sstep_flags;
372     int supported_sstep_flags;
373 } GDBState;
374
375 static GDBState gdbserver_state;
376
377 static void init_gdbserver_state(void)
378 {
379     g_assert(!gdbserver_state.init);
380     memset(&gdbserver_state, 0, sizeof(GDBState));
381     gdbserver_state.init = true;
382     gdbserver_state.str_buf = g_string_new(NULL);
383     gdbserver_state.mem_buf = g_byte_array_sized_new(MAX_PACKET_LENGTH);
384     gdbserver_state.last_packet = g_byte_array_sized_new(MAX_PACKET_LENGTH + 4);
385
386     /*
387      * In replay mode all events will come from the log and can't be
388      * suppressed otherwise we would break determinism. However as those
389      * events are tied to the number of executed instructions we won't see
390      * them occurring every time we single step.
391      */
392     if (replay_mode != REPLAY_MODE_NONE) {
393         gdbserver_state.supported_sstep_flags = SSTEP_ENABLE;
394     } else if (kvm_enabled()) {
395         gdbserver_state.supported_sstep_flags = kvm_get_supported_sstep_flags();
396     } else {
397         gdbserver_state.supported_sstep_flags =
398             SSTEP_ENABLE | SSTEP_NOIRQ | SSTEP_NOTIMER;
399     }
400
401     /*
402      * By default use no IRQs and no timers while single stepping so as to
403      * make single stepping like an ICE HW step.
404      */
405     gdbserver_state.sstep_flags = SSTEP_ENABLE | SSTEP_NOIRQ | SSTEP_NOTIMER;
406     gdbserver_state.sstep_flags &= gdbserver_state.supported_sstep_flags;
407
408 }
409
410 #ifndef CONFIG_USER_ONLY
411 static void reset_gdbserver_state(void)
412 {
413     g_free(gdbserver_state.processes);
414     gdbserver_state.processes = NULL;
415     gdbserver_state.process_num = 0;
416 }
417 #endif
418
419 bool gdb_has_xml;
420
421 #ifdef CONFIG_USER_ONLY
422
423 static int get_char(void)
424 {
425     uint8_t ch;
426     int ret;
427
428     for(;;) {
429         ret = qemu_recv(gdbserver_state.fd, &ch, 1, 0);
430         if (ret < 0) {
431             if (errno == ECONNRESET)
432                 gdbserver_state.fd = -1;
433             if (errno != EINTR)
434                 return -1;
435         } else if (ret == 0) {
436             close(gdbserver_state.fd);
437             gdbserver_state.fd = -1;
438             return -1;
439         } else {
440             break;
441         }
442     }
443     return ch;
444 }
445 #endif
446
447 static enum {
448     GDB_SYS_UNKNOWN,
449     GDB_SYS_ENABLED,
450     GDB_SYS_DISABLED,
451 } gdb_syscall_mode;
452
453 /* Decide if either remote gdb syscalls or native file IO should be used. */
454 int use_gdb_syscalls(void)
455 {
456     SemihostingTarget target = semihosting_get_target();
457     if (target == SEMIHOSTING_TARGET_NATIVE) {
458         /* -semihosting-config target=native */
459         return false;
460     } else if (target == SEMIHOSTING_TARGET_GDB) {
461         /* -semihosting-config target=gdb */
462         return true;
463     }
464
465     /* -semihosting-config target=auto */
466     /* On the first call check if gdb is connected and remember. */
467     if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
468         gdb_syscall_mode = gdbserver_state.init ?
469             GDB_SYS_ENABLED : GDB_SYS_DISABLED;
470     }
471     return gdb_syscall_mode == GDB_SYS_ENABLED;
472 }
473
474 static bool stub_can_reverse(void)
475 {
476 #ifdef CONFIG_USER_ONLY
477     return false;
478 #else
479     return replay_mode == REPLAY_MODE_PLAY;
480 #endif
481 }
482
483 /* Resume execution.  */
484 static inline void gdb_continue(void)
485 {
486
487 #ifdef CONFIG_USER_ONLY
488     gdbserver_state.running_state = 1;
489     trace_gdbstub_op_continue();
490 #else
491     if (!runstate_needs_reset()) {
492         trace_gdbstub_op_continue();
493         vm_start();
494     }
495 #endif
496 }
497
498 /*
499  * Resume execution, per CPU actions. For user-mode emulation it's
500  * equivalent to gdb_continue.
501  */
502 static int gdb_continue_partial(char *newstates)
503 {
504     CPUState *cpu;
505     int res = 0;
506 #ifdef CONFIG_USER_ONLY
507     /*
508      * This is not exactly accurate, but it's an improvement compared to the
509      * previous situation, where only one CPU would be single-stepped.
510      */
511     CPU_FOREACH(cpu) {
512         if (newstates[cpu->cpu_index] == 's') {
513             trace_gdbstub_op_stepping(cpu->cpu_index);
514             cpu_single_step(cpu, gdbserver_state.sstep_flags);
515         }
516     }
517     gdbserver_state.running_state = 1;
518 #else
519     int flag = 0;
520
521     if (!runstate_needs_reset()) {
522         if (vm_prepare_start()) {
523             return 0;
524         }
525
526         CPU_FOREACH(cpu) {
527             switch (newstates[cpu->cpu_index]) {
528             case 0:
529             case 1:
530                 break; /* nothing to do here */
531             case 's':
532                 trace_gdbstub_op_stepping(cpu->cpu_index);
533                 cpu_single_step(cpu, gdbserver_state.sstep_flags);
534                 cpu_resume(cpu);
535                 flag = 1;
536                 break;
537             case 'c':
538                 trace_gdbstub_op_continue_cpu(cpu->cpu_index);
539                 cpu_resume(cpu);
540                 flag = 1;
541                 break;
542             default:
543                 res = -1;
544                 break;
545             }
546         }
547     }
548     if (flag) {
549         qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
550     }
551 #endif
552     return res;
553 }
554
555 static void put_buffer(const uint8_t *buf, int len)
556 {
557 #ifdef CONFIG_USER_ONLY
558     int ret;
559
560     while (len > 0) {
561         ret = send(gdbserver_state.fd, buf, len, 0);
562         if (ret < 0) {
563             if (errno != EINTR)
564                 return;
565         } else {
566             buf += ret;
567             len -= ret;
568         }
569     }
570 #else
571     /* XXX this blocks entire thread. Rewrite to use
572      * qemu_chr_fe_write and background I/O callbacks */
573     qemu_chr_fe_write_all(&gdbserver_state.chr, buf, len);
574 #endif
575 }
576
577 static inline int fromhex(int v)
578 {
579     if (v >= '0' && v <= '9')
580         return v - '0';
581     else if (v >= 'A' && v <= 'F')
582         return v - 'A' + 10;
583     else if (v >= 'a' && v <= 'f')
584         return v - 'a' + 10;
585     else
586         return 0;
587 }
588
589 static inline int tohex(int v)
590 {
591     if (v < 10)
592         return v + '0';
593     else
594         return v - 10 + 'a';
595 }
596
597 /* writes 2*len+1 bytes in buf */
598 static void memtohex(GString *buf, const uint8_t *mem, int len)
599 {
600     int i, c;
601     for(i = 0; i < len; i++) {
602         c = mem[i];
603         g_string_append_c(buf, tohex(c >> 4));
604         g_string_append_c(buf, tohex(c & 0xf));
605     }
606     g_string_append_c(buf, '\0');
607 }
608
609 static void hextomem(GByteArray *mem, const char *buf, int len)
610 {
611     int i;
612
613     for(i = 0; i < len; i++) {
614         guint8 byte = fromhex(buf[0]) << 4 | fromhex(buf[1]);
615         g_byte_array_append(mem, &byte, 1);
616         buf += 2;
617     }
618 }
619
620 static void hexdump(const char *buf, int len,
621                     void (*trace_fn)(size_t ofs, char const *text))
622 {
623     char line_buffer[3 * 16 + 4 + 16 + 1];
624
625     size_t i;
626     for (i = 0; i < len || (i & 0xF); ++i) {
627         size_t byte_ofs = i & 15;
628
629         if (byte_ofs == 0) {
630             memset(line_buffer, ' ', 3 * 16 + 4 + 16);
631             line_buffer[3 * 16 + 4 + 16] = 0;
632         }
633
634         size_t col_group = (i >> 2) & 3;
635         size_t hex_col = byte_ofs * 3 + col_group;
636         size_t txt_col = 3 * 16 + 4 + byte_ofs;
637
638         if (i < len) {
639             char value = buf[i];
640
641             line_buffer[hex_col + 0] = tohex((value >> 4) & 0xF);
642             line_buffer[hex_col + 1] = tohex((value >> 0) & 0xF);
643             line_buffer[txt_col + 0] = (value >= ' ' && value < 127)
644                     ? value
645                     : '.';
646         }
647
648         if (byte_ofs == 0xF)
649             trace_fn(i & -16, line_buffer);
650     }
651 }
652
653 /* return -1 if error, 0 if OK */
654 static int put_packet_binary(const char *buf, int len, bool dump)
655 {
656     int csum, i;
657     uint8_t footer[3];
658
659     if (dump && trace_event_get_state_backends(TRACE_GDBSTUB_IO_BINARYREPLY)) {
660         hexdump(buf, len, trace_gdbstub_io_binaryreply);
661     }
662
663     for(;;) {
664         g_byte_array_set_size(gdbserver_state.last_packet, 0);
665         g_byte_array_append(gdbserver_state.last_packet,
666                             (const uint8_t *) "$", 1);
667         g_byte_array_append(gdbserver_state.last_packet,
668                             (const uint8_t *) buf, len);
669         csum = 0;
670         for(i = 0; i < len; i++) {
671             csum += buf[i];
672         }
673         footer[0] = '#';
674         footer[1] = tohex((csum >> 4) & 0xf);
675         footer[2] = tohex((csum) & 0xf);
676         g_byte_array_append(gdbserver_state.last_packet, footer, 3);
677
678         put_buffer(gdbserver_state.last_packet->data,
679                    gdbserver_state.last_packet->len);
680
681 #ifdef CONFIG_USER_ONLY
682         i = get_char();
683         if (i < 0)
684             return -1;
685         if (i == '+')
686             break;
687 #else
688         break;
689 #endif
690     }
691     return 0;
692 }
693
694 /* return -1 if error, 0 if OK */
695 static int put_packet(const char *buf)
696 {
697     trace_gdbstub_io_reply(buf);
698
699     return put_packet_binary(buf, strlen(buf), false);
700 }
701
702 static void put_strbuf(void)
703 {
704     put_packet(gdbserver_state.str_buf->str);
705 }
706
707 /* Encode data using the encoding for 'x' packets.  */
708 static void memtox(GString *buf, const char *mem, int len)
709 {
710     char c;
711
712     while (len--) {
713         c = *(mem++);
714         switch (c) {
715         case '#': case '$': case '*': case '}':
716             g_string_append_c(buf, '}');
717             g_string_append_c(buf, c ^ 0x20);
718             break;
719         default:
720             g_string_append_c(buf, c);
721             break;
722         }
723     }
724 }
725
726 static uint32_t gdb_get_cpu_pid(CPUState *cpu)
727 {
728     /* TODO: In user mode, we should use the task state PID */
729     if (cpu->cluster_index == UNASSIGNED_CLUSTER_INDEX) {
730         /* Return the default process' PID */
731         int index = gdbserver_state.process_num - 1;
732         return gdbserver_state.processes[index].pid;
733     }
734     return cpu->cluster_index + 1;
735 }
736
737 static GDBProcess *gdb_get_process(uint32_t pid)
738 {
739     int i;
740
741     if (!pid) {
742         /* 0 means any process, we take the first one */
743         return &gdbserver_state.processes[0];
744     }
745
746     for (i = 0; i < gdbserver_state.process_num; i++) {
747         if (gdbserver_state.processes[i].pid == pid) {
748             return &gdbserver_state.processes[i];
749         }
750     }
751
752     return NULL;
753 }
754
755 static GDBProcess *gdb_get_cpu_process(CPUState *cpu)
756 {
757     return gdb_get_process(gdb_get_cpu_pid(cpu));
758 }
759
760 static CPUState *find_cpu(uint32_t thread_id)
761 {
762     CPUState *cpu;
763
764     CPU_FOREACH(cpu) {
765         if (cpu_gdb_index(cpu) == thread_id) {
766             return cpu;
767         }
768     }
769
770     return NULL;
771 }
772
773 static CPUState *get_first_cpu_in_process(GDBProcess *process)
774 {
775     CPUState *cpu;
776
777     CPU_FOREACH(cpu) {
778         if (gdb_get_cpu_pid(cpu) == process->pid) {
779             return cpu;
780         }
781     }
782
783     return NULL;
784 }
785
786 static CPUState *gdb_next_cpu_in_process(CPUState *cpu)
787 {
788     uint32_t pid = gdb_get_cpu_pid(cpu);
789     cpu = CPU_NEXT(cpu);
790
791     while (cpu) {
792         if (gdb_get_cpu_pid(cpu) == pid) {
793             break;
794         }
795
796         cpu = CPU_NEXT(cpu);
797     }
798
799     return cpu;
800 }
801
802 /* Return the cpu following @cpu, while ignoring unattached processes. */
803 static CPUState *gdb_next_attached_cpu(CPUState *cpu)
804 {
805     cpu = CPU_NEXT(cpu);
806
807     while (cpu) {
808         if (gdb_get_cpu_process(cpu)->attached) {
809             break;
810         }
811
812         cpu = CPU_NEXT(cpu);
813     }
814
815     return cpu;
816 }
817
818 /* Return the first attached cpu */
819 static CPUState *gdb_first_attached_cpu(void)
820 {
821     CPUState *cpu = first_cpu;
822     GDBProcess *process = gdb_get_cpu_process(cpu);
823
824     if (!process->attached) {
825         return gdb_next_attached_cpu(cpu);
826     }
827
828     return cpu;
829 }
830
831 static CPUState *gdb_get_cpu(uint32_t pid, uint32_t tid)
832 {
833     GDBProcess *process;
834     CPUState *cpu;
835
836     if (!pid && !tid) {
837         /* 0 means any process/thread, we take the first attached one */
838         return gdb_first_attached_cpu();
839     } else if (pid && !tid) {
840         /* any thread in a specific process */
841         process = gdb_get_process(pid);
842
843         if (process == NULL) {
844             return NULL;
845         }
846
847         if (!process->attached) {
848             return NULL;
849         }
850
851         return get_first_cpu_in_process(process);
852     } else {
853         /* a specific thread */
854         cpu = find_cpu(tid);
855
856         if (cpu == NULL) {
857             return NULL;
858         }
859
860         process = gdb_get_cpu_process(cpu);
861
862         if (pid && process->pid != pid) {
863             return NULL;
864         }
865
866         if (!process->attached) {
867             return NULL;
868         }
869
870         return cpu;
871     }
872 }
873
874 static const char *get_feature_xml(const char *p, const char **newp,
875                                    GDBProcess *process)
876 {
877     size_t len;
878     int i;
879     const char *name;
880     CPUState *cpu = get_first_cpu_in_process(process);
881     CPUClass *cc = CPU_GET_CLASS(cpu);
882
883     len = 0;
884     while (p[len] && p[len] != ':')
885         len++;
886     *newp = p + len;
887
888     name = NULL;
889     if (strncmp(p, "target.xml", len) == 0) {
890         char *buf = process->target_xml;
891         const size_t buf_sz = sizeof(process->target_xml);
892
893         /* Generate the XML description for this CPU.  */
894         if (!buf[0]) {
895             GDBRegisterState *r;
896
897             pstrcat(buf, buf_sz,
898                     "<?xml version=\"1.0\"?>"
899                     "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
900                     "<target>");
901             if (cc->gdb_arch_name) {
902                 gchar *arch = cc->gdb_arch_name(cpu);
903                 pstrcat(buf, buf_sz, "<architecture>");
904                 pstrcat(buf, buf_sz, arch);
905                 pstrcat(buf, buf_sz, "</architecture>");
906                 g_free(arch);
907             }
908             pstrcat(buf, buf_sz, "<xi:include href=\"");
909             pstrcat(buf, buf_sz, cc->gdb_core_xml_file);
910             pstrcat(buf, buf_sz, "\"/>");
911             for (r = cpu->gdb_regs; r; r = r->next) {
912                 pstrcat(buf, buf_sz, "<xi:include href=\"");
913                 pstrcat(buf, buf_sz, r->xml);
914                 pstrcat(buf, buf_sz, "\"/>");
915             }
916             pstrcat(buf, buf_sz, "</target>");
917         }
918         return buf;
919     }
920     if (cc->gdb_get_dynamic_xml) {
921         char *xmlname = g_strndup(p, len);
922         const char *xml = cc->gdb_get_dynamic_xml(cpu, xmlname);
923
924         g_free(xmlname);
925         if (xml) {
926             return xml;
927         }
928     }
929     for (i = 0; ; i++) {
930         name = xml_builtin[i][0];
931         if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
932             break;
933     }
934     return name ? xml_builtin[i][1] : NULL;
935 }
936
937 static int gdb_read_register(CPUState *cpu, GByteArray *buf, int reg)
938 {
939     CPUClass *cc = CPU_GET_CLASS(cpu);
940     CPUArchState *env = cpu->env_ptr;
941     GDBRegisterState *r;
942
943     if (reg < cc->gdb_num_core_regs) {
944         return cc->gdb_read_register(cpu, buf, reg);
945     }
946
947     for (r = cpu->gdb_regs; r; r = r->next) {
948         if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
949             return r->get_reg(env, buf, reg - r->base_reg);
950         }
951     }
952     return 0;
953 }
954
955 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
956 {
957     CPUClass *cc = CPU_GET_CLASS(cpu);
958     CPUArchState *env = cpu->env_ptr;
959     GDBRegisterState *r;
960
961     if (reg < cc->gdb_num_core_regs) {
962         return cc->gdb_write_register(cpu, mem_buf, reg);
963     }
964
965     for (r = cpu->gdb_regs; r; r = r->next) {
966         if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
967             return r->set_reg(env, mem_buf, reg - r->base_reg);
968         }
969     }
970     return 0;
971 }
972
973 /* Register a supplemental set of CPU registers.  If g_pos is nonzero it
974    specifies the first register number and these registers are included in
975    a standard "g" packet.  Direction is relative to gdb, i.e. get_reg is
976    gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
977  */
978
979 void gdb_register_coprocessor(CPUState *cpu,
980                               gdb_get_reg_cb get_reg, gdb_set_reg_cb set_reg,
981                               int num_regs, const char *xml, int g_pos)
982 {
983     GDBRegisterState *s;
984     GDBRegisterState **p;
985
986     p = &cpu->gdb_regs;
987     while (*p) {
988         /* Check for duplicates.  */
989         if (strcmp((*p)->xml, xml) == 0)
990             return;
991         p = &(*p)->next;
992     }
993
994     s = g_new0(GDBRegisterState, 1);
995     s->base_reg = cpu->gdb_num_regs;
996     s->num_regs = num_regs;
997     s->get_reg = get_reg;
998     s->set_reg = set_reg;
999     s->xml = xml;
1000
1001     /* Add to end of list.  */
1002     cpu->gdb_num_regs += num_regs;
1003     *p = s;
1004     if (g_pos) {
1005         if (g_pos != s->base_reg) {
1006             error_report("Error: Bad gdb register numbering for '%s', "
1007                          "expected %d got %d", xml, g_pos, s->base_reg);
1008         } else {
1009             cpu->gdb_num_g_regs = cpu->gdb_num_regs;
1010         }
1011     }
1012 }
1013
1014 #ifndef CONFIG_USER_ONLY
1015 /* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
1016 static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
1017 {
1018     static const int xlat[] = {
1019         [GDB_WATCHPOINT_WRITE]  = BP_GDB | BP_MEM_WRITE,
1020         [GDB_WATCHPOINT_READ]   = BP_GDB | BP_MEM_READ,
1021         [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
1022     };
1023
1024     CPUClass *cc = CPU_GET_CLASS(cpu);
1025     int cputype = xlat[gdbtype];
1026
1027     if (cc->gdb_stop_before_watchpoint) {
1028         cputype |= BP_STOP_BEFORE_ACCESS;
1029     }
1030     return cputype;
1031 }
1032 #endif
1033
1034 static int gdb_breakpoint_insert(int type, target_ulong addr, target_ulong len)
1035 {
1036     CPUState *cpu;
1037     int err = 0;
1038
1039     if (kvm_enabled()) {
1040         return kvm_insert_breakpoint(gdbserver_state.c_cpu, addr, len, type);
1041     }
1042
1043     switch (type) {
1044     case GDB_BREAKPOINT_SW:
1045     case GDB_BREAKPOINT_HW:
1046         CPU_FOREACH(cpu) {
1047             err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
1048             if (err) {
1049                 break;
1050             }
1051         }
1052         return err;
1053 #ifndef CONFIG_USER_ONLY
1054     case GDB_WATCHPOINT_WRITE:
1055     case GDB_WATCHPOINT_READ:
1056     case GDB_WATCHPOINT_ACCESS:
1057         CPU_FOREACH(cpu) {
1058             err = cpu_watchpoint_insert(cpu, addr, len,
1059                                         xlat_gdb_type(cpu, type), NULL);
1060             if (err) {
1061                 break;
1062             }
1063         }
1064         return err;
1065 #endif
1066     default:
1067         return -ENOSYS;
1068     }
1069 }
1070
1071 static int gdb_breakpoint_remove(int type, target_ulong addr, target_ulong len)
1072 {
1073     CPUState *cpu;
1074     int err = 0;
1075
1076     if (kvm_enabled()) {
1077         return kvm_remove_breakpoint(gdbserver_state.c_cpu, addr, len, type);
1078     }
1079
1080     switch (type) {
1081     case GDB_BREAKPOINT_SW:
1082     case GDB_BREAKPOINT_HW:
1083         CPU_FOREACH(cpu) {
1084             err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
1085             if (err) {
1086                 break;
1087             }
1088         }
1089         return err;
1090 #ifndef CONFIG_USER_ONLY
1091     case GDB_WATCHPOINT_WRITE:
1092     case GDB_WATCHPOINT_READ:
1093     case GDB_WATCHPOINT_ACCESS:
1094         CPU_FOREACH(cpu) {
1095             err = cpu_watchpoint_remove(cpu, addr, len,
1096                                         xlat_gdb_type(cpu, type));
1097             if (err)
1098                 break;
1099         }
1100         return err;
1101 #endif
1102     default:
1103         return -ENOSYS;
1104     }
1105 }
1106
1107 static inline void gdb_cpu_breakpoint_remove_all(CPUState *cpu)
1108 {
1109     cpu_breakpoint_remove_all(cpu, BP_GDB);
1110 #ifndef CONFIG_USER_ONLY
1111     cpu_watchpoint_remove_all(cpu, BP_GDB);
1112 #endif
1113 }
1114
1115 static void gdb_process_breakpoint_remove_all(GDBProcess *p)
1116 {
1117     CPUState *cpu = get_first_cpu_in_process(p);
1118
1119     while (cpu) {
1120         gdb_cpu_breakpoint_remove_all(cpu);
1121         cpu = gdb_next_cpu_in_process(cpu);
1122     }
1123 }
1124
1125 static void gdb_breakpoint_remove_all(void)
1126 {
1127     CPUState *cpu;
1128
1129     if (kvm_enabled()) {
1130         kvm_remove_all_breakpoints(gdbserver_state.c_cpu);
1131         return;
1132     }
1133
1134     CPU_FOREACH(cpu) {
1135         gdb_cpu_breakpoint_remove_all(cpu);
1136     }
1137 }
1138
1139 static void gdb_set_cpu_pc(target_ulong pc)
1140 {
1141     CPUState *cpu = gdbserver_state.c_cpu;
1142
1143     cpu_synchronize_state(cpu);
1144     cpu_set_pc(cpu, pc);
1145 }
1146
1147 static void gdb_append_thread_id(CPUState *cpu, GString *buf)
1148 {
1149     if (gdbserver_state.multiprocess) {
1150         g_string_append_printf(buf, "p%02x.%02x",
1151                                gdb_get_cpu_pid(cpu), cpu_gdb_index(cpu));
1152     } else {
1153         g_string_append_printf(buf, "%02x", cpu_gdb_index(cpu));
1154     }
1155 }
1156
1157 typedef enum GDBThreadIdKind {
1158     GDB_ONE_THREAD = 0,
1159     GDB_ALL_THREADS,     /* One process, all threads */
1160     GDB_ALL_PROCESSES,
1161     GDB_READ_THREAD_ERR
1162 } GDBThreadIdKind;
1163
1164 static GDBThreadIdKind read_thread_id(const char *buf, const char **end_buf,
1165                                       uint32_t *pid, uint32_t *tid)
1166 {
1167     unsigned long p, t;
1168     int ret;
1169
1170     if (*buf == 'p') {
1171         buf++;
1172         ret = qemu_strtoul(buf, &buf, 16, &p);
1173
1174         if (ret) {
1175             return GDB_READ_THREAD_ERR;
1176         }
1177
1178         /* Skip '.' */
1179         buf++;
1180     } else {
1181         p = 1;
1182     }
1183
1184     ret = qemu_strtoul(buf, &buf, 16, &t);
1185
1186     if (ret) {
1187         return GDB_READ_THREAD_ERR;
1188     }
1189
1190     *end_buf = buf;
1191
1192     if (p == -1) {
1193         return GDB_ALL_PROCESSES;
1194     }
1195
1196     if (pid) {
1197         *pid = p;
1198     }
1199
1200     if (t == -1) {
1201         return GDB_ALL_THREADS;
1202     }
1203
1204     if (tid) {
1205         *tid = t;
1206     }
1207
1208     return GDB_ONE_THREAD;
1209 }
1210
1211 /**
1212  * gdb_handle_vcont - Parses and handles a vCont packet.
1213  * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
1214  *         a format error, 0 on success.
1215  */
1216 static int gdb_handle_vcont(const char *p)
1217 {
1218     int res, signal = 0;
1219     char cur_action;
1220     char *newstates;
1221     unsigned long tmp;
1222     uint32_t pid, tid;
1223     GDBProcess *process;
1224     CPUState *cpu;
1225     GDBThreadIdKind kind;
1226 #ifdef CONFIG_USER_ONLY
1227     int max_cpus = 1; /* global variable max_cpus exists only in system mode */
1228
1229     CPU_FOREACH(cpu) {
1230         max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
1231     }
1232 #else
1233     MachineState *ms = MACHINE(qdev_get_machine());
1234     unsigned int max_cpus = ms->smp.max_cpus;
1235 #endif
1236     /* uninitialised CPUs stay 0 */
1237     newstates = g_new0(char, max_cpus);
1238
1239     /* mark valid CPUs with 1 */
1240     CPU_FOREACH(cpu) {
1241         newstates[cpu->cpu_index] = 1;
1242     }
1243
1244     /*
1245      * res keeps track of what error we are returning, with -ENOTSUP meaning
1246      * that the command is unknown or unsupported, thus returning an empty
1247      * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
1248      *  or incorrect parameters passed.
1249      */
1250     res = 0;
1251     while (*p) {
1252         if (*p++ != ';') {
1253             res = -ENOTSUP;
1254             goto out;
1255         }
1256
1257         cur_action = *p++;
1258         if (cur_action == 'C' || cur_action == 'S') {
1259             cur_action = qemu_tolower(cur_action);
1260             res = qemu_strtoul(p, &p, 16, &tmp);
1261             if (res) {
1262                 goto out;
1263             }
1264             signal = gdb_signal_to_target(tmp);
1265         } else if (cur_action != 'c' && cur_action != 's') {
1266             /* unknown/invalid/unsupported command */
1267             res = -ENOTSUP;
1268             goto out;
1269         }
1270
1271         if (*p == '\0' || *p == ';') {
1272             /*
1273              * No thread specifier, action is on "all threads". The
1274              * specification is unclear regarding the process to act on. We
1275              * choose all processes.
1276              */
1277             kind = GDB_ALL_PROCESSES;
1278         } else if (*p++ == ':') {
1279             kind = read_thread_id(p, &p, &pid, &tid);
1280         } else {
1281             res = -ENOTSUP;
1282             goto out;
1283         }
1284
1285         switch (kind) {
1286         case GDB_READ_THREAD_ERR:
1287             res = -EINVAL;
1288             goto out;
1289
1290         case GDB_ALL_PROCESSES:
1291             cpu = gdb_first_attached_cpu();
1292             while (cpu) {
1293                 if (newstates[cpu->cpu_index] == 1) {
1294                     newstates[cpu->cpu_index] = cur_action;
1295                 }
1296
1297                 cpu = gdb_next_attached_cpu(cpu);
1298             }
1299             break;
1300
1301         case GDB_ALL_THREADS:
1302             process = gdb_get_process(pid);
1303
1304             if (!process->attached) {
1305                 res = -EINVAL;
1306                 goto out;
1307             }
1308
1309             cpu = get_first_cpu_in_process(process);
1310             while (cpu) {
1311                 if (newstates[cpu->cpu_index] == 1) {
1312                     newstates[cpu->cpu_index] = cur_action;
1313                 }
1314
1315                 cpu = gdb_next_cpu_in_process(cpu);
1316             }
1317             break;
1318
1319         case GDB_ONE_THREAD:
1320             cpu = gdb_get_cpu(pid, tid);
1321
1322             /* invalid CPU/thread specified */
1323             if (!cpu) {
1324                 res = -EINVAL;
1325                 goto out;
1326             }
1327
1328             /* only use if no previous match occourred */
1329             if (newstates[cpu->cpu_index] == 1) {
1330                 newstates[cpu->cpu_index] = cur_action;
1331             }
1332             break;
1333         }
1334     }
1335     gdbserver_state.signal = signal;
1336     gdb_continue_partial(newstates);
1337
1338 out:
1339     g_free(newstates);
1340
1341     return res;
1342 }
1343
1344 typedef union GdbCmdVariant {
1345     const char *data;
1346     uint8_t opcode;
1347     unsigned long val_ul;
1348     unsigned long long val_ull;
1349     struct {
1350         GDBThreadIdKind kind;
1351         uint32_t pid;
1352         uint32_t tid;
1353     } thread_id;
1354 } GdbCmdVariant;
1355
1356 #define get_param(p, i)    (&g_array_index(p, GdbCmdVariant, i))
1357
1358 static const char *cmd_next_param(const char *param, const char delimiter)
1359 {
1360     static const char all_delimiters[] = ",;:=";
1361     char curr_delimiters[2] = {0};
1362     const char *delimiters;
1363
1364     if (delimiter == '?') {
1365         delimiters = all_delimiters;
1366     } else if (delimiter == '0') {
1367         return strchr(param, '\0');
1368     } else if (delimiter == '.' && *param) {
1369         return param + 1;
1370     } else {
1371         curr_delimiters[0] = delimiter;
1372         delimiters = curr_delimiters;
1373     }
1374
1375     param += strcspn(param, delimiters);
1376     if (*param) {
1377         param++;
1378     }
1379     return param;
1380 }
1381
1382 static int cmd_parse_params(const char *data, const char *schema,
1383                             GArray *params)
1384 {
1385     const char *curr_schema, *curr_data;
1386
1387     g_assert(schema);
1388     g_assert(params->len == 0);
1389
1390     curr_schema = schema;
1391     curr_data = data;
1392     while (curr_schema[0] && curr_schema[1] && *curr_data) {
1393         GdbCmdVariant this_param;
1394
1395         switch (curr_schema[0]) {
1396         case 'l':
1397             if (qemu_strtoul(curr_data, &curr_data, 16,
1398                              &this_param.val_ul)) {
1399                 return -EINVAL;
1400             }
1401             curr_data = cmd_next_param(curr_data, curr_schema[1]);
1402             g_array_append_val(params, this_param);
1403             break;
1404         case 'L':
1405             if (qemu_strtou64(curr_data, &curr_data, 16,
1406                               (uint64_t *)&this_param.val_ull)) {
1407                 return -EINVAL;
1408             }
1409             curr_data = cmd_next_param(curr_data, curr_schema[1]);
1410             g_array_append_val(params, this_param);
1411             break;
1412         case 's':
1413             this_param.data = curr_data;
1414             curr_data = cmd_next_param(curr_data, curr_schema[1]);
1415             g_array_append_val(params, this_param);
1416             break;
1417         case 'o':
1418             this_param.opcode = *(uint8_t *)curr_data;
1419             curr_data = cmd_next_param(curr_data, curr_schema[1]);
1420             g_array_append_val(params, this_param);
1421             break;
1422         case 't':
1423             this_param.thread_id.kind =
1424                 read_thread_id(curr_data, &curr_data,
1425                                &this_param.thread_id.pid,
1426                                &this_param.thread_id.tid);
1427             curr_data = cmd_next_param(curr_data, curr_schema[1]);
1428             g_array_append_val(params, this_param);
1429             break;
1430         case '?':
1431             curr_data = cmd_next_param(curr_data, curr_schema[1]);
1432             break;
1433         default:
1434             return -EINVAL;
1435         }
1436         curr_schema += 2;
1437     }
1438
1439     return 0;
1440 }
1441
1442 typedef void (*GdbCmdHandler)(GArray *params, void *user_ctx);
1443
1444 /*
1445  * cmd_startswith -> cmd is compared using startswith
1446  *
1447  *
1448  * schema definitions:
1449  * Each schema parameter entry consists of 2 chars,
1450  * the first char represents the parameter type handling
1451  * the second char represents the delimiter for the next parameter
1452  *
1453  * Currently supported schema types:
1454  * 'l' -> unsigned long (stored in .val_ul)
1455  * 'L' -> unsigned long long (stored in .val_ull)
1456  * 's' -> string (stored in .data)
1457  * 'o' -> single char (stored in .opcode)
1458  * 't' -> thread id (stored in .thread_id)
1459  * '?' -> skip according to delimiter
1460  *
1461  * Currently supported delimiters:
1462  * '?' -> Stop at any delimiter (",;:=\0")
1463  * '0' -> Stop at "\0"
1464  * '.' -> Skip 1 char unless reached "\0"
1465  * Any other value is treated as the delimiter value itself
1466  */
1467 typedef struct GdbCmdParseEntry {
1468     GdbCmdHandler handler;
1469     const char *cmd;
1470     bool cmd_startswith;
1471     const char *schema;
1472 } GdbCmdParseEntry;
1473
1474 static inline int startswith(const char *string, const char *pattern)
1475 {
1476   return !strncmp(string, pattern, strlen(pattern));
1477 }
1478
1479 static int process_string_cmd(void *user_ctx, const char *data,
1480                               const GdbCmdParseEntry *cmds, int num_cmds)
1481 {
1482     int i;
1483     g_autoptr(GArray) params = g_array_new(false, true, sizeof(GdbCmdVariant));
1484
1485     if (!cmds) {
1486         return -1;
1487     }
1488
1489     for (i = 0; i < num_cmds; i++) {
1490         const GdbCmdParseEntry *cmd = &cmds[i];
1491         g_assert(cmd->handler && cmd->cmd);
1492
1493         if ((cmd->cmd_startswith && !startswith(data, cmd->cmd)) ||
1494             (!cmd->cmd_startswith && strcmp(cmd->cmd, data))) {
1495             continue;
1496         }
1497
1498         if (cmd->schema) {
1499             if (cmd_parse_params(&data[strlen(cmd->cmd)],
1500                                  cmd->schema, params)) {
1501                 return -1;
1502             }
1503         }
1504
1505         cmd->handler(params, user_ctx);
1506         return 0;
1507     }
1508
1509     return -1;
1510 }
1511
1512 static void run_cmd_parser(const char *data, const GdbCmdParseEntry *cmd)
1513 {
1514     if (!data) {
1515         return;
1516     }
1517
1518     g_string_set_size(gdbserver_state.str_buf, 0);
1519     g_byte_array_set_size(gdbserver_state.mem_buf, 0);
1520
1521     /* In case there was an error during the command parsing we must
1522     * send a NULL packet to indicate the command is not supported */
1523     if (process_string_cmd(NULL, data, cmd, 1)) {
1524         put_packet("");
1525     }
1526 }
1527
1528 static void handle_detach(GArray *params, void *user_ctx)
1529 {
1530     GDBProcess *process;
1531     uint32_t pid = 1;
1532
1533     if (gdbserver_state.multiprocess) {
1534         if (!params->len) {
1535             put_packet("E22");
1536             return;
1537         }
1538
1539         pid = get_param(params, 0)->val_ul;
1540     }
1541
1542     process = gdb_get_process(pid);
1543     gdb_process_breakpoint_remove_all(process);
1544     process->attached = false;
1545
1546     if (pid == gdb_get_cpu_pid(gdbserver_state.c_cpu)) {
1547         gdbserver_state.c_cpu = gdb_first_attached_cpu();
1548     }
1549
1550     if (pid == gdb_get_cpu_pid(gdbserver_state.g_cpu)) {
1551         gdbserver_state.g_cpu = gdb_first_attached_cpu();
1552     }
1553
1554     if (!gdbserver_state.c_cpu) {
1555         /* No more process attached */
1556         gdb_syscall_mode = GDB_SYS_DISABLED;
1557         gdb_continue();
1558     }
1559     put_packet("OK");
1560 }
1561
1562 static void handle_thread_alive(GArray *params, void *user_ctx)
1563 {
1564     CPUState *cpu;
1565
1566     if (!params->len) {
1567         put_packet("E22");
1568         return;
1569     }
1570
1571     if (get_param(params, 0)->thread_id.kind == GDB_READ_THREAD_ERR) {
1572         put_packet("E22");
1573         return;
1574     }
1575
1576     cpu = gdb_get_cpu(get_param(params, 0)->thread_id.pid,
1577                       get_param(params, 0)->thread_id.tid);
1578     if (!cpu) {
1579         put_packet("E22");
1580         return;
1581     }
1582
1583     put_packet("OK");
1584 }
1585
1586 static void handle_continue(GArray *params, void *user_ctx)
1587 {
1588     if (params->len) {
1589         gdb_set_cpu_pc(get_param(params, 0)->val_ull);
1590     }
1591
1592     gdbserver_state.signal = 0;
1593     gdb_continue();
1594 }
1595
1596 static void handle_cont_with_sig(GArray *params, void *user_ctx)
1597 {
1598     unsigned long signal = 0;
1599
1600     /*
1601      * Note: C sig;[addr] is currently unsupported and we simply
1602      *       omit the addr parameter
1603      */
1604     if (params->len) {
1605         signal = get_param(params, 0)->val_ul;
1606     }
1607
1608     gdbserver_state.signal = gdb_signal_to_target(signal);
1609     if (gdbserver_state.signal == -1) {
1610         gdbserver_state.signal = 0;
1611     }
1612     gdb_continue();
1613 }
1614
1615 static void handle_set_thread(GArray *params, void *user_ctx)
1616 {
1617     CPUState *cpu;
1618
1619     if (params->len != 2) {
1620         put_packet("E22");
1621         return;
1622     }
1623
1624     if (get_param(params, 1)->thread_id.kind == GDB_READ_THREAD_ERR) {
1625         put_packet("E22");
1626         return;
1627     }
1628
1629     if (get_param(params, 1)->thread_id.kind != GDB_ONE_THREAD) {
1630         put_packet("OK");
1631         return;
1632     }
1633
1634     cpu = gdb_get_cpu(get_param(params, 1)->thread_id.pid,
1635                       get_param(params, 1)->thread_id.tid);
1636     if (!cpu) {
1637         put_packet("E22");
1638         return;
1639     }
1640
1641     /*
1642      * Note: This command is deprecated and modern gdb's will be using the
1643      *       vCont command instead.
1644      */
1645     switch (get_param(params, 0)->opcode) {
1646     case 'c':
1647         gdbserver_state.c_cpu = cpu;
1648         put_packet("OK");
1649         break;
1650     case 'g':
1651         gdbserver_state.g_cpu = cpu;
1652         put_packet("OK");
1653         break;
1654     default:
1655         put_packet("E22");
1656         break;
1657     }
1658 }
1659
1660 static void handle_insert_bp(GArray *params, void *user_ctx)
1661 {
1662     int res;
1663
1664     if (params->len != 3) {
1665         put_packet("E22");
1666         return;
1667     }
1668
1669     res = gdb_breakpoint_insert(get_param(params, 0)->val_ul,
1670                                 get_param(params, 1)->val_ull,
1671                                 get_param(params, 2)->val_ull);
1672     if (res >= 0) {
1673         put_packet("OK");
1674         return;
1675     } else if (res == -ENOSYS) {
1676         put_packet("");
1677         return;
1678     }
1679
1680     put_packet("E22");
1681 }
1682
1683 static void handle_remove_bp(GArray *params, void *user_ctx)
1684 {
1685     int res;
1686
1687     if (params->len != 3) {
1688         put_packet("E22");
1689         return;
1690     }
1691
1692     res = gdb_breakpoint_remove(get_param(params, 0)->val_ul,
1693                                 get_param(params, 1)->val_ull,
1694                                 get_param(params, 2)->val_ull);
1695     if (res >= 0) {
1696         put_packet("OK");
1697         return;
1698     } else if (res == -ENOSYS) {
1699         put_packet("");
1700         return;
1701     }
1702
1703     put_packet("E22");
1704 }
1705
1706 /*
1707  * handle_set/get_reg
1708  *
1709  * Older gdb are really dumb, and don't use 'G/g' if 'P/p' is available.
1710  * This works, but can be very slow. Anything new enough to understand
1711  * XML also knows how to use this properly. However to use this we
1712  * need to define a local XML file as well as be talking to a
1713  * reasonably modern gdb. Responding with an empty packet will cause
1714  * the remote gdb to fallback to older methods.
1715  */
1716
1717 static void handle_set_reg(GArray *params, void *user_ctx)
1718 {
1719     int reg_size;
1720
1721     if (!gdb_has_xml) {
1722         put_packet("");
1723         return;
1724     }
1725
1726     if (params->len != 2) {
1727         put_packet("E22");
1728         return;
1729     }
1730
1731     reg_size = strlen(get_param(params, 1)->data) / 2;
1732     hextomem(gdbserver_state.mem_buf, get_param(params, 1)->data, reg_size);
1733     gdb_write_register(gdbserver_state.g_cpu, gdbserver_state.mem_buf->data,
1734                        get_param(params, 0)->val_ull);
1735     put_packet("OK");
1736 }
1737
1738 static void handle_get_reg(GArray *params, void *user_ctx)
1739 {
1740     int reg_size;
1741
1742     if (!gdb_has_xml) {
1743         put_packet("");
1744         return;
1745     }
1746
1747     if (!params->len) {
1748         put_packet("E14");
1749         return;
1750     }
1751
1752     reg_size = gdb_read_register(gdbserver_state.g_cpu,
1753                                  gdbserver_state.mem_buf,
1754                                  get_param(params, 0)->val_ull);
1755     if (!reg_size) {
1756         put_packet("E14");
1757         return;
1758     } else {
1759         g_byte_array_set_size(gdbserver_state.mem_buf, reg_size);
1760     }
1761
1762     memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data, reg_size);
1763     put_strbuf();
1764 }
1765
1766 static void handle_write_mem(GArray *params, void *user_ctx)
1767 {
1768     if (params->len != 3) {
1769         put_packet("E22");
1770         return;
1771     }
1772
1773     /* hextomem() reads 2*len bytes */
1774     if (get_param(params, 1)->val_ull >
1775         strlen(get_param(params, 2)->data) / 2) {
1776         put_packet("E22");
1777         return;
1778     }
1779
1780     hextomem(gdbserver_state.mem_buf, get_param(params, 2)->data,
1781              get_param(params, 1)->val_ull);
1782     if (target_memory_rw_debug(gdbserver_state.g_cpu,
1783                                get_param(params, 0)->val_ull,
1784                                gdbserver_state.mem_buf->data,
1785                                gdbserver_state.mem_buf->len, true)) {
1786         put_packet("E14");
1787         return;
1788     }
1789
1790     put_packet("OK");
1791 }
1792
1793 static void handle_read_mem(GArray *params, void *user_ctx)
1794 {
1795     if (params->len != 2) {
1796         put_packet("E22");
1797         return;
1798     }
1799
1800     /* memtohex() doubles the required space */
1801     if (get_param(params, 1)->val_ull > MAX_PACKET_LENGTH / 2) {
1802         put_packet("E22");
1803         return;
1804     }
1805
1806     g_byte_array_set_size(gdbserver_state.mem_buf,
1807                           get_param(params, 1)->val_ull);
1808
1809     if (target_memory_rw_debug(gdbserver_state.g_cpu,
1810                                get_param(params, 0)->val_ull,
1811                                gdbserver_state.mem_buf->data,
1812                                gdbserver_state.mem_buf->len, false)) {
1813         put_packet("E14");
1814         return;
1815     }
1816
1817     memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data,
1818              gdbserver_state.mem_buf->len);
1819     put_strbuf();
1820 }
1821
1822 static void handle_write_all_regs(GArray *params, void *user_ctx)
1823 {
1824     target_ulong addr, len;
1825     uint8_t *registers;
1826     int reg_size;
1827
1828     if (!params->len) {
1829         return;
1830     }
1831
1832     cpu_synchronize_state(gdbserver_state.g_cpu);
1833     len = strlen(get_param(params, 0)->data) / 2;
1834     hextomem(gdbserver_state.mem_buf, get_param(params, 0)->data, len);
1835     registers = gdbserver_state.mem_buf->data;
1836     for (addr = 0; addr < gdbserver_state.g_cpu->gdb_num_g_regs && len > 0;
1837          addr++) {
1838         reg_size = gdb_write_register(gdbserver_state.g_cpu, registers, addr);
1839         len -= reg_size;
1840         registers += reg_size;
1841     }
1842     put_packet("OK");
1843 }
1844
1845 static void handle_read_all_regs(GArray *params, void *user_ctx)
1846 {
1847     target_ulong addr, len;
1848
1849     cpu_synchronize_state(gdbserver_state.g_cpu);
1850     g_byte_array_set_size(gdbserver_state.mem_buf, 0);
1851     len = 0;
1852     for (addr = 0; addr < gdbserver_state.g_cpu->gdb_num_g_regs; addr++) {
1853         len += gdb_read_register(gdbserver_state.g_cpu,
1854                                  gdbserver_state.mem_buf,
1855                                  addr);
1856     }
1857     g_assert(len == gdbserver_state.mem_buf->len);
1858
1859     memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data, len);
1860     put_strbuf();
1861 }
1862
1863 static void handle_file_io(GArray *params, void *user_ctx)
1864 {
1865     if (params->len >= 1 && gdbserver_state.current_syscall_cb) {
1866         target_ulong ret, err;
1867
1868         ret = (target_ulong)get_param(params, 0)->val_ull;
1869         if (params->len >= 2) {
1870             err = (target_ulong)get_param(params, 1)->val_ull;
1871         } else {
1872             err = 0;
1873         }
1874         gdbserver_state.current_syscall_cb(gdbserver_state.c_cpu, ret, err);
1875         gdbserver_state.current_syscall_cb = NULL;
1876     }
1877
1878     if (params->len >= 3 && get_param(params, 2)->opcode == (uint8_t)'C') {
1879         put_packet("T02");
1880         return;
1881     }
1882
1883     gdb_continue();
1884 }
1885
1886 static void handle_step(GArray *params, void *user_ctx)
1887 {
1888     if (params->len) {
1889         gdb_set_cpu_pc((target_ulong)get_param(params, 0)->val_ull);
1890     }
1891
1892     cpu_single_step(gdbserver_state.c_cpu, gdbserver_state.sstep_flags);
1893     gdb_continue();
1894 }
1895
1896 static void handle_backward(GArray *params, void *user_ctx)
1897 {
1898     if (!stub_can_reverse()) {
1899         put_packet("E22");
1900     }
1901     if (params->len == 1) {
1902         switch (get_param(params, 0)->opcode) {
1903         case 's':
1904             if (replay_reverse_step()) {
1905                 gdb_continue();
1906             } else {
1907                 put_packet("E14");
1908             }
1909             return;
1910         case 'c':
1911             if (replay_reverse_continue()) {
1912                 gdb_continue();
1913             } else {
1914                 put_packet("E14");
1915             }
1916             return;
1917         }
1918     }
1919
1920     /* Default invalid command */
1921     put_packet("");
1922 }
1923
1924 static void handle_v_cont_query(GArray *params, void *user_ctx)
1925 {
1926     put_packet("vCont;c;C;s;S");
1927 }
1928
1929 static void handle_v_cont(GArray *params, void *user_ctx)
1930 {
1931     int res;
1932
1933     if (!params->len) {
1934         return;
1935     }
1936
1937     res = gdb_handle_vcont(get_param(params, 0)->data);
1938     if ((res == -EINVAL) || (res == -ERANGE)) {
1939         put_packet("E22");
1940     } else if (res) {
1941         put_packet("");
1942     }
1943 }
1944
1945 static void handle_v_attach(GArray *params, void *user_ctx)
1946 {
1947     GDBProcess *process;
1948     CPUState *cpu;
1949
1950     g_string_assign(gdbserver_state.str_buf, "E22");
1951     if (!params->len) {
1952         goto cleanup;
1953     }
1954
1955     process = gdb_get_process(get_param(params, 0)->val_ul);
1956     if (!process) {
1957         goto cleanup;
1958     }
1959
1960     cpu = get_first_cpu_in_process(process);
1961     if (!cpu) {
1962         goto cleanup;
1963     }
1964
1965     process->attached = true;
1966     gdbserver_state.g_cpu = cpu;
1967     gdbserver_state.c_cpu = cpu;
1968
1969     g_string_printf(gdbserver_state.str_buf, "T%02xthread:", GDB_SIGNAL_TRAP);
1970     gdb_append_thread_id(cpu, gdbserver_state.str_buf);
1971     g_string_append_c(gdbserver_state.str_buf, ';');
1972 cleanup:
1973     put_strbuf();
1974 }
1975
1976 static void handle_v_kill(GArray *params, void *user_ctx)
1977 {
1978     /* Kill the target */
1979     put_packet("OK");
1980     error_report("QEMU: Terminated via GDBstub");
1981     gdb_exit(0);
1982     exit(0);
1983 }
1984
1985 static const GdbCmdParseEntry gdb_v_commands_table[] = {
1986     /* Order is important if has same prefix */
1987     {
1988         .handler = handle_v_cont_query,
1989         .cmd = "Cont?",
1990         .cmd_startswith = 1
1991     },
1992     {
1993         .handler = handle_v_cont,
1994         .cmd = "Cont",
1995         .cmd_startswith = 1,
1996         .schema = "s0"
1997     },
1998     {
1999         .handler = handle_v_attach,
2000         .cmd = "Attach;",
2001         .cmd_startswith = 1,
2002         .schema = "l0"
2003     },
2004     {
2005         .handler = handle_v_kill,
2006         .cmd = "Kill;",
2007         .cmd_startswith = 1
2008     },
2009 };
2010
2011 static void handle_v_commands(GArray *params, void *user_ctx)
2012 {
2013     if (!params->len) {
2014         return;
2015     }
2016
2017     if (process_string_cmd(NULL, get_param(params, 0)->data,
2018                            gdb_v_commands_table,
2019                            ARRAY_SIZE(gdb_v_commands_table))) {
2020         put_packet("");
2021     }
2022 }
2023
2024 static void handle_query_qemu_sstepbits(GArray *params, void *user_ctx)
2025 {
2026     g_string_printf(gdbserver_state.str_buf, "ENABLE=%x", SSTEP_ENABLE);
2027
2028     if (gdbserver_state.supported_sstep_flags & SSTEP_NOIRQ) {
2029         g_string_append_printf(gdbserver_state.str_buf, ",NOIRQ=%x",
2030                                SSTEP_NOIRQ);
2031     }
2032
2033     if (gdbserver_state.supported_sstep_flags & SSTEP_NOTIMER) {
2034         g_string_append_printf(gdbserver_state.str_buf, ",NOTIMER=%x",
2035                                SSTEP_NOTIMER);
2036     }
2037
2038     put_strbuf();
2039 }
2040
2041 static void handle_set_qemu_sstep(GArray *params, void *user_ctx)
2042 {
2043     int new_sstep_flags;
2044
2045     if (!params->len) {
2046         return;
2047     }
2048
2049     new_sstep_flags = get_param(params, 0)->val_ul;
2050
2051     if (new_sstep_flags  & ~gdbserver_state.supported_sstep_flags) {
2052         put_packet("E22");
2053         return;
2054     }
2055
2056     gdbserver_state.sstep_flags = new_sstep_flags;
2057     put_packet("OK");
2058 }
2059
2060 static void handle_query_qemu_sstep(GArray *params, void *user_ctx)
2061 {
2062     g_string_printf(gdbserver_state.str_buf, "0x%x",
2063                     gdbserver_state.sstep_flags);
2064     put_strbuf();
2065 }
2066
2067 static void handle_query_curr_tid(GArray *params, void *user_ctx)
2068 {
2069     CPUState *cpu;
2070     GDBProcess *process;
2071
2072     /*
2073      * "Current thread" remains vague in the spec, so always return
2074      * the first thread of the current process (gdb returns the
2075      * first thread).
2076      */
2077     process = gdb_get_cpu_process(gdbserver_state.g_cpu);
2078     cpu = get_first_cpu_in_process(process);
2079     g_string_assign(gdbserver_state.str_buf, "QC");
2080     gdb_append_thread_id(cpu, gdbserver_state.str_buf);
2081     put_strbuf();
2082 }
2083
2084 static void handle_query_threads(GArray *params, void *user_ctx)
2085 {
2086     if (!gdbserver_state.query_cpu) {
2087         put_packet("l");
2088         return;
2089     }
2090
2091     g_string_assign(gdbserver_state.str_buf, "m");
2092     gdb_append_thread_id(gdbserver_state.query_cpu, gdbserver_state.str_buf);
2093     put_strbuf();
2094     gdbserver_state.query_cpu = gdb_next_attached_cpu(gdbserver_state.query_cpu);
2095 }
2096
2097 static void handle_query_first_threads(GArray *params, void *user_ctx)
2098 {
2099     gdbserver_state.query_cpu = gdb_first_attached_cpu();
2100     handle_query_threads(params, user_ctx);
2101 }
2102
2103 static void handle_query_thread_extra(GArray *params, void *user_ctx)
2104 {
2105     g_autoptr(GString) rs = g_string_new(NULL);
2106     CPUState *cpu;
2107
2108     if (!params->len ||
2109         get_param(params, 0)->thread_id.kind == GDB_READ_THREAD_ERR) {
2110         put_packet("E22");
2111         return;
2112     }
2113
2114     cpu = gdb_get_cpu(get_param(params, 0)->thread_id.pid,
2115                       get_param(params, 0)->thread_id.tid);
2116     if (!cpu) {
2117         return;
2118     }
2119
2120     cpu_synchronize_state(cpu);
2121
2122     if (gdbserver_state.multiprocess && (gdbserver_state.process_num > 1)) {
2123         /* Print the CPU model and name in multiprocess mode */
2124         ObjectClass *oc = object_get_class(OBJECT(cpu));
2125         const char *cpu_model = object_class_get_name(oc);
2126         const char *cpu_name =
2127             object_get_canonical_path_component(OBJECT(cpu));
2128         g_string_printf(rs, "%s %s [%s]", cpu_model, cpu_name,
2129                         cpu->halted ? "halted " : "running");
2130     } else {
2131         g_string_printf(rs, "CPU#%d [%s]", cpu->cpu_index,
2132                         cpu->halted ? "halted " : "running");
2133     }
2134     trace_gdbstub_op_extra_info(rs->str);
2135     memtohex(gdbserver_state.str_buf, (uint8_t *)rs->str, rs->len);
2136     put_strbuf();
2137 }
2138
2139 #ifdef CONFIG_USER_ONLY
2140 static void handle_query_offsets(GArray *params, void *user_ctx)
2141 {
2142     TaskState *ts;
2143
2144     ts = gdbserver_state.c_cpu->opaque;
2145     g_string_printf(gdbserver_state.str_buf,
2146                     "Text=" TARGET_ABI_FMT_lx
2147                     ";Data=" TARGET_ABI_FMT_lx
2148                     ";Bss=" TARGET_ABI_FMT_lx,
2149                     ts->info->code_offset,
2150                     ts->info->data_offset,
2151                     ts->info->data_offset);
2152     put_strbuf();
2153 }
2154 #else
2155 static void handle_query_rcmd(GArray *params, void *user_ctx)
2156 {
2157     const guint8 zero = 0;
2158     int len;
2159
2160     if (!params->len) {
2161         put_packet("E22");
2162         return;
2163     }
2164
2165     len = strlen(get_param(params, 0)->data);
2166     if (len % 2) {
2167         put_packet("E01");
2168         return;
2169     }
2170
2171     g_assert(gdbserver_state.mem_buf->len == 0);
2172     len = len / 2;
2173     hextomem(gdbserver_state.mem_buf, get_param(params, 0)->data, len);
2174     g_byte_array_append(gdbserver_state.mem_buf, &zero, 1);
2175     qemu_chr_be_write(gdbserver_state.mon_chr, gdbserver_state.mem_buf->data,
2176                       gdbserver_state.mem_buf->len);
2177     put_packet("OK");
2178 }
2179 #endif
2180
2181 static void handle_query_supported(GArray *params, void *user_ctx)
2182 {
2183     CPUClass *cc;
2184
2185     g_string_printf(gdbserver_state.str_buf, "PacketSize=%x", MAX_PACKET_LENGTH);
2186     cc = CPU_GET_CLASS(first_cpu);
2187     if (cc->gdb_core_xml_file) {
2188         g_string_append(gdbserver_state.str_buf, ";qXfer:features:read+");
2189     }
2190
2191     if (stub_can_reverse()) {
2192         g_string_append(gdbserver_state.str_buf,
2193             ";ReverseStep+;ReverseContinue+");
2194     }
2195
2196 #ifdef CONFIG_USER_ONLY
2197     if (gdbserver_state.c_cpu->opaque) {
2198         g_string_append(gdbserver_state.str_buf, ";qXfer:auxv:read+");
2199     }
2200 #endif
2201
2202     if (params->len &&
2203         strstr(get_param(params, 0)->data, "multiprocess+")) {
2204         gdbserver_state.multiprocess = true;
2205     }
2206
2207     g_string_append(gdbserver_state.str_buf, ";vContSupported+;multiprocess+");
2208     put_strbuf();
2209 }
2210
2211 static void handle_query_xfer_features(GArray *params, void *user_ctx)
2212 {
2213     GDBProcess *process;
2214     CPUClass *cc;
2215     unsigned long len, total_len, addr;
2216     const char *xml;
2217     const char *p;
2218
2219     if (params->len < 3) {
2220         put_packet("E22");
2221         return;
2222     }
2223
2224     process = gdb_get_cpu_process(gdbserver_state.g_cpu);
2225     cc = CPU_GET_CLASS(gdbserver_state.g_cpu);
2226     if (!cc->gdb_core_xml_file) {
2227         put_packet("");
2228         return;
2229     }
2230
2231     gdb_has_xml = true;
2232     p = get_param(params, 0)->data;
2233     xml = get_feature_xml(p, &p, process);
2234     if (!xml) {
2235         put_packet("E00");
2236         return;
2237     }
2238
2239     addr = get_param(params, 1)->val_ul;
2240     len = get_param(params, 2)->val_ul;
2241     total_len = strlen(xml);
2242     if (addr > total_len) {
2243         put_packet("E00");
2244         return;
2245     }
2246
2247     if (len > (MAX_PACKET_LENGTH - 5) / 2) {
2248         len = (MAX_PACKET_LENGTH - 5) / 2;
2249     }
2250
2251     if (len < total_len - addr) {
2252         g_string_assign(gdbserver_state.str_buf, "m");
2253         memtox(gdbserver_state.str_buf, xml + addr, len);
2254     } else {
2255         g_string_assign(gdbserver_state.str_buf, "l");
2256         memtox(gdbserver_state.str_buf, xml + addr, total_len - addr);
2257     }
2258
2259     put_packet_binary(gdbserver_state.str_buf->str,
2260                       gdbserver_state.str_buf->len, true);
2261 }
2262
2263 #if defined(CONFIG_USER_ONLY) && defined(CONFIG_LINUX_USER)
2264 static void handle_query_xfer_auxv(GArray *params, void *user_ctx)
2265 {
2266     TaskState *ts;
2267     unsigned long offset, len, saved_auxv, auxv_len;
2268
2269     if (params->len < 2) {
2270         put_packet("E22");
2271         return;
2272     }
2273
2274     offset = get_param(params, 0)->val_ul;
2275     len = get_param(params, 1)->val_ul;
2276     ts = gdbserver_state.c_cpu->opaque;
2277     saved_auxv = ts->info->saved_auxv;
2278     auxv_len = ts->info->auxv_len;
2279
2280     if (offset >= auxv_len) {
2281         put_packet("E00");
2282         return;
2283     }
2284
2285     if (len > (MAX_PACKET_LENGTH - 5) / 2) {
2286         len = (MAX_PACKET_LENGTH - 5) / 2;
2287     }
2288
2289     if (len < auxv_len - offset) {
2290         g_string_assign(gdbserver_state.str_buf, "m");
2291     } else {
2292         g_string_assign(gdbserver_state.str_buf, "l");
2293         len = auxv_len - offset;
2294     }
2295
2296     g_byte_array_set_size(gdbserver_state.mem_buf, len);
2297     if (target_memory_rw_debug(gdbserver_state.g_cpu, saved_auxv + offset,
2298                                gdbserver_state.mem_buf->data, len, false)) {
2299         put_packet("E14");
2300         return;
2301     }
2302
2303     memtox(gdbserver_state.str_buf,
2304            (const char *)gdbserver_state.mem_buf->data, len);
2305     put_packet_binary(gdbserver_state.str_buf->str,
2306                       gdbserver_state.str_buf->len, true);
2307 }
2308 #endif
2309
2310 static void handle_query_attached(GArray *params, void *user_ctx)
2311 {
2312     put_packet(GDB_ATTACHED);
2313 }
2314
2315 static void handle_query_qemu_supported(GArray *params, void *user_ctx)
2316 {
2317     g_string_printf(gdbserver_state.str_buf, "sstepbits;sstep");
2318 #ifndef CONFIG_USER_ONLY
2319     g_string_append(gdbserver_state.str_buf, ";PhyMemMode");
2320 #endif
2321     put_strbuf();
2322 }
2323
2324 #ifndef CONFIG_USER_ONLY
2325 static void handle_query_qemu_phy_mem_mode(GArray *params,
2326                                            void *user_ctx)
2327 {
2328     g_string_printf(gdbserver_state.str_buf, "%d", phy_memory_mode);
2329     put_strbuf();
2330 }
2331
2332 static void handle_set_qemu_phy_mem_mode(GArray *params, void *user_ctx)
2333 {
2334     if (!params->len) {
2335         put_packet("E22");
2336         return;
2337     }
2338
2339     if (!get_param(params, 0)->val_ul) {
2340         phy_memory_mode = 0;
2341     } else {
2342         phy_memory_mode = 1;
2343     }
2344     put_packet("OK");
2345 }
2346 #endif
2347
2348 static const GdbCmdParseEntry gdb_gen_query_set_common_table[] = {
2349     /* Order is important if has same prefix */
2350     {
2351         .handler = handle_query_qemu_sstepbits,
2352         .cmd = "qemu.sstepbits",
2353     },
2354     {
2355         .handler = handle_query_qemu_sstep,
2356         .cmd = "qemu.sstep",
2357     },
2358     {
2359         .handler = handle_set_qemu_sstep,
2360         .cmd = "qemu.sstep=",
2361         .cmd_startswith = 1,
2362         .schema = "l0"
2363     },
2364 };
2365
2366 static const GdbCmdParseEntry gdb_gen_query_table[] = {
2367     {
2368         .handler = handle_query_curr_tid,
2369         .cmd = "C",
2370     },
2371     {
2372         .handler = handle_query_threads,
2373         .cmd = "sThreadInfo",
2374     },
2375     {
2376         .handler = handle_query_first_threads,
2377         .cmd = "fThreadInfo",
2378     },
2379     {
2380         .handler = handle_query_thread_extra,
2381         .cmd = "ThreadExtraInfo,",
2382         .cmd_startswith = 1,
2383         .schema = "t0"
2384     },
2385 #ifdef CONFIG_USER_ONLY
2386     {
2387         .handler = handle_query_offsets,
2388         .cmd = "Offsets",
2389     },
2390 #else
2391     {
2392         .handler = handle_query_rcmd,
2393         .cmd = "Rcmd,",
2394         .cmd_startswith = 1,
2395         .schema = "s0"
2396     },
2397 #endif
2398     {
2399         .handler = handle_query_supported,
2400         .cmd = "Supported:",
2401         .cmd_startswith = 1,
2402         .schema = "s0"
2403     },
2404     {
2405         .handler = handle_query_supported,
2406         .cmd = "Supported",
2407         .schema = "s0"
2408     },
2409     {
2410         .handler = handle_query_xfer_features,
2411         .cmd = "Xfer:features:read:",
2412         .cmd_startswith = 1,
2413         .schema = "s:l,l0"
2414     },
2415 #if defined(CONFIG_USER_ONLY) && defined(CONFIG_LINUX_USER)
2416     {
2417         .handler = handle_query_xfer_auxv,
2418         .cmd = "Xfer:auxv:read::",
2419         .cmd_startswith = 1,
2420         .schema = "l,l0"
2421     },
2422 #endif
2423     {
2424         .handler = handle_query_attached,
2425         .cmd = "Attached:",
2426         .cmd_startswith = 1
2427     },
2428     {
2429         .handler = handle_query_attached,
2430         .cmd = "Attached",
2431     },
2432     {
2433         .handler = handle_query_qemu_supported,
2434         .cmd = "qemu.Supported",
2435     },
2436 #ifndef CONFIG_USER_ONLY
2437     {
2438         .handler = handle_query_qemu_phy_mem_mode,
2439         .cmd = "qemu.PhyMemMode",
2440     },
2441 #endif
2442 };
2443
2444 static const GdbCmdParseEntry gdb_gen_set_table[] = {
2445     /* Order is important if has same prefix */
2446     {
2447         .handler = handle_set_qemu_sstep,
2448         .cmd = "qemu.sstep:",
2449         .cmd_startswith = 1,
2450         .schema = "l0"
2451     },
2452 #ifndef CONFIG_USER_ONLY
2453     {
2454         .handler = handle_set_qemu_phy_mem_mode,
2455         .cmd = "qemu.PhyMemMode:",
2456         .cmd_startswith = 1,
2457         .schema = "l0"
2458     },
2459 #endif
2460 };
2461
2462 static void handle_gen_query(GArray *params, void *user_ctx)
2463 {
2464     if (!params->len) {
2465         return;
2466     }
2467
2468     if (!process_string_cmd(NULL, get_param(params, 0)->data,
2469                             gdb_gen_query_set_common_table,
2470                             ARRAY_SIZE(gdb_gen_query_set_common_table))) {
2471         return;
2472     }
2473
2474     if (process_string_cmd(NULL, get_param(params, 0)->data,
2475                            gdb_gen_query_table,
2476                            ARRAY_SIZE(gdb_gen_query_table))) {
2477         put_packet("");
2478     }
2479 }
2480
2481 static void handle_gen_set(GArray *params, void *user_ctx)
2482 {
2483     if (!params->len) {
2484         return;
2485     }
2486
2487     if (!process_string_cmd(NULL, get_param(params, 0)->data,
2488                             gdb_gen_query_set_common_table,
2489                             ARRAY_SIZE(gdb_gen_query_set_common_table))) {
2490         return;
2491     }
2492
2493     if (process_string_cmd(NULL, get_param(params, 0)->data,
2494                            gdb_gen_set_table,
2495                            ARRAY_SIZE(gdb_gen_set_table))) {
2496         put_packet("");
2497     }
2498 }
2499
2500 static void handle_target_halt(GArray *params, void *user_ctx)
2501 {
2502     g_string_printf(gdbserver_state.str_buf, "T%02xthread:", GDB_SIGNAL_TRAP);
2503     gdb_append_thread_id(gdbserver_state.c_cpu, gdbserver_state.str_buf);
2504     g_string_append_c(gdbserver_state.str_buf, ';');
2505     put_strbuf();
2506     /*
2507      * Remove all the breakpoints when this query is issued,
2508      * because gdb is doing an initial connect and the state
2509      * should be cleaned up.
2510      */
2511     gdb_breakpoint_remove_all();
2512 }
2513
2514 static int gdb_handle_packet(const char *line_buf)
2515 {
2516     const GdbCmdParseEntry *cmd_parser = NULL;
2517
2518     trace_gdbstub_io_command(line_buf);
2519
2520     switch (line_buf[0]) {
2521     case '!':
2522         put_packet("OK");
2523         break;
2524     case '?':
2525         {
2526             static const GdbCmdParseEntry target_halted_cmd_desc = {
2527                 .handler = handle_target_halt,
2528                 .cmd = "?",
2529                 .cmd_startswith = 1
2530             };
2531             cmd_parser = &target_halted_cmd_desc;
2532         }
2533         break;
2534     case 'c':
2535         {
2536             static const GdbCmdParseEntry continue_cmd_desc = {
2537                 .handler = handle_continue,
2538                 .cmd = "c",
2539                 .cmd_startswith = 1,
2540                 .schema = "L0"
2541             };
2542             cmd_parser = &continue_cmd_desc;
2543         }
2544         break;
2545     case 'C':
2546         {
2547             static const GdbCmdParseEntry cont_with_sig_cmd_desc = {
2548                 .handler = handle_cont_with_sig,
2549                 .cmd = "C",
2550                 .cmd_startswith = 1,
2551                 .schema = "l0"
2552             };
2553             cmd_parser = &cont_with_sig_cmd_desc;
2554         }
2555         break;
2556     case 'v':
2557         {
2558             static const GdbCmdParseEntry v_cmd_desc = {
2559                 .handler = handle_v_commands,
2560                 .cmd = "v",
2561                 .cmd_startswith = 1,
2562                 .schema = "s0"
2563             };
2564             cmd_parser = &v_cmd_desc;
2565         }
2566         break;
2567     case 'k':
2568         /* Kill the target */
2569         error_report("QEMU: Terminated via GDBstub");
2570         gdb_exit(0);
2571         exit(0);
2572     case 'D':
2573         {
2574             static const GdbCmdParseEntry detach_cmd_desc = {
2575                 .handler = handle_detach,
2576                 .cmd = "D",
2577                 .cmd_startswith = 1,
2578                 .schema = "?.l0"
2579             };
2580             cmd_parser = &detach_cmd_desc;
2581         }
2582         break;
2583     case 's':
2584         {
2585             static const GdbCmdParseEntry step_cmd_desc = {
2586                 .handler = handle_step,
2587                 .cmd = "s",
2588                 .cmd_startswith = 1,
2589                 .schema = "L0"
2590             };
2591             cmd_parser = &step_cmd_desc;
2592         }
2593         break;
2594     case 'b':
2595         {
2596             static const GdbCmdParseEntry backward_cmd_desc = {
2597                 .handler = handle_backward,
2598                 .cmd = "b",
2599                 .cmd_startswith = 1,
2600                 .schema = "o0"
2601             };
2602             cmd_parser = &backward_cmd_desc;
2603         }
2604         break;
2605     case 'F':
2606         {
2607             static const GdbCmdParseEntry file_io_cmd_desc = {
2608                 .handler = handle_file_io,
2609                 .cmd = "F",
2610                 .cmd_startswith = 1,
2611                 .schema = "L,L,o0"
2612             };
2613             cmd_parser = &file_io_cmd_desc;
2614         }
2615         break;
2616     case 'g':
2617         {
2618             static const GdbCmdParseEntry read_all_regs_cmd_desc = {
2619                 .handler = handle_read_all_regs,
2620                 .cmd = "g",
2621                 .cmd_startswith = 1
2622             };
2623             cmd_parser = &read_all_regs_cmd_desc;
2624         }
2625         break;
2626     case 'G':
2627         {
2628             static const GdbCmdParseEntry write_all_regs_cmd_desc = {
2629                 .handler = handle_write_all_regs,
2630                 .cmd = "G",
2631                 .cmd_startswith = 1,
2632                 .schema = "s0"
2633             };
2634             cmd_parser = &write_all_regs_cmd_desc;
2635         }
2636         break;
2637     case 'm':
2638         {
2639             static const GdbCmdParseEntry read_mem_cmd_desc = {
2640                 .handler = handle_read_mem,
2641                 .cmd = "m",
2642                 .cmd_startswith = 1,
2643                 .schema = "L,L0"
2644             };
2645             cmd_parser = &read_mem_cmd_desc;
2646         }
2647         break;
2648     case 'M':
2649         {
2650             static const GdbCmdParseEntry write_mem_cmd_desc = {
2651                 .handler = handle_write_mem,
2652                 .cmd = "M",
2653                 .cmd_startswith = 1,
2654                 .schema = "L,L:s0"
2655             };
2656             cmd_parser = &write_mem_cmd_desc;
2657         }
2658         break;
2659     case 'p':
2660         {
2661             static const GdbCmdParseEntry get_reg_cmd_desc = {
2662                 .handler = handle_get_reg,
2663                 .cmd = "p",
2664                 .cmd_startswith = 1,
2665                 .schema = "L0"
2666             };
2667             cmd_parser = &get_reg_cmd_desc;
2668         }
2669         break;
2670     case 'P':
2671         {
2672             static const GdbCmdParseEntry set_reg_cmd_desc = {
2673                 .handler = handle_set_reg,
2674                 .cmd = "P",
2675                 .cmd_startswith = 1,
2676                 .schema = "L?s0"
2677             };
2678             cmd_parser = &set_reg_cmd_desc;
2679         }
2680         break;
2681     case 'Z':
2682         {
2683             static const GdbCmdParseEntry insert_bp_cmd_desc = {
2684                 .handler = handle_insert_bp,
2685                 .cmd = "Z",
2686                 .cmd_startswith = 1,
2687                 .schema = "l?L?L0"
2688             };
2689             cmd_parser = &insert_bp_cmd_desc;
2690         }
2691         break;
2692     case 'z':
2693         {
2694             static const GdbCmdParseEntry remove_bp_cmd_desc = {
2695                 .handler = handle_remove_bp,
2696                 .cmd = "z",
2697                 .cmd_startswith = 1,
2698                 .schema = "l?L?L0"
2699             };
2700             cmd_parser = &remove_bp_cmd_desc;
2701         }
2702         break;
2703     case 'H':
2704         {
2705             static const GdbCmdParseEntry set_thread_cmd_desc = {
2706                 .handler = handle_set_thread,
2707                 .cmd = "H",
2708                 .cmd_startswith = 1,
2709                 .schema = "o.t0"
2710             };
2711             cmd_parser = &set_thread_cmd_desc;
2712         }
2713         break;
2714     case 'T':
2715         {
2716             static const GdbCmdParseEntry thread_alive_cmd_desc = {
2717                 .handler = handle_thread_alive,
2718                 .cmd = "T",
2719                 .cmd_startswith = 1,
2720                 .schema = "t0"
2721             };
2722             cmd_parser = &thread_alive_cmd_desc;
2723         }
2724         break;
2725     case 'q':
2726         {
2727             static const GdbCmdParseEntry gen_query_cmd_desc = {
2728                 .handler = handle_gen_query,
2729                 .cmd = "q",
2730                 .cmd_startswith = 1,
2731                 .schema = "s0"
2732             };
2733             cmd_parser = &gen_query_cmd_desc;
2734         }
2735         break;
2736     case 'Q':
2737         {
2738             static const GdbCmdParseEntry gen_set_cmd_desc = {
2739                 .handler = handle_gen_set,
2740                 .cmd = "Q",
2741                 .cmd_startswith = 1,
2742                 .schema = "s0"
2743             };
2744             cmd_parser = &gen_set_cmd_desc;
2745         }
2746         break;
2747     default:
2748         /* put empty packet */
2749         put_packet("");
2750         break;
2751     }
2752
2753     if (cmd_parser) {
2754         run_cmd_parser(line_buf, cmd_parser);
2755     }
2756
2757     return RS_IDLE;
2758 }
2759
2760 void gdb_set_stop_cpu(CPUState *cpu)
2761 {
2762     GDBProcess *p = gdb_get_cpu_process(cpu);
2763
2764     if (!p->attached) {
2765         /*
2766          * Having a stop CPU corresponding to a process that is not attached
2767          * confuses GDB. So we ignore the request.
2768          */
2769         return;
2770     }
2771
2772     gdbserver_state.c_cpu = cpu;
2773     gdbserver_state.g_cpu = cpu;
2774 }
2775
2776 #ifndef CONFIG_USER_ONLY
2777 static void gdb_vm_state_change(void *opaque, bool running, RunState state)
2778 {
2779     CPUState *cpu = gdbserver_state.c_cpu;
2780     g_autoptr(GString) buf = g_string_new(NULL);
2781     g_autoptr(GString) tid = g_string_new(NULL);
2782     const char *type;
2783     int ret;
2784
2785     if (running || gdbserver_state.state == RS_INACTIVE) {
2786         return;
2787     }
2788     /* Is there a GDB syscall waiting to be sent?  */
2789     if (gdbserver_state.current_syscall_cb) {
2790         put_packet(gdbserver_state.syscall_buf);
2791         return;
2792     }
2793
2794     if (cpu == NULL) {
2795         /* No process attached */
2796         return;
2797     }
2798
2799     gdb_append_thread_id(cpu, tid);
2800
2801     switch (state) {
2802     case RUN_STATE_DEBUG:
2803         if (cpu->watchpoint_hit) {
2804             switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
2805             case BP_MEM_READ:
2806                 type = "r";
2807                 break;
2808             case BP_MEM_ACCESS:
2809                 type = "a";
2810                 break;
2811             default:
2812                 type = "";
2813                 break;
2814             }
2815             trace_gdbstub_hit_watchpoint(type, cpu_gdb_index(cpu),
2816                     (target_ulong)cpu->watchpoint_hit->vaddr);
2817             g_string_printf(buf, "T%02xthread:%s;%swatch:" TARGET_FMT_lx ";",
2818                             GDB_SIGNAL_TRAP, tid->str, type,
2819                             (target_ulong)cpu->watchpoint_hit->vaddr);
2820             cpu->watchpoint_hit = NULL;
2821             goto send_packet;
2822         } else {
2823             trace_gdbstub_hit_break();
2824         }
2825         tb_flush(cpu);
2826         ret = GDB_SIGNAL_TRAP;
2827         break;
2828     case RUN_STATE_PAUSED:
2829         trace_gdbstub_hit_paused();
2830         ret = GDB_SIGNAL_INT;
2831         break;
2832     case RUN_STATE_SHUTDOWN:
2833         trace_gdbstub_hit_shutdown();
2834         ret = GDB_SIGNAL_QUIT;
2835         break;
2836     case RUN_STATE_IO_ERROR:
2837         trace_gdbstub_hit_io_error();
2838         ret = GDB_SIGNAL_IO;
2839         break;
2840     case RUN_STATE_WATCHDOG:
2841         trace_gdbstub_hit_watchdog();
2842         ret = GDB_SIGNAL_ALRM;
2843         break;
2844     case RUN_STATE_INTERNAL_ERROR:
2845         trace_gdbstub_hit_internal_error();
2846         ret = GDB_SIGNAL_ABRT;
2847         break;
2848     case RUN_STATE_SAVE_VM:
2849     case RUN_STATE_RESTORE_VM:
2850         return;
2851     case RUN_STATE_FINISH_MIGRATE:
2852         ret = GDB_SIGNAL_XCPU;
2853         break;
2854     default:
2855         trace_gdbstub_hit_unknown(state);
2856         ret = GDB_SIGNAL_UNKNOWN;
2857         break;
2858     }
2859     gdb_set_stop_cpu(cpu);
2860     g_string_printf(buf, "T%02xthread:%s;", ret, tid->str);
2861
2862 send_packet:
2863     put_packet(buf->str);
2864
2865     /* disable single step if it was enabled */
2866     cpu_single_step(cpu, 0);
2867 }
2868 #endif
2869
2870 /* Send a gdb syscall request.
2871    This accepts limited printf-style format specifiers, specifically:
2872     %x  - target_ulong argument printed in hex.
2873     %lx - 64-bit argument printed in hex.
2874     %s  - string pointer (target_ulong) and length (int) pair.  */
2875 void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
2876 {
2877     char *p;
2878     char *p_end;
2879     target_ulong addr;
2880     uint64_t i64;
2881
2882     if (!gdbserver_state.init) {
2883         return;
2884     }
2885
2886     gdbserver_state.current_syscall_cb = cb;
2887 #ifndef CONFIG_USER_ONLY
2888     vm_stop(RUN_STATE_DEBUG);
2889 #endif
2890     p = &gdbserver_state.syscall_buf[0];
2891     p_end = &gdbserver_state.syscall_buf[sizeof(gdbserver_state.syscall_buf)];
2892     *(p++) = 'F';
2893     while (*fmt) {
2894         if (*fmt == '%') {
2895             fmt++;
2896             switch (*fmt++) {
2897             case 'x':
2898                 addr = va_arg(va, target_ulong);
2899                 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
2900                 break;
2901             case 'l':
2902                 if (*(fmt++) != 'x')
2903                     goto bad_format;
2904                 i64 = va_arg(va, uint64_t);
2905                 p += snprintf(p, p_end - p, "%" PRIx64, i64);
2906                 break;
2907             case 's':
2908                 addr = va_arg(va, target_ulong);
2909                 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
2910                               addr, va_arg(va, int));
2911                 break;
2912             default:
2913             bad_format:
2914                 error_report("gdbstub: Bad syscall format string '%s'",
2915                              fmt - 1);
2916                 break;
2917             }
2918         } else {
2919             *(p++) = *(fmt++);
2920         }
2921     }
2922     *p = 0;
2923 #ifdef CONFIG_USER_ONLY
2924     put_packet(gdbserver_state.syscall_buf);
2925     /* Return control to gdb for it to process the syscall request.
2926      * Since the protocol requires that gdb hands control back to us
2927      * using a "here are the results" F packet, we don't need to check
2928      * gdb_handlesig's return value (which is the signal to deliver if
2929      * execution was resumed via a continue packet).
2930      */
2931     gdb_handlesig(gdbserver_state.c_cpu, 0);
2932 #else
2933     /* In this case wait to send the syscall packet until notification that
2934        the CPU has stopped.  This must be done because if the packet is sent
2935        now the reply from the syscall request could be received while the CPU
2936        is still in the running state, which can cause packets to be dropped
2937        and state transition 'T' packets to be sent while the syscall is still
2938        being processed.  */
2939     qemu_cpu_kick(gdbserver_state.c_cpu);
2940 #endif
2941 }
2942
2943 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
2944 {
2945     va_list va;
2946
2947     va_start(va, fmt);
2948     gdb_do_syscallv(cb, fmt, va);
2949     va_end(va);
2950 }
2951
2952 static void gdb_read_byte(uint8_t ch)
2953 {
2954     uint8_t reply;
2955
2956 #ifndef CONFIG_USER_ONLY
2957     if (gdbserver_state.last_packet->len) {
2958         /* Waiting for a response to the last packet.  If we see the start
2959            of a new command then abandon the previous response.  */
2960         if (ch == '-') {
2961             trace_gdbstub_err_got_nack();
2962             put_buffer(gdbserver_state.last_packet->data,
2963                        gdbserver_state.last_packet->len);
2964         } else if (ch == '+') {
2965             trace_gdbstub_io_got_ack();
2966         } else {
2967             trace_gdbstub_io_got_unexpected(ch);
2968         }
2969
2970         if (ch == '+' || ch == '$') {
2971             g_byte_array_set_size(gdbserver_state.last_packet, 0);
2972         }
2973         if (ch != '$')
2974             return;
2975     }
2976     if (runstate_is_running()) {
2977         /* when the CPU is running, we cannot do anything except stop
2978            it when receiving a char */
2979         vm_stop(RUN_STATE_PAUSED);
2980     } else
2981 #endif
2982     {
2983         switch(gdbserver_state.state) {
2984         case RS_IDLE:
2985             if (ch == '$') {
2986                 /* start of command packet */
2987                 gdbserver_state.line_buf_index = 0;
2988                 gdbserver_state.line_sum = 0;
2989                 gdbserver_state.state = RS_GETLINE;
2990             } else {
2991                 trace_gdbstub_err_garbage(ch);
2992             }
2993             break;
2994         case RS_GETLINE:
2995             if (ch == '}') {
2996                 /* start escape sequence */
2997                 gdbserver_state.state = RS_GETLINE_ESC;
2998                 gdbserver_state.line_sum += ch;
2999             } else if (ch == '*') {
3000                 /* start run length encoding sequence */
3001                 gdbserver_state.state = RS_GETLINE_RLE;
3002                 gdbserver_state.line_sum += ch;
3003             } else if (ch == '#') {
3004                 /* end of command, start of checksum*/
3005                 gdbserver_state.state = RS_CHKSUM1;
3006             } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
3007                 trace_gdbstub_err_overrun();
3008                 gdbserver_state.state = RS_IDLE;
3009             } else {
3010                 /* unescaped command character */
3011                 gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch;
3012                 gdbserver_state.line_sum += ch;
3013             }
3014             break;
3015         case RS_GETLINE_ESC:
3016             if (ch == '#') {
3017                 /* unexpected end of command in escape sequence */
3018                 gdbserver_state.state = RS_CHKSUM1;
3019             } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
3020                 /* command buffer overrun */
3021                 trace_gdbstub_err_overrun();
3022                 gdbserver_state.state = RS_IDLE;
3023             } else {
3024                 /* parse escaped character and leave escape state */
3025                 gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch ^ 0x20;
3026                 gdbserver_state.line_sum += ch;
3027                 gdbserver_state.state = RS_GETLINE;
3028             }
3029             break;
3030         case RS_GETLINE_RLE:
3031             /*
3032              * Run-length encoding is explained in "Debugging with GDB /
3033              * Appendix E GDB Remote Serial Protocol / Overview".
3034              */
3035             if (ch < ' ' || ch == '#' || ch == '$' || ch > 126) {
3036                 /* invalid RLE count encoding */
3037                 trace_gdbstub_err_invalid_repeat(ch);
3038                 gdbserver_state.state = RS_GETLINE;
3039             } else {
3040                 /* decode repeat length */
3041                 int repeat = ch - ' ' + 3;
3042                 if (gdbserver_state.line_buf_index + repeat >= sizeof(gdbserver_state.line_buf) - 1) {
3043                     /* that many repeats would overrun the command buffer */
3044                     trace_gdbstub_err_overrun();
3045                     gdbserver_state.state = RS_IDLE;
3046                 } else if (gdbserver_state.line_buf_index < 1) {
3047                     /* got a repeat but we have nothing to repeat */
3048                     trace_gdbstub_err_invalid_rle();
3049                     gdbserver_state.state = RS_GETLINE;
3050                 } else {
3051                     /* repeat the last character */
3052                     memset(gdbserver_state.line_buf + gdbserver_state.line_buf_index,
3053                            gdbserver_state.line_buf[gdbserver_state.line_buf_index - 1], repeat);
3054                     gdbserver_state.line_buf_index += repeat;
3055                     gdbserver_state.line_sum += ch;
3056                     gdbserver_state.state = RS_GETLINE;
3057                 }
3058             }
3059             break;
3060         case RS_CHKSUM1:
3061             /* get high hex digit of checksum */
3062             if (!isxdigit(ch)) {
3063                 trace_gdbstub_err_checksum_invalid(ch);
3064                 gdbserver_state.state = RS_GETLINE;
3065                 break;
3066             }
3067             gdbserver_state.line_buf[gdbserver_state.line_buf_index] = '\0';
3068             gdbserver_state.line_csum = fromhex(ch) << 4;
3069             gdbserver_state.state = RS_CHKSUM2;
3070             break;
3071         case RS_CHKSUM2:
3072             /* get low hex digit of checksum */
3073             if (!isxdigit(ch)) {
3074                 trace_gdbstub_err_checksum_invalid(ch);
3075                 gdbserver_state.state = RS_GETLINE;
3076                 break;
3077             }
3078             gdbserver_state.line_csum |= fromhex(ch);
3079
3080             if (gdbserver_state.line_csum != (gdbserver_state.line_sum & 0xff)) {
3081                 trace_gdbstub_err_checksum_incorrect(gdbserver_state.line_sum, gdbserver_state.line_csum);
3082                 /* send NAK reply */
3083                 reply = '-';
3084                 put_buffer(&reply, 1);
3085                 gdbserver_state.state = RS_IDLE;
3086             } else {
3087                 /* send ACK reply */
3088                 reply = '+';
3089                 put_buffer(&reply, 1);
3090                 gdbserver_state.state = gdb_handle_packet(gdbserver_state.line_buf);
3091             }
3092             break;
3093         default:
3094             abort();
3095         }
3096     }
3097 }
3098
3099 /* Tell the remote gdb that the process has exited.  */
3100 void gdb_exit(int code)
3101 {
3102   char buf[4];
3103
3104   if (!gdbserver_state.init) {
3105       return;
3106   }
3107 #ifdef CONFIG_USER_ONLY
3108   if (gdbserver_state.socket_path) {
3109       unlink(gdbserver_state.socket_path);
3110   }
3111   if (gdbserver_state.fd < 0) {
3112       return;
3113   }
3114 #endif
3115
3116   trace_gdbstub_op_exiting((uint8_t)code);
3117
3118   snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
3119   put_packet(buf);
3120
3121 #ifndef CONFIG_USER_ONLY
3122   qemu_chr_fe_deinit(&gdbserver_state.chr, true);
3123 #endif
3124 }
3125
3126 /*
3127  * Create the process that will contain all the "orphan" CPUs (that are not
3128  * part of a CPU cluster). Note that if this process contains no CPUs, it won't
3129  * be attachable and thus will be invisible to the user.
3130  */
3131 static void create_default_process(GDBState *s)
3132 {
3133     GDBProcess *process;
3134     int max_pid = 0;
3135
3136     if (gdbserver_state.process_num) {
3137         max_pid = s->processes[s->process_num - 1].pid;
3138     }
3139
3140     s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
3141     process = &s->processes[s->process_num - 1];
3142
3143     /* We need an available PID slot for this process */
3144     assert(max_pid < UINT32_MAX);
3145
3146     process->pid = max_pid + 1;
3147     process->attached = false;
3148     process->target_xml[0] = '\0';
3149 }
3150
3151 #ifdef CONFIG_USER_ONLY
3152 int
3153 gdb_handlesig(CPUState *cpu, int sig)
3154 {
3155     char buf[256];
3156     int n;
3157
3158     if (!gdbserver_state.init || gdbserver_state.fd < 0) {
3159         return sig;
3160     }
3161
3162     /* disable single step if it was enabled */
3163     cpu_single_step(cpu, 0);
3164     tb_flush(cpu);
3165
3166     if (sig != 0) {
3167         gdb_set_stop_cpu(cpu);
3168         g_string_printf(gdbserver_state.str_buf,
3169                         "T%02xthread:", target_signal_to_gdb(sig));
3170         gdb_append_thread_id(cpu, gdbserver_state.str_buf);
3171         g_string_append_c(gdbserver_state.str_buf, ';');
3172         put_strbuf();
3173     }
3174     /* put_packet() might have detected that the peer terminated the
3175        connection.  */
3176     if (gdbserver_state.fd < 0) {
3177         return sig;
3178     }
3179
3180     sig = 0;
3181     gdbserver_state.state = RS_IDLE;
3182     gdbserver_state.running_state = 0;
3183     while (gdbserver_state.running_state == 0) {
3184         n = read(gdbserver_state.fd, buf, 256);
3185         if (n > 0) {
3186             int i;
3187
3188             for (i = 0; i < n; i++) {
3189                 gdb_read_byte(buf[i]);
3190             }
3191         } else {
3192             /* XXX: Connection closed.  Should probably wait for another
3193                connection before continuing.  */
3194             if (n == 0) {
3195                 close(gdbserver_state.fd);
3196             }
3197             gdbserver_state.fd = -1;
3198             return sig;
3199         }
3200     }
3201     sig = gdbserver_state.signal;
3202     gdbserver_state.signal = 0;
3203     return sig;
3204 }
3205
3206 /* Tell the remote gdb that the process has exited due to SIG.  */
3207 void gdb_signalled(CPUArchState *env, int sig)
3208 {
3209     char buf[4];
3210
3211     if (!gdbserver_state.init || gdbserver_state.fd < 0) {
3212         return;
3213     }
3214
3215     snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
3216     put_packet(buf);
3217 }
3218
3219 static void gdb_accept_init(int fd)
3220 {
3221     init_gdbserver_state();
3222     create_default_process(&gdbserver_state);
3223     gdbserver_state.processes[0].attached = true;
3224     gdbserver_state.c_cpu = gdb_first_attached_cpu();
3225     gdbserver_state.g_cpu = gdbserver_state.c_cpu;
3226     gdbserver_state.fd = fd;
3227     gdb_has_xml = false;
3228 }
3229
3230 static bool gdb_accept_socket(int gdb_fd)
3231 {
3232     int fd;
3233
3234     for(;;) {
3235         fd = accept(gdb_fd, NULL, NULL);
3236         if (fd < 0 && errno != EINTR) {
3237             perror("accept socket");
3238             return false;
3239         } else if (fd >= 0) {
3240             qemu_set_cloexec(fd);
3241             break;
3242         }
3243     }
3244
3245     gdb_accept_init(fd);
3246     return true;
3247 }
3248
3249 static int gdbserver_open_socket(const char *path)
3250 {
3251     struct sockaddr_un sockaddr = {};
3252     int fd, ret;
3253
3254     fd = socket(AF_UNIX, SOCK_STREAM, 0);
3255     if (fd < 0) {
3256         perror("create socket");
3257         return -1;
3258     }
3259
3260     sockaddr.sun_family = AF_UNIX;
3261     pstrcpy(sockaddr.sun_path, sizeof(sockaddr.sun_path) - 1, path);
3262     ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
3263     if (ret < 0) {
3264         perror("bind socket");
3265         close(fd);
3266         return -1;
3267     }
3268     ret = listen(fd, 1);
3269     if (ret < 0) {
3270         perror("listen socket");
3271         close(fd);
3272         return -1;
3273     }
3274
3275     return fd;
3276 }
3277
3278 static bool gdb_accept_tcp(int gdb_fd)
3279 {
3280     struct sockaddr_in sockaddr = {};
3281     socklen_t len;
3282     int fd;
3283
3284     for(;;) {
3285         len = sizeof(sockaddr);
3286         fd = accept(gdb_fd, (struct sockaddr *)&sockaddr, &len);
3287         if (fd < 0 && errno != EINTR) {
3288             perror("accept");
3289             return false;
3290         } else if (fd >= 0) {
3291             qemu_set_cloexec(fd);
3292             break;
3293         }
3294     }
3295
3296     /* set short latency */
3297     if (socket_set_nodelay(fd)) {
3298         perror("setsockopt");
3299         close(fd);
3300         return false;
3301     }
3302
3303     gdb_accept_init(fd);
3304     return true;
3305 }
3306
3307 static int gdbserver_open_port(int port)
3308 {
3309     struct sockaddr_in sockaddr;
3310     int fd, ret;
3311
3312     fd = socket(PF_INET, SOCK_STREAM, 0);
3313     if (fd < 0) {
3314         perror("socket");
3315         return -1;
3316     }
3317     qemu_set_cloexec(fd);
3318
3319     socket_set_fast_reuse(fd);
3320
3321     sockaddr.sin_family = AF_INET;
3322     sockaddr.sin_port = htons(port);
3323     sockaddr.sin_addr.s_addr = 0;
3324     ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
3325     if (ret < 0) {
3326         perror("bind");
3327         close(fd);
3328         return -1;
3329     }
3330     ret = listen(fd, 1);
3331     if (ret < 0) {
3332         perror("listen");
3333         close(fd);
3334         return -1;
3335     }
3336
3337     return fd;
3338 }
3339
3340 int gdbserver_start(const char *port_or_path)
3341 {
3342     int port = g_ascii_strtoull(port_or_path, NULL, 10);
3343     int gdb_fd;
3344
3345     if (port > 0) {
3346         gdb_fd = gdbserver_open_port(port);
3347     } else {
3348         gdb_fd = gdbserver_open_socket(port_or_path);
3349     }
3350
3351     if (gdb_fd < 0) {
3352         return -1;
3353     }
3354
3355     if (port > 0 && gdb_accept_tcp(gdb_fd)) {
3356         return 0;
3357     } else if (gdb_accept_socket(gdb_fd)) {
3358         gdbserver_state.socket_path = g_strdup(port_or_path);
3359         return 0;
3360     }
3361
3362     /* gone wrong */
3363     close(gdb_fd);
3364     return -1;
3365 }
3366
3367 /* Disable gdb stub for child processes.  */
3368 void gdbserver_fork(CPUState *cpu)
3369 {
3370     if (!gdbserver_state.init || gdbserver_state.fd < 0) {
3371         return;
3372     }
3373     close(gdbserver_state.fd);
3374     gdbserver_state.fd = -1;
3375     cpu_breakpoint_remove_all(cpu, BP_GDB);
3376     cpu_watchpoint_remove_all(cpu, BP_GDB);
3377 }
3378 #else
3379 static int gdb_chr_can_receive(void *opaque)
3380 {
3381   /* We can handle an arbitrarily large amount of data.
3382    Pick the maximum packet size, which is as good as anything.  */
3383   return MAX_PACKET_LENGTH;
3384 }
3385
3386 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
3387 {
3388     int i;
3389
3390     for (i = 0; i < size; i++) {
3391         gdb_read_byte(buf[i]);
3392     }
3393 }
3394
3395 static void gdb_chr_event(void *opaque, QEMUChrEvent event)
3396 {
3397     int i;
3398     GDBState *s = (GDBState *) opaque;
3399
3400     switch (event) {
3401     case CHR_EVENT_OPENED:
3402         /* Start with first process attached, others detached */
3403         for (i = 0; i < s->process_num; i++) {
3404             s->processes[i].attached = !i;
3405         }
3406
3407         s->c_cpu = gdb_first_attached_cpu();
3408         s->g_cpu = s->c_cpu;
3409
3410         vm_stop(RUN_STATE_PAUSED);
3411         replay_gdb_attached();
3412         gdb_has_xml = false;
3413         break;
3414     default:
3415         break;
3416     }
3417 }
3418
3419 static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
3420 {
3421     g_autoptr(GString) hex_buf = g_string_new("O");
3422     memtohex(hex_buf, buf, len);
3423     put_packet(hex_buf->str);
3424     return len;
3425 }
3426
3427 #ifndef _WIN32
3428 static void gdb_sigterm_handler(int signal)
3429 {
3430     if (runstate_is_running()) {
3431         vm_stop(RUN_STATE_PAUSED);
3432     }
3433 }
3434 #endif
3435
3436 static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
3437                              bool *be_opened, Error **errp)
3438 {
3439     *be_opened = false;
3440 }
3441
3442 static void char_gdb_class_init(ObjectClass *oc, void *data)
3443 {
3444     ChardevClass *cc = CHARDEV_CLASS(oc);
3445
3446     cc->internal = true;
3447     cc->open = gdb_monitor_open;
3448     cc->chr_write = gdb_monitor_write;
3449 }
3450
3451 #define TYPE_CHARDEV_GDB "chardev-gdb"
3452
3453 static const TypeInfo char_gdb_type_info = {
3454     .name = TYPE_CHARDEV_GDB,
3455     .parent = TYPE_CHARDEV,
3456     .class_init = char_gdb_class_init,
3457 };
3458
3459 static int find_cpu_clusters(Object *child, void *opaque)
3460 {
3461     if (object_dynamic_cast(child, TYPE_CPU_CLUSTER)) {
3462         GDBState *s = (GDBState *) opaque;
3463         CPUClusterState *cluster = CPU_CLUSTER(child);
3464         GDBProcess *process;
3465
3466         s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
3467
3468         process = &s->processes[s->process_num - 1];
3469
3470         /*
3471          * GDB process IDs -1 and 0 are reserved. To avoid subtle errors at
3472          * runtime, we enforce here that the machine does not use a cluster ID
3473          * that would lead to PID 0.
3474          */
3475         assert(cluster->cluster_id != UINT32_MAX);
3476         process->pid = cluster->cluster_id + 1;
3477         process->attached = false;
3478         process->target_xml[0] = '\0';
3479
3480         return 0;
3481     }
3482
3483     return object_child_foreach(child, find_cpu_clusters, opaque);
3484 }
3485
3486 static int pid_order(const void *a, const void *b)
3487 {
3488     GDBProcess *pa = (GDBProcess *) a;
3489     GDBProcess *pb = (GDBProcess *) b;
3490
3491     if (pa->pid < pb->pid) {
3492         return -1;
3493     } else if (pa->pid > pb->pid) {
3494         return 1;
3495     } else {
3496         return 0;
3497     }
3498 }
3499
3500 static void create_processes(GDBState *s)
3501 {
3502     object_child_foreach(object_get_root(), find_cpu_clusters, s);
3503
3504     if (gdbserver_state.processes) {
3505         /* Sort by PID */
3506         qsort(gdbserver_state.processes, gdbserver_state.process_num, sizeof(gdbserver_state.processes[0]), pid_order);
3507     }
3508
3509     create_default_process(s);
3510 }
3511
3512 int gdbserver_start(const char *device)
3513 {
3514     trace_gdbstub_op_start(device);
3515
3516     char gdbstub_device_name[128];
3517     Chardev *chr = NULL;
3518     Chardev *mon_chr;
3519
3520     if (!first_cpu) {
3521         error_report("gdbstub: meaningless to attach gdb to a "
3522                      "machine without any CPU.");
3523         return -1;
3524     }
3525
3526     if (kvm_enabled() && !kvm_supports_guest_debug()) {
3527         error_report("gdbstub: KVM doesn't support guest debugging");
3528         return -1;
3529     }
3530
3531     if (!device)
3532         return -1;
3533     if (strcmp(device, "none") != 0) {
3534         if (strstart(device, "tcp:", NULL)) {
3535             /* enforce required TCP attributes */
3536             snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
3537                      "%s,wait=off,nodelay=on,server=on", device);
3538             device = gdbstub_device_name;
3539         }
3540 #ifndef _WIN32
3541         else if (strcmp(device, "stdio") == 0) {
3542             struct sigaction act;
3543
3544             memset(&act, 0, sizeof(act));
3545             act.sa_handler = gdb_sigterm_handler;
3546             sigaction(SIGINT, &act, NULL);
3547         }
3548 #endif
3549         /*
3550          * FIXME: it's a bit weird to allow using a mux chardev here
3551          * and implicitly setup a monitor. We may want to break this.
3552          */
3553         chr = qemu_chr_new_noreplay("gdb", device, true, NULL);
3554         if (!chr)
3555             return -1;
3556     }
3557
3558     if (!gdbserver_state.init) {
3559         init_gdbserver_state();
3560
3561         qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
3562
3563         /* Initialize a monitor terminal for gdb */
3564         mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
3565                                    NULL, NULL, &error_abort);
3566         monitor_init_hmp(mon_chr, false, &error_abort);
3567     } else {
3568         qemu_chr_fe_deinit(&gdbserver_state.chr, true);
3569         mon_chr = gdbserver_state.mon_chr;
3570         reset_gdbserver_state();
3571     }
3572
3573     create_processes(&gdbserver_state);
3574
3575     if (chr) {
3576         qemu_chr_fe_init(&gdbserver_state.chr, chr, &error_abort);
3577         qemu_chr_fe_set_handlers(&gdbserver_state.chr, gdb_chr_can_receive,
3578                                  gdb_chr_receive, gdb_chr_event,
3579                                  NULL, &gdbserver_state, NULL, true);
3580     }
3581     gdbserver_state.state = chr ? RS_IDLE : RS_INACTIVE;
3582     gdbserver_state.mon_chr = mon_chr;
3583     gdbserver_state.current_syscall_cb = NULL;
3584
3585     return 0;
3586 }
3587
3588 static void register_types(void)
3589 {
3590     type_register_static(&char_gdb_type_info);
3591 }
3592
3593 type_init(register_types);
3594 #endif