cpu: Move watchpoint fields from CPU_COMMON to CPUState
[sdk/emulator/qemu.git] / gdbstub.c
1 /*
2  * gdb server stub
3  *
4  * Copyright (c) 2003-2005 Fabrice Bellard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19 #include "config.h"
20 #include "qemu-common.h"
21 #ifdef CONFIG_USER_ONLY
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <stdarg.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29
30 #include "qemu.h"
31 #else
32 #include "monitor/monitor.h"
33 #include "sysemu/char.h"
34 #include "sysemu/sysemu.h"
35 #include "exec/gdbstub.h"
36 #endif
37
38 #define MAX_PACKET_LENGTH 4096
39
40 #include "cpu.h"
41 #include "qemu/sockets.h"
42 #include "sysemu/kvm.h"
43
44 static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
45                                          uint8_t *buf, int len, bool is_write)
46 {
47     CPUClass *cc = CPU_GET_CLASS(cpu);
48
49     if (cc->memory_rw_debug) {
50         return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
51     }
52     return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
53 }
54
55 enum {
56     GDB_SIGNAL_0 = 0,
57     GDB_SIGNAL_INT = 2,
58     GDB_SIGNAL_QUIT = 3,
59     GDB_SIGNAL_TRAP = 5,
60     GDB_SIGNAL_ABRT = 6,
61     GDB_SIGNAL_ALRM = 14,
62     GDB_SIGNAL_IO = 23,
63     GDB_SIGNAL_XCPU = 24,
64     GDB_SIGNAL_UNKNOWN = 143
65 };
66
67 #ifdef CONFIG_USER_ONLY
68
69 /* Map target signal numbers to GDB protocol signal numbers and vice
70  * versa.  For user emulation's currently supported systems, we can
71  * assume most signals are defined.
72  */
73
74 static int gdb_signal_table[] = {
75     0,
76     TARGET_SIGHUP,
77     TARGET_SIGINT,
78     TARGET_SIGQUIT,
79     TARGET_SIGILL,
80     TARGET_SIGTRAP,
81     TARGET_SIGABRT,
82     -1, /* SIGEMT */
83     TARGET_SIGFPE,
84     TARGET_SIGKILL,
85     TARGET_SIGBUS,
86     TARGET_SIGSEGV,
87     TARGET_SIGSYS,
88     TARGET_SIGPIPE,
89     TARGET_SIGALRM,
90     TARGET_SIGTERM,
91     TARGET_SIGURG,
92     TARGET_SIGSTOP,
93     TARGET_SIGTSTP,
94     TARGET_SIGCONT,
95     TARGET_SIGCHLD,
96     TARGET_SIGTTIN,
97     TARGET_SIGTTOU,
98     TARGET_SIGIO,
99     TARGET_SIGXCPU,
100     TARGET_SIGXFSZ,
101     TARGET_SIGVTALRM,
102     TARGET_SIGPROF,
103     TARGET_SIGWINCH,
104     -1, /* SIGLOST */
105     TARGET_SIGUSR1,
106     TARGET_SIGUSR2,
107 #ifdef TARGET_SIGPWR
108     TARGET_SIGPWR,
109 #else
110     -1,
111 #endif
112     -1, /* SIGPOLL */
113     -1,
114     -1,
115     -1,
116     -1,
117     -1,
118     -1,
119     -1,
120     -1,
121     -1,
122     -1,
123     -1,
124 #ifdef __SIGRTMIN
125     __SIGRTMIN + 1,
126     __SIGRTMIN + 2,
127     __SIGRTMIN + 3,
128     __SIGRTMIN + 4,
129     __SIGRTMIN + 5,
130     __SIGRTMIN + 6,
131     __SIGRTMIN + 7,
132     __SIGRTMIN + 8,
133     __SIGRTMIN + 9,
134     __SIGRTMIN + 10,
135     __SIGRTMIN + 11,
136     __SIGRTMIN + 12,
137     __SIGRTMIN + 13,
138     __SIGRTMIN + 14,
139     __SIGRTMIN + 15,
140     __SIGRTMIN + 16,
141     __SIGRTMIN + 17,
142     __SIGRTMIN + 18,
143     __SIGRTMIN + 19,
144     __SIGRTMIN + 20,
145     __SIGRTMIN + 21,
146     __SIGRTMIN + 22,
147     __SIGRTMIN + 23,
148     __SIGRTMIN + 24,
149     __SIGRTMIN + 25,
150     __SIGRTMIN + 26,
151     __SIGRTMIN + 27,
152     __SIGRTMIN + 28,
153     __SIGRTMIN + 29,
154     __SIGRTMIN + 30,
155     __SIGRTMIN + 31,
156     -1, /* SIGCANCEL */
157     __SIGRTMIN,
158     __SIGRTMIN + 32,
159     __SIGRTMIN + 33,
160     __SIGRTMIN + 34,
161     __SIGRTMIN + 35,
162     __SIGRTMIN + 36,
163     __SIGRTMIN + 37,
164     __SIGRTMIN + 38,
165     __SIGRTMIN + 39,
166     __SIGRTMIN + 40,
167     __SIGRTMIN + 41,
168     __SIGRTMIN + 42,
169     __SIGRTMIN + 43,
170     __SIGRTMIN + 44,
171     __SIGRTMIN + 45,
172     __SIGRTMIN + 46,
173     __SIGRTMIN + 47,
174     __SIGRTMIN + 48,
175     __SIGRTMIN + 49,
176     __SIGRTMIN + 50,
177     __SIGRTMIN + 51,
178     __SIGRTMIN + 52,
179     __SIGRTMIN + 53,
180     __SIGRTMIN + 54,
181     __SIGRTMIN + 55,
182     __SIGRTMIN + 56,
183     __SIGRTMIN + 57,
184     __SIGRTMIN + 58,
185     __SIGRTMIN + 59,
186     __SIGRTMIN + 60,
187     __SIGRTMIN + 61,
188     __SIGRTMIN + 62,
189     __SIGRTMIN + 63,
190     __SIGRTMIN + 64,
191     __SIGRTMIN + 65,
192     __SIGRTMIN + 66,
193     __SIGRTMIN + 67,
194     __SIGRTMIN + 68,
195     __SIGRTMIN + 69,
196     __SIGRTMIN + 70,
197     __SIGRTMIN + 71,
198     __SIGRTMIN + 72,
199     __SIGRTMIN + 73,
200     __SIGRTMIN + 74,
201     __SIGRTMIN + 75,
202     __SIGRTMIN + 76,
203     __SIGRTMIN + 77,
204     __SIGRTMIN + 78,
205     __SIGRTMIN + 79,
206     __SIGRTMIN + 80,
207     __SIGRTMIN + 81,
208     __SIGRTMIN + 82,
209     __SIGRTMIN + 83,
210     __SIGRTMIN + 84,
211     __SIGRTMIN + 85,
212     __SIGRTMIN + 86,
213     __SIGRTMIN + 87,
214     __SIGRTMIN + 88,
215     __SIGRTMIN + 89,
216     __SIGRTMIN + 90,
217     __SIGRTMIN + 91,
218     __SIGRTMIN + 92,
219     __SIGRTMIN + 93,
220     __SIGRTMIN + 94,
221     __SIGRTMIN + 95,
222     -1, /* SIGINFO */
223     -1, /* UNKNOWN */
224     -1, /* DEFAULT */
225     -1,
226     -1,
227     -1,
228     -1,
229     -1,
230     -1
231 #endif
232 };
233 #else
234 /* In system mode we only need SIGINT and SIGTRAP; other signals
235    are not yet supported.  */
236
237 enum {
238     TARGET_SIGINT = 2,
239     TARGET_SIGTRAP = 5
240 };
241
242 static int gdb_signal_table[] = {
243     -1,
244     -1,
245     TARGET_SIGINT,
246     -1,
247     -1,
248     TARGET_SIGTRAP
249 };
250 #endif
251
252 #ifdef CONFIG_USER_ONLY
253 static int target_signal_to_gdb (int sig)
254 {
255     int i;
256     for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
257         if (gdb_signal_table[i] == sig)
258             return i;
259     return GDB_SIGNAL_UNKNOWN;
260 }
261 #endif
262
263 static int gdb_signal_to_target (int sig)
264 {
265     if (sig < ARRAY_SIZE (gdb_signal_table))
266         return gdb_signal_table[sig];
267     else
268         return -1;
269 }
270
271 //#define DEBUG_GDB
272
273 typedef struct GDBRegisterState {
274     int base_reg;
275     int num_regs;
276     gdb_reg_cb get_reg;
277     gdb_reg_cb set_reg;
278     const char *xml;
279     struct GDBRegisterState *next;
280 } GDBRegisterState;
281
282 enum RSState {
283     RS_INACTIVE,
284     RS_IDLE,
285     RS_GETLINE,
286     RS_CHKSUM1,
287     RS_CHKSUM2,
288 };
289 typedef struct GDBState {
290     CPUState *c_cpu; /* current CPU for step/continue ops */
291     CPUState *g_cpu; /* current CPU for other ops */
292     CPUState *query_cpu; /* for q{f|s}ThreadInfo */
293     enum RSState state; /* parsing state */
294     char line_buf[MAX_PACKET_LENGTH];
295     int line_buf_index;
296     int line_csum;
297     uint8_t last_packet[MAX_PACKET_LENGTH + 4];
298     int last_packet_len;
299     int signal;
300 #ifdef CONFIG_USER_ONLY
301     int fd;
302     int running_state;
303 #else
304     CharDriverState *chr;
305     CharDriverState *mon_chr;
306 #endif
307     char syscall_buf[256];
308     gdb_syscall_complete_cb current_syscall_cb;
309 } GDBState;
310
311 /* By default use no IRQs and no timers while single stepping so as to
312  * make single stepping like an ICE HW step.
313  */
314 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
315
316 static GDBState *gdbserver_state;
317
318 bool gdb_has_xml;
319
320 #ifdef CONFIG_USER_ONLY
321 /* XXX: This is not thread safe.  Do we care?  */
322 static int gdbserver_fd = -1;
323
324 static int get_char(GDBState *s)
325 {
326     uint8_t ch;
327     int ret;
328
329     for(;;) {
330         ret = qemu_recv(s->fd, &ch, 1, 0);
331         if (ret < 0) {
332             if (errno == ECONNRESET)
333                 s->fd = -1;
334             if (errno != EINTR && errno != EAGAIN)
335                 return -1;
336         } else if (ret == 0) {
337             close(s->fd);
338             s->fd = -1;
339             return -1;
340         } else {
341             break;
342         }
343     }
344     return ch;
345 }
346 #endif
347
348 static enum {
349     GDB_SYS_UNKNOWN,
350     GDB_SYS_ENABLED,
351     GDB_SYS_DISABLED,
352 } gdb_syscall_mode;
353
354 /* If gdb is connected when the first semihosting syscall occurs then use
355    remote gdb syscalls.  Otherwise use native file IO.  */
356 int use_gdb_syscalls(void)
357 {
358     if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
359         gdb_syscall_mode = (gdbserver_state ? GDB_SYS_ENABLED
360                                             : GDB_SYS_DISABLED);
361     }
362     return gdb_syscall_mode == GDB_SYS_ENABLED;
363 }
364
365 /* Resume execution.  */
366 static inline void gdb_continue(GDBState *s)
367 {
368 #ifdef CONFIG_USER_ONLY
369     s->running_state = 1;
370 #else
371     if (!runstate_needs_reset()) {
372         vm_start();
373     }
374 #endif
375 }
376
377 static void put_buffer(GDBState *s, const uint8_t *buf, int len)
378 {
379 #ifdef CONFIG_USER_ONLY
380     int ret;
381
382     while (len > 0) {
383         ret = send(s->fd, buf, len, 0);
384         if (ret < 0) {
385             if (errno != EINTR && errno != EAGAIN)
386                 return;
387         } else {
388             buf += ret;
389             len -= ret;
390         }
391     }
392 #else
393     qemu_chr_fe_write(s->chr, buf, len);
394 #endif
395 }
396
397 static inline int fromhex(int v)
398 {
399     if (v >= '0' && v <= '9')
400         return v - '0';
401     else if (v >= 'A' && v <= 'F')
402         return v - 'A' + 10;
403     else if (v >= 'a' && v <= 'f')
404         return v - 'a' + 10;
405     else
406         return 0;
407 }
408
409 static inline int tohex(int v)
410 {
411     if (v < 10)
412         return v + '0';
413     else
414         return v - 10 + 'a';
415 }
416
417 static void memtohex(char *buf, const uint8_t *mem, int len)
418 {
419     int i, c;
420     char *q;
421     q = buf;
422     for(i = 0; i < len; i++) {
423         c = mem[i];
424         *q++ = tohex(c >> 4);
425         *q++ = tohex(c & 0xf);
426     }
427     *q = '\0';
428 }
429
430 static void hextomem(uint8_t *mem, const char *buf, int len)
431 {
432     int i;
433
434     for(i = 0; i < len; i++) {
435         mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
436         buf += 2;
437     }
438 }
439
440 /* return -1 if error, 0 if OK */
441 static int put_packet_binary(GDBState *s, const char *buf, int len)
442 {
443     int csum, i;
444     uint8_t *p;
445
446     for(;;) {
447         p = s->last_packet;
448         *(p++) = '$';
449         memcpy(p, buf, len);
450         p += len;
451         csum = 0;
452         for(i = 0; i < len; i++) {
453             csum += buf[i];
454         }
455         *(p++) = '#';
456         *(p++) = tohex((csum >> 4) & 0xf);
457         *(p++) = tohex((csum) & 0xf);
458
459         s->last_packet_len = p - s->last_packet;
460         put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
461
462 #ifdef CONFIG_USER_ONLY
463         i = get_char(s);
464         if (i < 0)
465             return -1;
466         if (i == '+')
467             break;
468 #else
469         break;
470 #endif
471     }
472     return 0;
473 }
474
475 /* return -1 if error, 0 if OK */
476 static int put_packet(GDBState *s, const char *buf)
477 {
478 #ifdef DEBUG_GDB
479     printf("reply='%s'\n", buf);
480 #endif
481
482     return put_packet_binary(s, buf, strlen(buf));
483 }
484
485 /* Encode data using the encoding for 'x' packets.  */
486 static int memtox(char *buf, const char *mem, int len)
487 {
488     char *p = buf;
489     char c;
490
491     while (len--) {
492         c = *(mem++);
493         switch (c) {
494         case '#': case '$': case '*': case '}':
495             *(p++) = '}';
496             *(p++) = c ^ 0x20;
497             break;
498         default:
499             *(p++) = c;
500             break;
501         }
502     }
503     return p - buf;
504 }
505
506 static const char *get_feature_xml(const char *p, const char **newp,
507                                    CPUClass *cc)
508 {
509     size_t len;
510     int i;
511     const char *name;
512     static char target_xml[1024];
513
514     len = 0;
515     while (p[len] && p[len] != ':')
516         len++;
517     *newp = p + len;
518
519     name = NULL;
520     if (strncmp(p, "target.xml", len) == 0) {
521         /* Generate the XML description for this CPU.  */
522         if (!target_xml[0]) {
523             GDBRegisterState *r;
524             CPUState *cpu = first_cpu;
525
526             snprintf(target_xml, sizeof(target_xml),
527                      "<?xml version=\"1.0\"?>"
528                      "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
529                      "<target>"
530                      "<xi:include href=\"%s\"/>",
531                      cc->gdb_core_xml_file);
532
533             for (r = cpu->gdb_regs; r; r = r->next) {
534                 pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
535                 pstrcat(target_xml, sizeof(target_xml), r->xml);
536                 pstrcat(target_xml, sizeof(target_xml), "\"/>");
537             }
538             pstrcat(target_xml, sizeof(target_xml), "</target>");
539         }
540         return target_xml;
541     }
542     for (i = 0; ; i++) {
543         name = xml_builtin[i][0];
544         if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
545             break;
546     }
547     return name ? xml_builtin[i][1] : NULL;
548 }
549
550 static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
551 {
552     CPUClass *cc = CPU_GET_CLASS(cpu);
553     CPUArchState *env = cpu->env_ptr;
554     GDBRegisterState *r;
555
556     if (reg < cc->gdb_num_core_regs) {
557         return cc->gdb_read_register(cpu, mem_buf, reg);
558     }
559
560     for (r = cpu->gdb_regs; r; r = r->next) {
561         if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
562             return r->get_reg(env, mem_buf, reg - r->base_reg);
563         }
564     }
565     return 0;
566 }
567
568 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
569 {
570     CPUClass *cc = CPU_GET_CLASS(cpu);
571     CPUArchState *env = cpu->env_ptr;
572     GDBRegisterState *r;
573
574     if (reg < cc->gdb_num_core_regs) {
575         return cc->gdb_write_register(cpu, mem_buf, reg);
576     }
577
578     for (r = cpu->gdb_regs; r; r = r->next) {
579         if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
580             return r->set_reg(env, mem_buf, reg - r->base_reg);
581         }
582     }
583     return 0;
584 }
585
586 /* Register a supplemental set of CPU registers.  If g_pos is nonzero it
587    specifies the first register number and these registers are included in
588    a standard "g" packet.  Direction is relative to gdb, i.e. get_reg is
589    gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
590  */
591
592 void gdb_register_coprocessor(CPUState *cpu,
593                               gdb_reg_cb get_reg, gdb_reg_cb set_reg,
594                               int num_regs, const char *xml, int g_pos)
595 {
596     GDBRegisterState *s;
597     GDBRegisterState **p;
598
599     p = &cpu->gdb_regs;
600     while (*p) {
601         /* Check for duplicates.  */
602         if (strcmp((*p)->xml, xml) == 0)
603             return;
604         p = &(*p)->next;
605     }
606
607     s = g_new0(GDBRegisterState, 1);
608     s->base_reg = cpu->gdb_num_regs;
609     s->num_regs = num_regs;
610     s->get_reg = get_reg;
611     s->set_reg = set_reg;
612     s->xml = xml;
613
614     /* Add to end of list.  */
615     cpu->gdb_num_regs += num_regs;
616     *p = s;
617     if (g_pos) {
618         if (g_pos != s->base_reg) {
619             fprintf(stderr, "Error: Bad gdb register numbering for '%s'\n"
620                     "Expected %d got %d\n", xml, g_pos, s->base_reg);
621         } else {
622             cpu->gdb_num_g_regs = cpu->gdb_num_regs;
623         }
624     }
625 }
626
627 #ifndef CONFIG_USER_ONLY
628 static const int xlat_gdb_type[] = {
629     [GDB_WATCHPOINT_WRITE]  = BP_GDB | BP_MEM_WRITE,
630     [GDB_WATCHPOINT_READ]   = BP_GDB | BP_MEM_READ,
631     [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
632 };
633 #endif
634
635 static int gdb_breakpoint_insert(target_ulong addr, target_ulong len, int type)
636 {
637     CPUState *cpu;
638     CPUArchState *env;
639     int err = 0;
640
641     if (kvm_enabled()) {
642         return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
643     }
644
645     switch (type) {
646     case GDB_BREAKPOINT_SW:
647     case GDB_BREAKPOINT_HW:
648         CPU_FOREACH(cpu) {
649             env = cpu->env_ptr;
650             err = cpu_breakpoint_insert(env, addr, BP_GDB, NULL);
651             if (err)
652                 break;
653         }
654         return err;
655 #ifndef CONFIG_USER_ONLY
656     case GDB_WATCHPOINT_WRITE:
657     case GDB_WATCHPOINT_READ:
658     case GDB_WATCHPOINT_ACCESS:
659         CPU_FOREACH(cpu) {
660             env = cpu->env_ptr;
661             err = cpu_watchpoint_insert(env, addr, len, xlat_gdb_type[type],
662                                         NULL);
663             if (err)
664                 break;
665         }
666         return err;
667 #endif
668     default:
669         return -ENOSYS;
670     }
671 }
672
673 static int gdb_breakpoint_remove(target_ulong addr, target_ulong len, int type)
674 {
675     CPUState *cpu;
676     CPUArchState *env;
677     int err = 0;
678
679     if (kvm_enabled()) {
680         return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
681     }
682
683     switch (type) {
684     case GDB_BREAKPOINT_SW:
685     case GDB_BREAKPOINT_HW:
686         CPU_FOREACH(cpu) {
687             env = cpu->env_ptr;
688             err = cpu_breakpoint_remove(env, addr, BP_GDB);
689             if (err)
690                 break;
691         }
692         return err;
693 #ifndef CONFIG_USER_ONLY
694     case GDB_WATCHPOINT_WRITE:
695     case GDB_WATCHPOINT_READ:
696     case GDB_WATCHPOINT_ACCESS:
697         CPU_FOREACH(cpu) {
698             env = cpu->env_ptr;
699             err = cpu_watchpoint_remove(env, addr, len, xlat_gdb_type[type]);
700             if (err)
701                 break;
702         }
703         return err;
704 #endif
705     default:
706         return -ENOSYS;
707     }
708 }
709
710 static void gdb_breakpoint_remove_all(void)
711 {
712     CPUState *cpu;
713     CPUArchState *env;
714
715     if (kvm_enabled()) {
716         kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
717         return;
718     }
719
720     CPU_FOREACH(cpu) {
721         env = cpu->env_ptr;
722         cpu_breakpoint_remove_all(env, BP_GDB);
723 #ifndef CONFIG_USER_ONLY
724         cpu_watchpoint_remove_all(env, BP_GDB);
725 #endif
726     }
727 }
728
729 static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
730 {
731     CPUState *cpu = s->c_cpu;
732     CPUClass *cc = CPU_GET_CLASS(cpu);
733
734     cpu_synchronize_state(cpu);
735     if (cc->set_pc) {
736         cc->set_pc(cpu, pc);
737     }
738 }
739
740 static CPUState *find_cpu(uint32_t thread_id)
741 {
742     CPUState *cpu;
743
744     CPU_FOREACH(cpu) {
745         if (cpu_index(cpu) == thread_id) {
746             return cpu;
747         }
748     }
749
750     return NULL;
751 }
752
753 static int gdb_handle_packet(GDBState *s, const char *line_buf)
754 {
755     CPUState *cpu;
756     CPUClass *cc;
757     const char *p;
758     uint32_t thread;
759     int ch, reg_size, type, res;
760     char buf[MAX_PACKET_LENGTH];
761     uint8_t mem_buf[MAX_PACKET_LENGTH];
762     uint8_t *registers;
763     target_ulong addr, len;
764
765 #ifdef DEBUG_GDB
766     printf("command='%s'\n", line_buf);
767 #endif
768     p = line_buf;
769     ch = *p++;
770     switch(ch) {
771     case '?':
772         /* TODO: Make this return the correct value for user-mode.  */
773         snprintf(buf, sizeof(buf), "T%02xthread:%02x;", GDB_SIGNAL_TRAP,
774                  cpu_index(s->c_cpu));
775         put_packet(s, buf);
776         /* Remove all the breakpoints when this query is issued,
777          * because gdb is doing and initial connect and the state
778          * should be cleaned up.
779          */
780         gdb_breakpoint_remove_all();
781         break;
782     case 'c':
783         if (*p != '\0') {
784             addr = strtoull(p, (char **)&p, 16);
785             gdb_set_cpu_pc(s, addr);
786         }
787         s->signal = 0;
788         gdb_continue(s);
789         return RS_IDLE;
790     case 'C':
791         s->signal = gdb_signal_to_target (strtoul(p, (char **)&p, 16));
792         if (s->signal == -1)
793             s->signal = 0;
794         gdb_continue(s);
795         return RS_IDLE;
796     case 'v':
797         if (strncmp(p, "Cont", 4) == 0) {
798             int res_signal, res_thread;
799
800             p += 4;
801             if (*p == '?') {
802                 put_packet(s, "vCont;c;C;s;S");
803                 break;
804             }
805             res = 0;
806             res_signal = 0;
807             res_thread = 0;
808             while (*p) {
809                 int action, signal;
810
811                 if (*p++ != ';') {
812                     res = 0;
813                     break;
814                 }
815                 action = *p++;
816                 signal = 0;
817                 if (action == 'C' || action == 'S') {
818                     signal = strtoul(p, (char **)&p, 16);
819                 } else if (action != 'c' && action != 's') {
820                     res = 0;
821                     break;
822                 }
823                 thread = 0;
824                 if (*p == ':') {
825                     thread = strtoull(p+1, (char **)&p, 16);
826                 }
827                 action = tolower(action);
828                 if (res == 0 || (res == 'c' && action == 's')) {
829                     res = action;
830                     res_signal = signal;
831                     res_thread = thread;
832                 }
833             }
834             if (res) {
835                 if (res_thread != -1 && res_thread != 0) {
836                     cpu = find_cpu(res_thread);
837                     if (cpu == NULL) {
838                         put_packet(s, "E22");
839                         break;
840                     }
841                     s->c_cpu = cpu;
842                 }
843                 if (res == 's') {
844                     cpu_single_step(s->c_cpu, sstep_flags);
845                 }
846                 s->signal = res_signal;
847                 gdb_continue(s);
848                 return RS_IDLE;
849             }
850             break;
851         } else {
852             goto unknown_command;
853         }
854     case 'k':
855 #ifdef CONFIG_USER_ONLY
856         /* Kill the target */
857         fprintf(stderr, "\nQEMU: Terminated via GDBstub\n");
858         exit(0);
859 #endif
860     case 'D':
861         /* Detach packet */
862         gdb_breakpoint_remove_all();
863         gdb_syscall_mode = GDB_SYS_DISABLED;
864         gdb_continue(s);
865         put_packet(s, "OK");
866         break;
867     case 's':
868         if (*p != '\0') {
869             addr = strtoull(p, (char **)&p, 16);
870             gdb_set_cpu_pc(s, addr);
871         }
872         cpu_single_step(s->c_cpu, sstep_flags);
873         gdb_continue(s);
874         return RS_IDLE;
875     case 'F':
876         {
877             target_ulong ret;
878             target_ulong err;
879
880             ret = strtoull(p, (char **)&p, 16);
881             if (*p == ',') {
882                 p++;
883                 err = strtoull(p, (char **)&p, 16);
884             } else {
885                 err = 0;
886             }
887             if (*p == ',')
888                 p++;
889             type = *p;
890             if (s->current_syscall_cb) {
891                 s->current_syscall_cb(s->c_cpu, ret, err);
892                 s->current_syscall_cb = NULL;
893             }
894             if (type == 'C') {
895                 put_packet(s, "T02");
896             } else {
897                 gdb_continue(s);
898             }
899         }
900         break;
901     case 'g':
902         cpu_synchronize_state(s->g_cpu);
903         len = 0;
904         for (addr = 0; addr < s->g_cpu->gdb_num_g_regs; addr++) {
905             reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);
906             len += reg_size;
907         }
908         memtohex(buf, mem_buf, len);
909         put_packet(s, buf);
910         break;
911     case 'G':
912         cpu_synchronize_state(s->g_cpu);
913         registers = mem_buf;
914         len = strlen(p) / 2;
915         hextomem((uint8_t *)registers, p, len);
916         for (addr = 0; addr < s->g_cpu->gdb_num_g_regs && len > 0; addr++) {
917             reg_size = gdb_write_register(s->g_cpu, registers, addr);
918             len -= reg_size;
919             registers += reg_size;
920         }
921         put_packet(s, "OK");
922         break;
923     case 'm':
924         addr = strtoull(p, (char **)&p, 16);
925         if (*p == ',')
926             p++;
927         len = strtoull(p, NULL, 16);
928         if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len, false) != 0) {
929             put_packet (s, "E14");
930         } else {
931             memtohex(buf, mem_buf, len);
932             put_packet(s, buf);
933         }
934         break;
935     case 'M':
936         addr = strtoull(p, (char **)&p, 16);
937         if (*p == ',')
938             p++;
939         len = strtoull(p, (char **)&p, 16);
940         if (*p == ':')
941             p++;
942         hextomem(mem_buf, p, len);
943         if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len,
944                                    true) != 0) {
945             put_packet(s, "E14");
946         } else {
947             put_packet(s, "OK");
948         }
949         break;
950     case 'p':
951         /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
952            This works, but can be very slow.  Anything new enough to
953            understand XML also knows how to use this properly.  */
954         if (!gdb_has_xml)
955             goto unknown_command;
956         addr = strtoull(p, (char **)&p, 16);
957         reg_size = gdb_read_register(s->g_cpu, mem_buf, addr);
958         if (reg_size) {
959             memtohex(buf, mem_buf, reg_size);
960             put_packet(s, buf);
961         } else {
962             put_packet(s, "E14");
963         }
964         break;
965     case 'P':
966         if (!gdb_has_xml)
967             goto unknown_command;
968         addr = strtoull(p, (char **)&p, 16);
969         if (*p == '=')
970             p++;
971         reg_size = strlen(p) / 2;
972         hextomem(mem_buf, p, reg_size);
973         gdb_write_register(s->g_cpu, mem_buf, addr);
974         put_packet(s, "OK");
975         break;
976     case 'Z':
977     case 'z':
978         type = strtoul(p, (char **)&p, 16);
979         if (*p == ',')
980             p++;
981         addr = strtoull(p, (char **)&p, 16);
982         if (*p == ',')
983             p++;
984         len = strtoull(p, (char **)&p, 16);
985         if (ch == 'Z')
986             res = gdb_breakpoint_insert(addr, len, type);
987         else
988             res = gdb_breakpoint_remove(addr, len, type);
989         if (res >= 0)
990              put_packet(s, "OK");
991         else if (res == -ENOSYS)
992             put_packet(s, "");
993         else
994             put_packet(s, "E22");
995         break;
996     case 'H':
997         type = *p++;
998         thread = strtoull(p, (char **)&p, 16);
999         if (thread == -1 || thread == 0) {
1000             put_packet(s, "OK");
1001             break;
1002         }
1003         cpu = find_cpu(thread);
1004         if (cpu == NULL) {
1005             put_packet(s, "E22");
1006             break;
1007         }
1008         switch (type) {
1009         case 'c':
1010             s->c_cpu = cpu;
1011             put_packet(s, "OK");
1012             break;
1013         case 'g':
1014             s->g_cpu = cpu;
1015             put_packet(s, "OK");
1016             break;
1017         default:
1018              put_packet(s, "E22");
1019              break;
1020         }
1021         break;
1022     case 'T':
1023         thread = strtoull(p, (char **)&p, 16);
1024         cpu = find_cpu(thread);
1025
1026         if (cpu != NULL) {
1027             put_packet(s, "OK");
1028         } else {
1029             put_packet(s, "E22");
1030         }
1031         break;
1032     case 'q':
1033     case 'Q':
1034         /* parse any 'q' packets here */
1035         if (!strcmp(p,"qemu.sstepbits")) {
1036             /* Query Breakpoint bit definitions */
1037             snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1038                      SSTEP_ENABLE,
1039                      SSTEP_NOIRQ,
1040                      SSTEP_NOTIMER);
1041             put_packet(s, buf);
1042             break;
1043         } else if (strncmp(p,"qemu.sstep",10) == 0) {
1044             /* Display or change the sstep_flags */
1045             p += 10;
1046             if (*p != '=') {
1047                 /* Display current setting */
1048                 snprintf(buf, sizeof(buf), "0x%x", sstep_flags);
1049                 put_packet(s, buf);
1050                 break;
1051             }
1052             p++;
1053             type = strtoul(p, (char **)&p, 16);
1054             sstep_flags = type;
1055             put_packet(s, "OK");
1056             break;
1057         } else if (strcmp(p,"C") == 0) {
1058             /* "Current thread" remains vague in the spec, so always return
1059              *  the first CPU (gdb returns the first thread). */
1060             put_packet(s, "QC1");
1061             break;
1062         } else if (strcmp(p,"fThreadInfo") == 0) {
1063             s->query_cpu = first_cpu;
1064             goto report_cpuinfo;
1065         } else if (strcmp(p,"sThreadInfo") == 0) {
1066         report_cpuinfo:
1067             if (s->query_cpu) {
1068                 snprintf(buf, sizeof(buf), "m%x", cpu_index(s->query_cpu));
1069                 put_packet(s, buf);
1070                 s->query_cpu = CPU_NEXT(s->query_cpu);
1071             } else
1072                 put_packet(s, "l");
1073             break;
1074         } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {
1075             thread = strtoull(p+16, (char **)&p, 16);
1076             cpu = find_cpu(thread);
1077             if (cpu != NULL) {
1078                 cpu_synchronize_state(cpu);
1079                 len = snprintf((char *)mem_buf, sizeof(mem_buf),
1080                                "CPU#%d [%s]", cpu->cpu_index,
1081                                cpu->halted ? "halted " : "running");
1082                 memtohex(buf, mem_buf, len);
1083                 put_packet(s, buf);
1084             }
1085             break;
1086         }
1087 #ifdef CONFIG_USER_ONLY
1088         else if (strncmp(p, "Offsets", 7) == 0) {
1089             TaskState *ts = s->c_cpu->opaque;
1090
1091             snprintf(buf, sizeof(buf),
1092                      "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
1093                      ";Bss=" TARGET_ABI_FMT_lx,
1094                      ts->info->code_offset,
1095                      ts->info->data_offset,
1096                      ts->info->data_offset);
1097             put_packet(s, buf);
1098             break;
1099         }
1100 #else /* !CONFIG_USER_ONLY */
1101         else if (strncmp(p, "Rcmd,", 5) == 0) {
1102             int len = strlen(p + 5);
1103
1104             if ((len % 2) != 0) {
1105                 put_packet(s, "E01");
1106                 break;
1107             }
1108             hextomem(mem_buf, p + 5, len);
1109             len = len / 2;
1110             mem_buf[len++] = 0;
1111             qemu_chr_be_write(s->mon_chr, mem_buf, len);
1112             put_packet(s, "OK");
1113             break;
1114         }
1115 #endif /* !CONFIG_USER_ONLY */
1116         if (strncmp(p, "Supported", 9) == 0) {
1117             snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);
1118             cc = CPU_GET_CLASS(first_cpu);
1119             if (cc->gdb_core_xml_file != NULL) {
1120                 pstrcat(buf, sizeof(buf), ";qXfer:features:read+");
1121             }
1122             put_packet(s, buf);
1123             break;
1124         }
1125         if (strncmp(p, "Xfer:features:read:", 19) == 0) {
1126             const char *xml;
1127             target_ulong total_len;
1128
1129             cc = CPU_GET_CLASS(first_cpu);
1130             if (cc->gdb_core_xml_file == NULL) {
1131                 goto unknown_command;
1132             }
1133
1134             gdb_has_xml = true;
1135             p += 19;
1136             xml = get_feature_xml(p, &p, cc);
1137             if (!xml) {
1138                 snprintf(buf, sizeof(buf), "E00");
1139                 put_packet(s, buf);
1140                 break;
1141             }
1142
1143             if (*p == ':')
1144                 p++;
1145             addr = strtoul(p, (char **)&p, 16);
1146             if (*p == ',')
1147                 p++;
1148             len = strtoul(p, (char **)&p, 16);
1149
1150             total_len = strlen(xml);
1151             if (addr > total_len) {
1152                 snprintf(buf, sizeof(buf), "E00");
1153                 put_packet(s, buf);
1154                 break;
1155             }
1156             if (len > (MAX_PACKET_LENGTH - 5) / 2)
1157                 len = (MAX_PACKET_LENGTH - 5) / 2;
1158             if (len < total_len - addr) {
1159                 buf[0] = 'm';
1160                 len = memtox(buf + 1, xml + addr, len);
1161             } else {
1162                 buf[0] = 'l';
1163                 len = memtox(buf + 1, xml + addr, total_len - addr);
1164             }
1165             put_packet_binary(s, buf, len + 1);
1166             break;
1167         }
1168         /* Unrecognised 'q' command.  */
1169         goto unknown_command;
1170
1171     default:
1172     unknown_command:
1173         /* put empty packet */
1174         buf[0] = '\0';
1175         put_packet(s, buf);
1176         break;
1177     }
1178     return RS_IDLE;
1179 }
1180
1181 void gdb_set_stop_cpu(CPUState *cpu)
1182 {
1183     gdbserver_state->c_cpu = cpu;
1184     gdbserver_state->g_cpu = cpu;
1185 }
1186
1187 #ifndef CONFIG_USER_ONLY
1188 static void gdb_vm_state_change(void *opaque, int running, RunState state)
1189 {
1190     GDBState *s = gdbserver_state;
1191     CPUArchState *env = s->c_cpu->env_ptr;
1192     CPUState *cpu = s->c_cpu;
1193     char buf[256];
1194     const char *type;
1195     int ret;
1196
1197     if (running || s->state == RS_INACTIVE) {
1198         return;
1199     }
1200     /* Is there a GDB syscall waiting to be sent?  */
1201     if (s->current_syscall_cb) {
1202         put_packet(s, s->syscall_buf);
1203         return;
1204     }
1205     switch (state) {
1206     case RUN_STATE_DEBUG:
1207         if (cpu->watchpoint_hit) {
1208             switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
1209             case BP_MEM_READ:
1210                 type = "r";
1211                 break;
1212             case BP_MEM_ACCESS:
1213                 type = "a";
1214                 break;
1215             default:
1216                 type = "";
1217                 break;
1218             }
1219             snprintf(buf, sizeof(buf),
1220                      "T%02xthread:%02x;%swatch:" TARGET_FMT_lx ";",
1221                      GDB_SIGNAL_TRAP, cpu_index(cpu), type,
1222                      (target_ulong)cpu->watchpoint_hit->vaddr);
1223             cpu->watchpoint_hit = NULL;
1224             goto send_packet;
1225         }
1226         tb_flush(env);
1227         ret = GDB_SIGNAL_TRAP;
1228         break;
1229     case RUN_STATE_PAUSED:
1230         ret = GDB_SIGNAL_INT;
1231         break;
1232     case RUN_STATE_SHUTDOWN:
1233         ret = GDB_SIGNAL_QUIT;
1234         break;
1235     case RUN_STATE_IO_ERROR:
1236         ret = GDB_SIGNAL_IO;
1237         break;
1238     case RUN_STATE_WATCHDOG:
1239         ret = GDB_SIGNAL_ALRM;
1240         break;
1241     case RUN_STATE_INTERNAL_ERROR:
1242         ret = GDB_SIGNAL_ABRT;
1243         break;
1244     case RUN_STATE_SAVE_VM:
1245     case RUN_STATE_RESTORE_VM:
1246         return;
1247     case RUN_STATE_FINISH_MIGRATE:
1248         ret = GDB_SIGNAL_XCPU;
1249         break;
1250     default:
1251         ret = GDB_SIGNAL_UNKNOWN;
1252         break;
1253     }
1254     snprintf(buf, sizeof(buf), "T%02xthread:%02x;", ret, cpu_index(cpu));
1255
1256 send_packet:
1257     put_packet(s, buf);
1258
1259     /* disable single step if it was enabled */
1260     cpu_single_step(cpu, 0);
1261 }
1262 #endif
1263
1264 /* Send a gdb syscall request.
1265    This accepts limited printf-style format specifiers, specifically:
1266     %x  - target_ulong argument printed in hex.
1267     %lx - 64-bit argument printed in hex.
1268     %s  - string pointer (target_ulong) and length (int) pair.  */
1269 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
1270 {
1271     va_list va;
1272     char *p;
1273     char *p_end;
1274     target_ulong addr;
1275     uint64_t i64;
1276     GDBState *s;
1277
1278     s = gdbserver_state;
1279     if (!s)
1280         return;
1281     s->current_syscall_cb = cb;
1282 #ifndef CONFIG_USER_ONLY
1283     vm_stop(RUN_STATE_DEBUG);
1284 #endif
1285     va_start(va, fmt);
1286     p = s->syscall_buf;
1287     p_end = &s->syscall_buf[sizeof(s->syscall_buf)];
1288     *(p++) = 'F';
1289     while (*fmt) {
1290         if (*fmt == '%') {
1291             fmt++;
1292             switch (*fmt++) {
1293             case 'x':
1294                 addr = va_arg(va, target_ulong);
1295                 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
1296                 break;
1297             case 'l':
1298                 if (*(fmt++) != 'x')
1299                     goto bad_format;
1300                 i64 = va_arg(va, uint64_t);
1301                 p += snprintf(p, p_end - p, "%" PRIx64, i64);
1302                 break;
1303             case 's':
1304                 addr = va_arg(va, target_ulong);
1305                 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
1306                               addr, va_arg(va, int));
1307                 break;
1308             default:
1309             bad_format:
1310                 fprintf(stderr, "gdbstub: Bad syscall format string '%s'\n",
1311                         fmt - 1);
1312                 break;
1313             }
1314         } else {
1315             *(p++) = *(fmt++);
1316         }
1317     }
1318     *p = 0;
1319     va_end(va);
1320 #ifdef CONFIG_USER_ONLY
1321     put_packet(s, s->syscall_buf);
1322     gdb_handlesig(s->c_cpu, 0);
1323 #else
1324     /* In this case wait to send the syscall packet until notification that
1325        the CPU has stopped.  This must be done because if the packet is sent
1326        now the reply from the syscall request could be received while the CPU
1327        is still in the running state, which can cause packets to be dropped
1328        and state transition 'T' packets to be sent while the syscall is still
1329        being processed.  */
1330     cpu_exit(s->c_cpu);
1331 #endif
1332 }
1333
1334 static void gdb_read_byte(GDBState *s, int ch)
1335 {
1336     int i, csum;
1337     uint8_t reply;
1338
1339 #ifndef CONFIG_USER_ONLY
1340     if (s->last_packet_len) {
1341         /* Waiting for a response to the last packet.  If we see the start
1342            of a new command then abandon the previous response.  */
1343         if (ch == '-') {
1344 #ifdef DEBUG_GDB
1345             printf("Got NACK, retransmitting\n");
1346 #endif
1347             put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
1348         }
1349 #ifdef DEBUG_GDB
1350         else if (ch == '+')
1351             printf("Got ACK\n");
1352         else
1353             printf("Got '%c' when expecting ACK/NACK\n", ch);
1354 #endif
1355         if (ch == '+' || ch == '$')
1356             s->last_packet_len = 0;
1357         if (ch != '$')
1358             return;
1359     }
1360     if (runstate_is_running()) {
1361         /* when the CPU is running, we cannot do anything except stop
1362            it when receiving a char */
1363         vm_stop(RUN_STATE_PAUSED);
1364     } else
1365 #endif
1366     {
1367         switch(s->state) {
1368         case RS_IDLE:
1369             if (ch == '$') {
1370                 s->line_buf_index = 0;
1371                 s->state = RS_GETLINE;
1372             }
1373             break;
1374         case RS_GETLINE:
1375             if (ch == '#') {
1376             s->state = RS_CHKSUM1;
1377             } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
1378                 s->state = RS_IDLE;
1379             } else {
1380             s->line_buf[s->line_buf_index++] = ch;
1381             }
1382             break;
1383         case RS_CHKSUM1:
1384             s->line_buf[s->line_buf_index] = '\0';
1385             s->line_csum = fromhex(ch) << 4;
1386             s->state = RS_CHKSUM2;
1387             break;
1388         case RS_CHKSUM2:
1389             s->line_csum |= fromhex(ch);
1390             csum = 0;
1391             for(i = 0; i < s->line_buf_index; i++) {
1392                 csum += s->line_buf[i];
1393             }
1394             if (s->line_csum != (csum & 0xff)) {
1395                 reply = '-';
1396                 put_buffer(s, &reply, 1);
1397                 s->state = RS_IDLE;
1398             } else {
1399                 reply = '+';
1400                 put_buffer(s, &reply, 1);
1401                 s->state = gdb_handle_packet(s, s->line_buf);
1402             }
1403             break;
1404         default:
1405             abort();
1406         }
1407     }
1408 }
1409
1410 /* Tell the remote gdb that the process has exited.  */
1411 void gdb_exit(CPUArchState *env, int code)
1412 {
1413   GDBState *s;
1414   char buf[4];
1415
1416   s = gdbserver_state;
1417   if (!s) {
1418       return;
1419   }
1420 #ifdef CONFIG_USER_ONLY
1421   if (gdbserver_fd < 0 || s->fd < 0) {
1422       return;
1423   }
1424 #endif
1425
1426   snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
1427   put_packet(s, buf);
1428
1429 #ifndef CONFIG_USER_ONLY
1430   if (s->chr) {
1431       qemu_chr_delete(s->chr);
1432   }
1433 #endif
1434 }
1435
1436 #ifdef CONFIG_USER_ONLY
1437 int
1438 gdb_queuesig (void)
1439 {
1440     GDBState *s;
1441
1442     s = gdbserver_state;
1443
1444     if (gdbserver_fd < 0 || s->fd < 0)
1445         return 0;
1446     else
1447         return 1;
1448 }
1449
1450 int
1451 gdb_handlesig(CPUState *cpu, int sig)
1452 {
1453     CPUArchState *env = cpu->env_ptr;
1454     GDBState *s;
1455     char buf[256];
1456     int n;
1457
1458     s = gdbserver_state;
1459     if (gdbserver_fd < 0 || s->fd < 0) {
1460         return sig;
1461     }
1462
1463     /* disable single step if it was enabled */
1464     cpu_single_step(cpu, 0);
1465     tb_flush(env);
1466
1467     if (sig != 0) {
1468         snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
1469         put_packet(s, buf);
1470     }
1471     /* put_packet() might have detected that the peer terminated the
1472        connection.  */
1473     if (s->fd < 0) {
1474         return sig;
1475     }
1476
1477     sig = 0;
1478     s->state = RS_IDLE;
1479     s->running_state = 0;
1480     while (s->running_state == 0) {
1481         n = read(s->fd, buf, 256);
1482         if (n > 0) {
1483             int i;
1484
1485             for (i = 0; i < n; i++) {
1486                 gdb_read_byte(s, buf[i]);
1487             }
1488         } else if (n == 0 || errno != EAGAIN) {
1489             /* XXX: Connection closed.  Should probably wait for another
1490                connection before continuing.  */
1491             return sig;
1492         }
1493     }
1494     sig = s->signal;
1495     s->signal = 0;
1496     return sig;
1497 }
1498
1499 /* Tell the remote gdb that the process has exited due to SIG.  */
1500 void gdb_signalled(CPUArchState *env, int sig)
1501 {
1502     GDBState *s;
1503     char buf[4];
1504
1505     s = gdbserver_state;
1506     if (gdbserver_fd < 0 || s->fd < 0) {
1507         return;
1508     }
1509
1510     snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
1511     put_packet(s, buf);
1512 }
1513
1514 static void gdb_accept(void)
1515 {
1516     GDBState *s;
1517     struct sockaddr_in sockaddr;
1518     socklen_t len;
1519     int fd;
1520
1521     for(;;) {
1522         len = sizeof(sockaddr);
1523         fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
1524         if (fd < 0 && errno != EINTR) {
1525             perror("accept");
1526             return;
1527         } else if (fd >= 0) {
1528 #ifndef _WIN32
1529             fcntl(fd, F_SETFD, FD_CLOEXEC);
1530 #endif
1531             break;
1532         }
1533     }
1534
1535     /* set short latency */
1536     socket_set_nodelay(fd);
1537
1538     s = g_malloc0(sizeof(GDBState));
1539     s->c_cpu = first_cpu;
1540     s->g_cpu = first_cpu;
1541     s->fd = fd;
1542     gdb_has_xml = false;
1543
1544     gdbserver_state = s;
1545
1546     fcntl(fd, F_SETFL, O_NONBLOCK);
1547 }
1548
1549 static int gdbserver_open(int port)
1550 {
1551     struct sockaddr_in sockaddr;
1552     int fd, ret;
1553
1554     fd = socket(PF_INET, SOCK_STREAM, 0);
1555     if (fd < 0) {
1556         perror("socket");
1557         return -1;
1558     }
1559 #ifndef _WIN32
1560     fcntl(fd, F_SETFD, FD_CLOEXEC);
1561 #endif
1562
1563     socket_set_fast_reuse(fd);
1564
1565     sockaddr.sin_family = AF_INET;
1566     sockaddr.sin_port = htons(port);
1567     sockaddr.sin_addr.s_addr = 0;
1568     ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
1569     if (ret < 0) {
1570         perror("bind");
1571         close(fd);
1572         return -1;
1573     }
1574     ret = listen(fd, 0);
1575     if (ret < 0) {
1576         perror("listen");
1577         close(fd);
1578         return -1;
1579     }
1580     return fd;
1581 }
1582
1583 int gdbserver_start(int port)
1584 {
1585     gdbserver_fd = gdbserver_open(port);
1586     if (gdbserver_fd < 0)
1587         return -1;
1588     /* accept connections */
1589     gdb_accept();
1590     return 0;
1591 }
1592
1593 /* Disable gdb stub for child processes.  */
1594 void gdbserver_fork(CPUArchState *env)
1595 {
1596     GDBState *s = gdbserver_state;
1597     if (gdbserver_fd < 0 || s->fd < 0)
1598       return;
1599     close(s->fd);
1600     s->fd = -1;
1601     cpu_breakpoint_remove_all(env, BP_GDB);
1602     cpu_watchpoint_remove_all(env, BP_GDB);
1603 }
1604 #else
1605 static int gdb_chr_can_receive(void *opaque)
1606 {
1607   /* We can handle an arbitrarily large amount of data.
1608    Pick the maximum packet size, which is as good as anything.  */
1609   return MAX_PACKET_LENGTH;
1610 }
1611
1612 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
1613 {
1614     int i;
1615
1616     for (i = 0; i < size; i++) {
1617         gdb_read_byte(gdbserver_state, buf[i]);
1618     }
1619 }
1620
1621 static void gdb_chr_event(void *opaque, int event)
1622 {
1623     switch (event) {
1624     case CHR_EVENT_OPENED:
1625         vm_stop(RUN_STATE_PAUSED);
1626         gdb_has_xml = false;
1627         break;
1628     default:
1629         break;
1630     }
1631 }
1632
1633 static void gdb_monitor_output(GDBState *s, const char *msg, int len)
1634 {
1635     char buf[MAX_PACKET_LENGTH];
1636
1637     buf[0] = 'O';
1638     if (len > (MAX_PACKET_LENGTH/2) - 1)
1639         len = (MAX_PACKET_LENGTH/2) - 1;
1640     memtohex(buf + 1, (uint8_t *)msg, len);
1641     put_packet(s, buf);
1642 }
1643
1644 static int gdb_monitor_write(CharDriverState *chr, const uint8_t *buf, int len)
1645 {
1646     const char *p = (const char *)buf;
1647     int max_sz;
1648
1649     max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
1650     for (;;) {
1651         if (len <= max_sz) {
1652             gdb_monitor_output(gdbserver_state, p, len);
1653             break;
1654         }
1655         gdb_monitor_output(gdbserver_state, p, max_sz);
1656         p += max_sz;
1657         len -= max_sz;
1658     }
1659     return len;
1660 }
1661
1662 #ifndef _WIN32
1663 static void gdb_sigterm_handler(int signal)
1664 {
1665     if (runstate_is_running()) {
1666         vm_stop(RUN_STATE_PAUSED);
1667     }
1668 }
1669 #endif
1670
1671 int gdbserver_start(const char *device)
1672 {
1673     GDBState *s;
1674     char gdbstub_device_name[128];
1675     CharDriverState *chr = NULL;
1676     CharDriverState *mon_chr;
1677
1678     if (!device)
1679         return -1;
1680     if (strcmp(device, "none") != 0) {
1681         if (strstart(device, "tcp:", NULL)) {
1682             /* enforce required TCP attributes */
1683             snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
1684                      "%s,nowait,nodelay,server", device);
1685             device = gdbstub_device_name;
1686         }
1687 #ifndef _WIN32
1688         else if (strcmp(device, "stdio") == 0) {
1689             struct sigaction act;
1690
1691             memset(&act, 0, sizeof(act));
1692             act.sa_handler = gdb_sigterm_handler;
1693             sigaction(SIGINT, &act, NULL);
1694         }
1695 #endif
1696         chr = qemu_chr_new("gdb", device, NULL);
1697         if (!chr)
1698             return -1;
1699
1700         qemu_chr_fe_claim_no_fail(chr);
1701         qemu_chr_add_handlers(chr, gdb_chr_can_receive, gdb_chr_receive,
1702                               gdb_chr_event, NULL);
1703     }
1704
1705     s = gdbserver_state;
1706     if (!s) {
1707         s = g_malloc0(sizeof(GDBState));
1708         gdbserver_state = s;
1709
1710         qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
1711
1712         /* Initialize a monitor terminal for gdb */
1713         mon_chr = g_malloc0(sizeof(*mon_chr));
1714         mon_chr->chr_write = gdb_monitor_write;
1715         monitor_init(mon_chr, 0);
1716     } else {
1717         if (s->chr)
1718             qemu_chr_delete(s->chr);
1719         mon_chr = s->mon_chr;
1720         memset(s, 0, sizeof(GDBState));
1721     }
1722     s->c_cpu = first_cpu;
1723     s->g_cpu = first_cpu;
1724     s->chr = chr;
1725     s->state = chr ? RS_IDLE : RS_INACTIVE;
1726     s->mon_chr = mon_chr;
1727     s->current_syscall_cb = NULL;
1728
1729     return 0;
1730 }
1731 #endif