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