target-m68k: Move cpu_gdb_{read,write}_register()
[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 static int cpu_gdb_read_register(CPUMIPSState *env, uint8_t *mem_buf, int n)
554 {
555     if (n < 32) {
556         GET_REGL(env->active_tc.gpr[n]);
557     }
558     if (env->CP0_Config1 & (1 << CP0C1_FP)) {
559         if (n >= 38 && n < 70) {
560             if (env->CP0_Status & (1 << CP0St_FR)) {
561                 GET_REGL(env->active_fpu.fpr[n - 38].d);
562             } else {
563                 GET_REGL(env->active_fpu.fpr[n - 38].w[FP_ENDIAN_IDX]);
564             }
565         }
566         switch (n) {
567         case 70:
568             GET_REGL((int32_t)env->active_fpu.fcr31);
569         case 71:
570             GET_REGL((int32_t)env->active_fpu.fcr0);
571         }
572     }
573     switch (n) {
574     case 32:
575         GET_REGL((int32_t)env->CP0_Status);
576     case 33:
577         GET_REGL(env->active_tc.LO[0]);
578     case 34:
579         GET_REGL(env->active_tc.HI[0]);
580     case 35:
581         GET_REGL(env->CP0_BadVAddr);
582     case 36:
583         GET_REGL((int32_t)env->CP0_Cause);
584     case 37:
585         GET_REGL(env->active_tc.PC | !!(env->hflags & MIPS_HFLAG_M16));
586     case 72:
587         GET_REGL(0); /* fp */
588     case 89:
589         GET_REGL((int32_t)env->CP0_PRid);
590     }
591     if (n >= 73 && n <= 88) {
592         /* 16 embedded regs.  */
593         GET_REGL(0);
594     }
595
596     return 0;
597 }
598
599 /* convert MIPS rounding mode in FCR31 to IEEE library */
600 static unsigned int ieee_rm[] = {
601     float_round_nearest_even,
602     float_round_to_zero,
603     float_round_up,
604     float_round_down
605 };
606 #define RESTORE_ROUNDING_MODE \
607     set_float_rounding_mode(ieee_rm[env->active_fpu.fcr31 & 3], \
608                             &env->active_fpu.fp_status)
609
610 static int cpu_gdb_write_register(CPUMIPSState *env, uint8_t *mem_buf, int n)
611 {
612     target_ulong tmp;
613
614     tmp = ldtul_p(mem_buf);
615
616     if (n < 32) {
617         env->active_tc.gpr[n] = tmp;
618         return sizeof(target_ulong);
619     }
620     if (env->CP0_Config1 & (1 << CP0C1_FP)
621             && n >= 38 && n < 73) {
622         if (n < 70) {
623             if (env->CP0_Status & (1 << CP0St_FR)) {
624                 env->active_fpu.fpr[n - 38].d = tmp;
625             } else {
626                 env->active_fpu.fpr[n - 38].w[FP_ENDIAN_IDX] = tmp;
627             }
628         }
629         switch (n) {
630         case 70:
631             env->active_fpu.fcr31 = tmp & 0xFF83FFFF;
632             /* set rounding mode */
633             RESTORE_ROUNDING_MODE;
634             break;
635         case 71:
636             env->active_fpu.fcr0 = tmp;
637             break;
638         }
639         return sizeof(target_ulong);
640     }
641     switch (n) {
642     case 32:
643         env->CP0_Status = tmp;
644         break;
645     case 33:
646         env->active_tc.LO[0] = tmp;
647         break;
648     case 34:
649         env->active_tc.HI[0] = tmp;
650         break;
651     case 35:
652         env->CP0_BadVAddr = tmp;
653         break;
654     case 36:
655         env->CP0_Cause = tmp;
656         break;
657     case 37:
658         env->active_tc.PC = tmp & ~(target_ulong)1;
659         if (tmp & 1) {
660             env->hflags |= MIPS_HFLAG_M16;
661         } else {
662             env->hflags &= ~(MIPS_HFLAG_M16);
663         }
664         break;
665     case 72: /* fp, ignored */
666         break;
667     default:
668         if (n > 89) {
669             return 0;
670         }
671         /* Other registers are readonly.  Ignore writes.  */
672         break;
673     }
674
675     return sizeof(target_ulong);
676 }
677 #elif defined(TARGET_OPENRISC)
678
679 static int cpu_gdb_read_register(CPUOpenRISCState *env, uint8_t *mem_buf, int n)
680 {
681     if (n < 32) {
682         GET_REG32(env->gpr[n]);
683     } else {
684         switch (n) {
685         case 32:    /* PPC */
686             GET_REG32(env->ppc);
687
688         case 33:    /* NPC */
689             GET_REG32(env->npc);
690
691         case 34:    /* SR */
692             GET_REG32(env->sr);
693
694         default:
695             break;
696         }
697     }
698     return 0;
699 }
700
701 static int cpu_gdb_write_register(CPUOpenRISCState *env,
702                                   uint8_t *mem_buf, int n)
703 {
704     OpenRISCCPU *cpu = openrisc_env_get_cpu(env);
705     CPUClass *cc = CPU_GET_CLASS(cpu);
706     uint32_t tmp;
707
708     if (n > cc->gdb_num_core_regs) {
709         return 0;
710     }
711
712     tmp = ldl_p(mem_buf);
713
714     if (n < 32) {
715         env->gpr[n] = tmp;
716     } else {
717         switch (n) {
718         case 32: /* PPC */
719             env->ppc = tmp;
720             break;
721
722         case 33: /* NPC */
723             env->npc = tmp;
724             break;
725
726         case 34: /* SR */
727             env->sr = tmp;
728             break;
729
730         default:
731             break;
732         }
733     }
734     return 4;
735 }
736 #elif defined (TARGET_SH4)
737
738 /* Hint: Use "set architecture sh4" in GDB to see fpu registers */
739 /* FIXME: We should use XML for this.  */
740
741 static int cpu_gdb_read_register(CPUSH4State *env, uint8_t *mem_buf, int n)
742 {
743     switch (n) {
744     case 0 ... 7:
745         if ((env->sr & (SR_MD | SR_RB)) == (SR_MD | SR_RB)) {
746             GET_REGL(env->gregs[n + 16]);
747         } else {
748             GET_REGL(env->gregs[n]);
749         }
750     case 8 ... 15:
751         GET_REGL(env->gregs[n]);
752     case 16:
753         GET_REGL(env->pc);
754     case 17:
755         GET_REGL(env->pr);
756     case 18:
757         GET_REGL(env->gbr);
758     case 19:
759         GET_REGL(env->vbr);
760     case 20:
761         GET_REGL(env->mach);
762     case 21:
763         GET_REGL(env->macl);
764     case 22:
765         GET_REGL(env->sr);
766     case 23:
767         GET_REGL(env->fpul);
768     case 24:
769         GET_REGL(env->fpscr);
770     case 25 ... 40:
771         if (env->fpscr & FPSCR_FR) {
772             stfl_p(mem_buf, env->fregs[n - 9]);
773         } else {
774             stfl_p(mem_buf, env->fregs[n - 25]);
775         }
776         return 4;
777     case 41:
778         GET_REGL(env->ssr);
779     case 42:
780         GET_REGL(env->spc);
781     case 43 ... 50:
782         GET_REGL(env->gregs[n - 43]);
783     case 51 ... 58:
784         GET_REGL(env->gregs[n - (51 - 16)]);
785     }
786
787     return 0;
788 }
789
790 static int cpu_gdb_write_register(CPUSH4State *env, uint8_t *mem_buf, int n)
791 {
792     switch (n) {
793     case 0 ... 7:
794         if ((env->sr & (SR_MD | SR_RB)) == (SR_MD | SR_RB)) {
795             env->gregs[n + 16] = ldl_p(mem_buf);
796         } else {
797             env->gregs[n] = ldl_p(mem_buf);
798         }
799         break;
800     case 8 ... 15:
801         env->gregs[n] = ldl_p(mem_buf);
802         break;
803     case 16:
804         env->pc = ldl_p(mem_buf);
805         break;
806     case 17:
807         env->pr = ldl_p(mem_buf);
808         break;
809     case 18:
810         env->gbr = ldl_p(mem_buf);
811         break;
812     case 19:
813         env->vbr = ldl_p(mem_buf);
814         break;
815     case 20:
816         env->mach = ldl_p(mem_buf);
817         break;
818     case 21:
819         env->macl = ldl_p(mem_buf);
820         break;
821     case 22:
822         env->sr = ldl_p(mem_buf);
823         break;
824     case 23:
825         env->fpul = ldl_p(mem_buf);
826         break;
827     case 24:
828         env->fpscr = ldl_p(mem_buf);
829         break;
830     case 25 ... 40:
831         if (env->fpscr & FPSCR_FR) {
832             env->fregs[n - 9] = ldfl_p(mem_buf);
833         } else {
834             env->fregs[n - 25] = ldfl_p(mem_buf);
835         }
836         break;
837     case 41:
838         env->ssr = ldl_p(mem_buf);
839         break;
840     case 42:
841         env->spc = ldl_p(mem_buf);
842         break;
843     case 43 ... 50:
844         env->gregs[n - 43] = ldl_p(mem_buf);
845         break;
846     case 51 ... 58:
847         env->gregs[n - (51 - 16)] = ldl_p(mem_buf);
848         break;
849     default:
850         return 0;
851     }
852
853     return 4;
854 }
855 #elif defined (TARGET_MICROBLAZE)
856
857 static int cpu_gdb_read_register(CPUMBState *env, uint8_t *mem_buf, int n)
858 {
859     if (n < 32) {
860         GET_REG32(env->regs[n]);
861     } else {
862         GET_REG32(env->sregs[n - 32]);
863     }
864     return 0;
865 }
866
867 static int cpu_gdb_write_register(CPUMBState *env, uint8_t *mem_buf, int n)
868 {
869     MicroBlazeCPU *cpu = mb_env_get_cpu(env);
870     CPUClass *cc = CPU_GET_CLASS(cpu);
871     uint32_t tmp;
872
873     if (n > cc->gdb_num_core_regs) {
874         return 0;
875     }
876
877     tmp = ldl_p(mem_buf);
878
879     if (n < 32) {
880         env->regs[n] = tmp;
881     } else {
882         env->sregs[n - 32] = tmp;
883     }
884     return 4;
885 }
886 #elif defined (TARGET_CRIS)
887
888 static int
889 read_register_crisv10(CPUCRISState *env, uint8_t *mem_buf, int n)
890 {
891     if (n < 15) {
892         GET_REG32(env->regs[n]);
893     }
894
895     if (n == 15) {
896         GET_REG32(env->pc);
897     }
898
899     if (n < 32) {
900         switch (n) {
901         case 16:
902             GET_REG8(env->pregs[n - 16]);
903         case 17:
904             GET_REG8(env->pregs[n - 16]);
905         case 20:
906         case 21:
907             GET_REG16(env->pregs[n - 16]);
908         default:
909             if (n >= 23) {
910                 GET_REG32(env->pregs[n - 16]);
911             }
912             break;
913         }
914     }
915     return 0;
916 }
917
918 static int cpu_gdb_read_register(CPUCRISState *env, uint8_t *mem_buf, int n)
919 {
920     uint8_t srs;
921
922     if (env->pregs[PR_VR] < 32) {
923         return read_register_crisv10(env, mem_buf, n);
924     }
925
926     srs = env->pregs[PR_SRS];
927     if (n < 16) {
928         GET_REG32(env->regs[n]);
929     }
930
931     if (n >= 21 && n < 32) {
932         GET_REG32(env->pregs[n - 16]);
933     }
934     if (n >= 33 && n < 49) {
935         GET_REG32(env->sregs[srs][n - 33]);
936     }
937     switch (n) {
938     case 16:
939         GET_REG8(env->pregs[0]);
940     case 17:
941         GET_REG8(env->pregs[1]);
942     case 18:
943         GET_REG32(env->pregs[2]);
944     case 19:
945         GET_REG8(srs);
946     case 20:
947         GET_REG16(env->pregs[4]);
948     case 32:
949         GET_REG32(env->pc);
950     }
951
952     return 0;
953 }
954
955 static int cpu_gdb_write_register(CPUCRISState *env, uint8_t *mem_buf, int n)
956 {
957     uint32_t tmp;
958
959     if (n > 49) {
960         return 0;
961     }
962
963     tmp = ldl_p(mem_buf);
964
965     if (n < 16) {
966         env->regs[n] = tmp;
967     }
968
969     if (n >= 21 && n < 32) {
970         env->pregs[n - 16] = tmp;
971     }
972
973     /* FIXME: Should support function regs be writable?  */
974     switch (n) {
975     case 16:
976         return 1;
977     case 17:
978         return 1;
979     case 18:
980         env->pregs[PR_PID] = tmp;
981         break;
982     case 19:
983         return 1;
984     case 20:
985         return 2;
986     case 32:
987         env->pc = tmp;
988         break;
989     }
990
991     return 4;
992 }
993 #elif defined (TARGET_ALPHA)
994
995 static int cpu_gdb_read_register(CPUAlphaState *env, uint8_t *mem_buf, int n)
996 {
997     uint64_t val;
998     CPU_DoubleU d;
999
1000     switch (n) {
1001     case 0 ... 30:
1002         val = env->ir[n];
1003         break;
1004     case 32 ... 62:
1005         d.d = env->fir[n - 32];
1006         val = d.ll;
1007         break;
1008     case 63:
1009         val = cpu_alpha_load_fpcr(env);
1010         break;
1011     case 64:
1012         val = env->pc;
1013         break;
1014     case 66:
1015         val = env->unique;
1016         break;
1017     case 31:
1018     case 65:
1019         /* 31 really is the zero register; 65 is unassigned in the
1020            gdb protocol, but is still required to occupy 8 bytes. */
1021         val = 0;
1022         break;
1023     default:
1024         return 0;
1025     }
1026     GET_REGL(val);
1027 }
1028
1029 static int cpu_gdb_write_register(CPUAlphaState *env, uint8_t *mem_buf, int n)
1030 {
1031     target_ulong tmp = ldtul_p(mem_buf);
1032     CPU_DoubleU d;
1033
1034     switch (n) {
1035     case 0 ... 30:
1036         env->ir[n] = tmp;
1037         break;
1038     case 32 ... 62:
1039         d.ll = tmp;
1040         env->fir[n - 32] = d.d;
1041         break;
1042     case 63:
1043         cpu_alpha_store_fpcr(env, tmp);
1044         break;
1045     case 64:
1046         env->pc = tmp;
1047         break;
1048     case 66:
1049         env->unique = tmp;
1050         break;
1051     case 31:
1052     case 65:
1053         /* 31 really is the zero register; 65 is unassigned in the
1054            gdb protocol, but is still required to occupy 8 bytes. */
1055         break;
1056     default:
1057         return 0;
1058     }
1059     return 8;
1060 }
1061 #elif defined (TARGET_S390X)
1062
1063 static int cpu_gdb_read_register(CPUS390XState *env, uint8_t *mem_buf, int n)
1064 {
1065     uint64_t val;
1066     int cc_op;
1067
1068     switch (n) {
1069     case S390_PSWM_REGNUM:
1070         cc_op = calc_cc(env, env->cc_op, env->cc_src, env->cc_dst, env->cc_vr);
1071         val = deposit64(env->psw.mask, 44, 2, cc_op);
1072         GET_REGL(val);
1073     case S390_PSWA_REGNUM:
1074         GET_REGL(env->psw.addr);
1075     case S390_R0_REGNUM ... S390_R15_REGNUM:
1076         GET_REGL(env->regs[n-S390_R0_REGNUM]);
1077     case S390_A0_REGNUM ... S390_A15_REGNUM:
1078         GET_REG32(env->aregs[n-S390_A0_REGNUM]);
1079     case S390_FPC_REGNUM:
1080         GET_REG32(env->fpc);
1081     case S390_F0_REGNUM ... S390_F15_REGNUM:
1082         GET_REG64(env->fregs[n-S390_F0_REGNUM].ll);
1083     }
1084
1085     return 0;
1086 }
1087
1088 static int cpu_gdb_write_register(CPUS390XState *env, uint8_t *mem_buf, int n)
1089 {
1090     target_ulong tmpl;
1091     uint32_t tmp32;
1092     int r = 8;
1093     tmpl = ldtul_p(mem_buf);
1094     tmp32 = ldl_p(mem_buf);
1095
1096     switch (n) {
1097     case S390_PSWM_REGNUM:
1098         env->psw.mask = tmpl;
1099         env->cc_op = extract64(tmpl, 44, 2);
1100         break;
1101     case S390_PSWA_REGNUM:
1102         env->psw.addr = tmpl;
1103         break;
1104     case S390_R0_REGNUM ... S390_R15_REGNUM:
1105         env->regs[n-S390_R0_REGNUM] = tmpl;
1106         break;
1107     case S390_A0_REGNUM ... S390_A15_REGNUM:
1108         env->aregs[n-S390_A0_REGNUM] = tmp32;
1109         r = 4;
1110         break;
1111     case S390_FPC_REGNUM:
1112         env->fpc = tmp32;
1113         r = 4;
1114         break;
1115     case S390_F0_REGNUM ... S390_F15_REGNUM:
1116         env->fregs[n-S390_F0_REGNUM].ll = tmpl;
1117         break;
1118     default:
1119         return 0;
1120     }
1121     return r;
1122 }
1123 #elif defined (TARGET_LM32)
1124
1125 #include "hw/lm32/lm32_pic.h"
1126
1127 static int cpu_gdb_read_register(CPULM32State *env, uint8_t *mem_buf, int n)
1128 {
1129     if (n < 32) {
1130         GET_REG32(env->regs[n]);
1131     } else {
1132         switch (n) {
1133         case 32:
1134             GET_REG32(env->pc);
1135         /* FIXME: put in right exception ID */
1136         case 33:
1137             GET_REG32(0);
1138         case 34:
1139             GET_REG32(env->eba);
1140         case 35:
1141             GET_REG32(env->deba);
1142         case 36:
1143             GET_REG32(env->ie);
1144         case 37:
1145             GET_REG32(lm32_pic_get_im(env->pic_state));
1146         case 38:
1147             GET_REG32(lm32_pic_get_ip(env->pic_state));
1148         }
1149     }
1150     return 0;
1151 }
1152
1153 static int cpu_gdb_write_register(CPULM32State *env, uint8_t *mem_buf, int n)
1154 {
1155     LM32CPU *cpu = lm32_env_get_cpu(env);
1156     CPUClass *cc = CPU_GET_CLASS(cpu);
1157     uint32_t tmp;
1158
1159     if (n > cc->gdb_num_core_regs) {
1160         return 0;
1161     }
1162
1163     tmp = ldl_p(mem_buf);
1164
1165     if (n < 32) {
1166         env->regs[n] = tmp;
1167     } else {
1168         switch (n) {
1169         case 32:
1170             env->pc = tmp;
1171             break;
1172         case 34:
1173             env->eba = tmp;
1174             break;
1175         case 35:
1176             env->deba = tmp;
1177             break;
1178         case 36:
1179             env->ie = tmp;
1180             break;
1181         case 37:
1182             lm32_pic_set_im(env->pic_state, tmp);
1183             break;
1184         case 38:
1185             lm32_pic_set_ip(env->pic_state, tmp);
1186             break;
1187         }
1188     }
1189     return 4;
1190 }
1191 #elif defined(TARGET_XTENSA)
1192
1193 static int cpu_gdb_read_register(CPUXtensaState *env, uint8_t *mem_buf, int n)
1194 {
1195     const XtensaGdbReg *reg = env->config->gdb_regmap.reg + n;
1196
1197     if (n < 0 || n >= env->config->gdb_regmap.num_regs) {
1198         return 0;
1199     }
1200
1201     switch (reg->type) {
1202     case 9: /*pc*/
1203         GET_REG32(env->pc);
1204
1205     case 1: /*ar*/
1206         xtensa_sync_phys_from_window(env);
1207         GET_REG32(env->phys_regs[(reg->targno & 0xff) % env->config->nareg]);
1208
1209     case 2: /*SR*/
1210         GET_REG32(env->sregs[reg->targno & 0xff]);
1211
1212     case 3: /*UR*/
1213         GET_REG32(env->uregs[reg->targno & 0xff]);
1214
1215     case 4: /*f*/
1216         GET_REG32(float32_val(env->fregs[reg->targno & 0x0f]));
1217
1218     case 8: /*a*/
1219         GET_REG32(env->regs[reg->targno & 0x0f]);
1220
1221     default:
1222         qemu_log("%s from reg %d of unsupported type %d\n",
1223                  __func__, n, reg->type);
1224         return 0;
1225     }
1226 }
1227
1228 static int cpu_gdb_write_register(CPUXtensaState *env, uint8_t *mem_buf, int n)
1229 {
1230     uint32_t tmp;
1231     const XtensaGdbReg *reg = env->config->gdb_regmap.reg + n;
1232
1233     if (n < 0 || n >= env->config->gdb_regmap.num_regs) {
1234         return 0;
1235     }
1236
1237     tmp = ldl_p(mem_buf);
1238
1239     switch (reg->type) {
1240     case 9: /*pc*/
1241         env->pc = tmp;
1242         break;
1243
1244     case 1: /*ar*/
1245         env->phys_regs[(reg->targno & 0xff) % env->config->nareg] = tmp;
1246         xtensa_sync_window_from_phys(env);
1247         break;
1248
1249     case 2: /*SR*/
1250         env->sregs[reg->targno & 0xff] = tmp;
1251         break;
1252
1253     case 3: /*UR*/
1254         env->uregs[reg->targno & 0xff] = tmp;
1255         break;
1256
1257     case 4: /*f*/
1258         env->fregs[reg->targno & 0x0f] = make_float32(tmp);
1259         break;
1260
1261     case 8: /*a*/
1262         env->regs[reg->targno & 0x0f] = tmp;
1263         break;
1264
1265     default:
1266         qemu_log("%s to reg %d of unsupported type %d\n",
1267                  __func__, n, reg->type);
1268         return 0;
1269     }
1270
1271     return 4;
1272 }
1273 #else
1274
1275 static int cpu_gdb_read_register(CPUArchState *env, uint8_t *mem_buf, int n)
1276 {
1277     return 0;
1278 }
1279
1280 static int cpu_gdb_write_register(CPUArchState *env, uint8_t *mem_buf, int n)
1281 {
1282     return 0;
1283 }
1284
1285 #endif
1286
1287 #ifdef GDB_CORE_XML
1288 /* Encode data using the encoding for 'x' packets.  */
1289 static int memtox(char *buf, const char *mem, int len)
1290 {
1291     char *p = buf;
1292     char c;
1293
1294     while (len--) {
1295         c = *(mem++);
1296         switch (c) {
1297         case '#': case '$': case '*': case '}':
1298             *(p++) = '}';
1299             *(p++) = c ^ 0x20;
1300             break;
1301         default:
1302             *(p++) = c;
1303             break;
1304         }
1305     }
1306     return p - buf;
1307 }
1308
1309 static const char *get_feature_xml(const char *p, const char **newp)
1310 {
1311     size_t len;
1312     int i;
1313     const char *name;
1314     static char target_xml[1024];
1315
1316     len = 0;
1317     while (p[len] && p[len] != ':')
1318         len++;
1319     *newp = p + len;
1320
1321     name = NULL;
1322     if (strncmp(p, "target.xml", len) == 0) {
1323         /* Generate the XML description for this CPU.  */
1324         if (!target_xml[0]) {
1325             GDBRegisterState *r;
1326             CPUState *cpu = first_cpu;
1327
1328             snprintf(target_xml, sizeof(target_xml),
1329                      "<?xml version=\"1.0\"?>"
1330                      "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
1331                      "<target>"
1332                      "<xi:include href=\"%s\"/>",
1333                      GDB_CORE_XML);
1334
1335             for (r = cpu->gdb_regs; r; r = r->next) {
1336                 pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
1337                 pstrcat(target_xml, sizeof(target_xml), r->xml);
1338                 pstrcat(target_xml, sizeof(target_xml), "\"/>");
1339             }
1340             pstrcat(target_xml, sizeof(target_xml), "</target>");
1341         }
1342         return target_xml;
1343     }
1344     for (i = 0; ; i++) {
1345         name = xml_builtin[i][0];
1346         if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
1347             break;
1348     }
1349     return name ? xml_builtin[i][1] : NULL;
1350 }
1351 #endif
1352
1353 static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
1354 {
1355     CPUClass *cc = CPU_GET_CLASS(cpu);
1356     CPUArchState *env = cpu->env_ptr;
1357     GDBRegisterState *r;
1358
1359     if (reg < cc->gdb_num_core_regs) {
1360         return cpu_gdb_read_register(env, mem_buf, reg);
1361     }
1362
1363     for (r = cpu->gdb_regs; r; r = r->next) {
1364         if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
1365             return r->get_reg(env, mem_buf, reg - r->base_reg);
1366         }
1367     }
1368     return 0;
1369 }
1370
1371 static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
1372 {
1373     CPUClass *cc = CPU_GET_CLASS(cpu);
1374     CPUArchState *env = cpu->env_ptr;
1375     GDBRegisterState *r;
1376
1377     if (reg < cc->gdb_num_core_regs) {
1378         return cpu_gdb_write_register(env, mem_buf, reg);
1379     }
1380
1381     for (r = cpu->gdb_regs; r; r = r->next) {
1382         if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
1383             return r->set_reg(env, mem_buf, reg - r->base_reg);
1384         }
1385     }
1386     return 0;
1387 }
1388
1389 /* Register a supplemental set of CPU registers.  If g_pos is nonzero it
1390    specifies the first register number and these registers are included in
1391    a standard "g" packet.  Direction is relative to gdb, i.e. get_reg is
1392    gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
1393  */
1394
1395 void gdb_register_coprocessor(CPUState *cpu,
1396                               gdb_reg_cb get_reg, gdb_reg_cb set_reg,
1397                               int num_regs, const char *xml, int g_pos)
1398 {
1399     GDBRegisterState *s;
1400     GDBRegisterState **p;
1401
1402     p = &cpu->gdb_regs;
1403     while (*p) {
1404         /* Check for duplicates.  */
1405         if (strcmp((*p)->xml, xml) == 0)
1406             return;
1407         p = &(*p)->next;
1408     }
1409
1410     s = g_new0(GDBRegisterState, 1);
1411     s->base_reg = cpu->gdb_num_regs;
1412     s->num_regs = num_regs;
1413     s->get_reg = get_reg;
1414     s->set_reg = set_reg;
1415     s->xml = xml;
1416
1417     /* Add to end of list.  */
1418     cpu->gdb_num_regs += num_regs;
1419     *p = s;
1420     if (g_pos) {
1421         if (g_pos != s->base_reg) {
1422             fprintf(stderr, "Error: Bad gdb register numbering for '%s'\n"
1423                     "Expected %d got %d\n", xml, g_pos, s->base_reg);
1424         }
1425     }
1426 }
1427
1428 #ifndef CONFIG_USER_ONLY
1429 static const int xlat_gdb_type[] = {
1430     [GDB_WATCHPOINT_WRITE]  = BP_GDB | BP_MEM_WRITE,
1431     [GDB_WATCHPOINT_READ]   = BP_GDB | BP_MEM_READ,
1432     [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
1433 };
1434 #endif
1435
1436 static int gdb_breakpoint_insert(target_ulong addr, target_ulong len, int type)
1437 {
1438     CPUState *cpu;
1439     CPUArchState *env;
1440     int err = 0;
1441
1442     if (kvm_enabled()) {
1443         return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
1444     }
1445
1446     switch (type) {
1447     case GDB_BREAKPOINT_SW:
1448     case GDB_BREAKPOINT_HW:
1449         for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
1450             env = cpu->env_ptr;
1451             err = cpu_breakpoint_insert(env, addr, BP_GDB, NULL);
1452             if (err)
1453                 break;
1454         }
1455         return err;
1456 #ifndef CONFIG_USER_ONLY
1457     case GDB_WATCHPOINT_WRITE:
1458     case GDB_WATCHPOINT_READ:
1459     case GDB_WATCHPOINT_ACCESS:
1460         for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
1461             env = cpu->env_ptr;
1462             err = cpu_watchpoint_insert(env, addr, len, xlat_gdb_type[type],
1463                                         NULL);
1464             if (err)
1465                 break;
1466         }
1467         return err;
1468 #endif
1469     default:
1470         return -ENOSYS;
1471     }
1472 }
1473
1474 static int gdb_breakpoint_remove(target_ulong addr, target_ulong len, int type)
1475 {
1476     CPUState *cpu;
1477     CPUArchState *env;
1478     int err = 0;
1479
1480     if (kvm_enabled()) {
1481         return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
1482     }
1483
1484     switch (type) {
1485     case GDB_BREAKPOINT_SW:
1486     case GDB_BREAKPOINT_HW:
1487         for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
1488             env = cpu->env_ptr;
1489             err = cpu_breakpoint_remove(env, addr, BP_GDB);
1490             if (err)
1491                 break;
1492         }
1493         return err;
1494 #ifndef CONFIG_USER_ONLY
1495     case GDB_WATCHPOINT_WRITE:
1496     case GDB_WATCHPOINT_READ:
1497     case GDB_WATCHPOINT_ACCESS:
1498         for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
1499             env = cpu->env_ptr;
1500             err = cpu_watchpoint_remove(env, addr, len, xlat_gdb_type[type]);
1501             if (err)
1502                 break;
1503         }
1504         return err;
1505 #endif
1506     default:
1507         return -ENOSYS;
1508     }
1509 }
1510
1511 static void gdb_breakpoint_remove_all(void)
1512 {
1513     CPUState *cpu;
1514     CPUArchState *env;
1515
1516     if (kvm_enabled()) {
1517         kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
1518         return;
1519     }
1520
1521     for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
1522         env = cpu->env_ptr;
1523         cpu_breakpoint_remove_all(env, BP_GDB);
1524 #ifndef CONFIG_USER_ONLY
1525         cpu_watchpoint_remove_all(env, BP_GDB);
1526 #endif
1527     }
1528 }
1529
1530 static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
1531 {
1532     CPUState *cpu = s->c_cpu;
1533     CPUClass *cc = CPU_GET_CLASS(cpu);
1534
1535     cpu_synchronize_state(cpu);
1536     if (cc->set_pc) {
1537         cc->set_pc(cpu, pc);
1538     }
1539 }
1540
1541 static CPUState *find_cpu(uint32_t thread_id)
1542 {
1543     CPUState *cpu;
1544
1545     for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
1546         if (cpu_index(cpu) == thread_id) {
1547             return cpu;
1548         }
1549     }
1550
1551     return NULL;
1552 }
1553
1554 static int gdb_handle_packet(GDBState *s, const char *line_buf)
1555 {
1556     CPUState *cpu;
1557     const char *p;
1558     uint32_t thread;
1559     int ch, reg_size, type, res;
1560     char buf[MAX_PACKET_LENGTH];
1561     uint8_t mem_buf[MAX_PACKET_LENGTH];
1562     uint8_t *registers;
1563     target_ulong addr, len;
1564
1565 #ifdef DEBUG_GDB
1566     printf("command='%s'\n", line_buf);
1567 #endif
1568     p = line_buf;
1569     ch = *p++;
1570     switch(ch) {
1571     case '?':
1572         /* TODO: Make this return the correct value for user-mode.  */
1573         snprintf(buf, sizeof(buf), "T%02xthread:%02x;", GDB_SIGNAL_TRAP,
1574                  cpu_index(s->c_cpu));
1575         put_packet(s, buf);
1576         /* Remove all the breakpoints when this query is issued,
1577          * because gdb is doing and initial connect and the state
1578          * should be cleaned up.
1579          */
1580         gdb_breakpoint_remove_all();
1581         break;
1582     case 'c':
1583         if (*p != '\0') {
1584             addr = strtoull(p, (char **)&p, 16);
1585             gdb_set_cpu_pc(s, addr);
1586         }
1587         s->signal = 0;
1588         gdb_continue(s);
1589         return RS_IDLE;
1590     case 'C':
1591         s->signal = gdb_signal_to_target (strtoul(p, (char **)&p, 16));
1592         if (s->signal == -1)
1593             s->signal = 0;
1594         gdb_continue(s);
1595         return RS_IDLE;
1596     case 'v':
1597         if (strncmp(p, "Cont", 4) == 0) {
1598             int res_signal, res_thread;
1599
1600             p += 4;
1601             if (*p == '?') {
1602                 put_packet(s, "vCont;c;C;s;S");
1603                 break;
1604             }
1605             res = 0;
1606             res_signal = 0;
1607             res_thread = 0;
1608             while (*p) {
1609                 int action, signal;
1610
1611                 if (*p++ != ';') {
1612                     res = 0;
1613                     break;
1614                 }
1615                 action = *p++;
1616                 signal = 0;
1617                 if (action == 'C' || action == 'S') {
1618                     signal = strtoul(p, (char **)&p, 16);
1619                 } else if (action != 'c' && action != 's') {
1620                     res = 0;
1621                     break;
1622                 }
1623                 thread = 0;
1624                 if (*p == ':') {
1625                     thread = strtoull(p+1, (char **)&p, 16);
1626                 }
1627                 action = tolower(action);
1628                 if (res == 0 || (res == 'c' && action == 's')) {
1629                     res = action;
1630                     res_signal = signal;
1631                     res_thread = thread;
1632                 }
1633             }
1634             if (res) {
1635                 if (res_thread != -1 && res_thread != 0) {
1636                     cpu = find_cpu(res_thread);
1637                     if (cpu == NULL) {
1638                         put_packet(s, "E22");
1639                         break;
1640                     }
1641                     s->c_cpu = cpu;
1642                 }
1643                 if (res == 's') {
1644                     cpu_single_step(s->c_cpu, sstep_flags);
1645                 }
1646                 s->signal = res_signal;
1647                 gdb_continue(s);
1648                 return RS_IDLE;
1649             }
1650             break;
1651         } else {
1652             goto unknown_command;
1653         }
1654     case 'k':
1655 #ifdef CONFIG_USER_ONLY
1656         /* Kill the target */
1657         fprintf(stderr, "\nQEMU: Terminated via GDBstub\n");
1658         exit(0);
1659 #endif
1660     case 'D':
1661         /* Detach packet */
1662         gdb_breakpoint_remove_all();
1663         gdb_syscall_mode = GDB_SYS_DISABLED;
1664         gdb_continue(s);
1665         put_packet(s, "OK");
1666         break;
1667     case 's':
1668         if (*p != '\0') {
1669             addr = strtoull(p, (char **)&p, 16);
1670             gdb_set_cpu_pc(s, addr);
1671         }
1672         cpu_single_step(s->c_cpu, sstep_flags);
1673         gdb_continue(s);
1674         return RS_IDLE;
1675     case 'F':
1676         {
1677             target_ulong ret;
1678             target_ulong err;
1679
1680             ret = strtoull(p, (char **)&p, 16);
1681             if (*p == ',') {
1682                 p++;
1683                 err = strtoull(p, (char **)&p, 16);
1684             } else {
1685                 err = 0;
1686             }
1687             if (*p == ',')
1688                 p++;
1689             type = *p;
1690             if (s->current_syscall_cb) {
1691                 s->current_syscall_cb(s->c_cpu, ret, err);
1692                 s->current_syscall_cb = NULL;
1693             }
1694             if (type == 'C') {
1695                 put_packet(s, "T02");
1696             } else {
1697                 gdb_continue(s);
1698             }
1699         }
1700         break;
1701     case 'g':
1702         cpu_synchronize_state(s->g_cpu);
1703         len = 0;
1704         for (addr = 0; addr < s->g_cpu->gdb_num_regs; addr++) {
1705             reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);
1706             len += reg_size;
1707         }
1708         memtohex(buf, mem_buf, len);
1709         put_packet(s, buf);
1710         break;
1711     case 'G':
1712         cpu_synchronize_state(s->g_cpu);
1713         registers = mem_buf;
1714         len = strlen(p) / 2;
1715         hextomem((uint8_t *)registers, p, len);
1716         for (addr = 0; addr < s->g_cpu->gdb_num_regs && len > 0; addr++) {
1717             reg_size = gdb_write_register(s->g_cpu, registers, addr);
1718             len -= reg_size;
1719             registers += reg_size;
1720         }
1721         put_packet(s, "OK");
1722         break;
1723     case 'm':
1724         addr = strtoull(p, (char **)&p, 16);
1725         if (*p == ',')
1726             p++;
1727         len = strtoull(p, NULL, 16);
1728         if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len, false) != 0) {
1729             put_packet (s, "E14");
1730         } else {
1731             memtohex(buf, mem_buf, len);
1732             put_packet(s, buf);
1733         }
1734         break;
1735     case 'M':
1736         addr = strtoull(p, (char **)&p, 16);
1737         if (*p == ',')
1738             p++;
1739         len = strtoull(p, (char **)&p, 16);
1740         if (*p == ':')
1741             p++;
1742         hextomem(mem_buf, p, len);
1743         if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len,
1744                                    true) != 0) {
1745             put_packet(s, "E14");
1746         } else {
1747             put_packet(s, "OK");
1748         }
1749         break;
1750     case 'p':
1751         /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
1752            This works, but can be very slow.  Anything new enough to
1753            understand XML also knows how to use this properly.  */
1754         if (!gdb_has_xml)
1755             goto unknown_command;
1756         addr = strtoull(p, (char **)&p, 16);
1757         reg_size = gdb_read_register(s->g_cpu, mem_buf, addr);
1758         if (reg_size) {
1759             memtohex(buf, mem_buf, reg_size);
1760             put_packet(s, buf);
1761         } else {
1762             put_packet(s, "E14");
1763         }
1764         break;
1765     case 'P':
1766         if (!gdb_has_xml)
1767             goto unknown_command;
1768         addr = strtoull(p, (char **)&p, 16);
1769         if (*p == '=')
1770             p++;
1771         reg_size = strlen(p) / 2;
1772         hextomem(mem_buf, p, reg_size);
1773         gdb_write_register(s->g_cpu, mem_buf, addr);
1774         put_packet(s, "OK");
1775         break;
1776     case 'Z':
1777     case 'z':
1778         type = strtoul(p, (char **)&p, 16);
1779         if (*p == ',')
1780             p++;
1781         addr = strtoull(p, (char **)&p, 16);
1782         if (*p == ',')
1783             p++;
1784         len = strtoull(p, (char **)&p, 16);
1785         if (ch == 'Z')
1786             res = gdb_breakpoint_insert(addr, len, type);
1787         else
1788             res = gdb_breakpoint_remove(addr, len, type);
1789         if (res >= 0)
1790              put_packet(s, "OK");
1791         else if (res == -ENOSYS)
1792             put_packet(s, "");
1793         else
1794             put_packet(s, "E22");
1795         break;
1796     case 'H':
1797         type = *p++;
1798         thread = strtoull(p, (char **)&p, 16);
1799         if (thread == -1 || thread == 0) {
1800             put_packet(s, "OK");
1801             break;
1802         }
1803         cpu = find_cpu(thread);
1804         if (cpu == NULL) {
1805             put_packet(s, "E22");
1806             break;
1807         }
1808         switch (type) {
1809         case 'c':
1810             s->c_cpu = cpu;
1811             put_packet(s, "OK");
1812             break;
1813         case 'g':
1814             s->g_cpu = cpu;
1815             put_packet(s, "OK");
1816             break;
1817         default:
1818              put_packet(s, "E22");
1819              break;
1820         }
1821         break;
1822     case 'T':
1823         thread = strtoull(p, (char **)&p, 16);
1824         cpu = find_cpu(thread);
1825
1826         if (cpu != NULL) {
1827             put_packet(s, "OK");
1828         } else {
1829             put_packet(s, "E22");
1830         }
1831         break;
1832     case 'q':
1833     case 'Q':
1834         /* parse any 'q' packets here */
1835         if (!strcmp(p,"qemu.sstepbits")) {
1836             /* Query Breakpoint bit definitions */
1837             snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1838                      SSTEP_ENABLE,
1839                      SSTEP_NOIRQ,
1840                      SSTEP_NOTIMER);
1841             put_packet(s, buf);
1842             break;
1843         } else if (strncmp(p,"qemu.sstep",10) == 0) {
1844             /* Display or change the sstep_flags */
1845             p += 10;
1846             if (*p != '=') {
1847                 /* Display current setting */
1848                 snprintf(buf, sizeof(buf), "0x%x", sstep_flags);
1849                 put_packet(s, buf);
1850                 break;
1851             }
1852             p++;
1853             type = strtoul(p, (char **)&p, 16);
1854             sstep_flags = type;
1855             put_packet(s, "OK");
1856             break;
1857         } else if (strcmp(p,"C") == 0) {
1858             /* "Current thread" remains vague in the spec, so always return
1859              *  the first CPU (gdb returns the first thread). */
1860             put_packet(s, "QC1");
1861             break;
1862         } else if (strcmp(p,"fThreadInfo") == 0) {
1863             s->query_cpu = first_cpu;
1864             goto report_cpuinfo;
1865         } else if (strcmp(p,"sThreadInfo") == 0) {
1866         report_cpuinfo:
1867             if (s->query_cpu) {
1868                 snprintf(buf, sizeof(buf), "m%x", cpu_index(s->query_cpu));
1869                 put_packet(s, buf);
1870                 s->query_cpu = s->query_cpu->next_cpu;
1871             } else
1872                 put_packet(s, "l");
1873             break;
1874         } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {
1875             thread = strtoull(p+16, (char **)&p, 16);
1876             cpu = find_cpu(thread);
1877             if (cpu != NULL) {
1878                 cpu_synchronize_state(cpu);
1879                 len = snprintf((char *)mem_buf, sizeof(mem_buf),
1880                                "CPU#%d [%s]", cpu->cpu_index,
1881                                cpu->halted ? "halted " : "running");
1882                 memtohex(buf, mem_buf, len);
1883                 put_packet(s, buf);
1884             }
1885             break;
1886         }
1887 #ifdef CONFIG_USER_ONLY
1888         else if (strncmp(p, "Offsets", 7) == 0) {
1889             CPUArchState *env = s->c_cpu->env_ptr;
1890             TaskState *ts = env->opaque;
1891
1892             snprintf(buf, sizeof(buf),
1893                      "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
1894                      ";Bss=" TARGET_ABI_FMT_lx,
1895                      ts->info->code_offset,
1896                      ts->info->data_offset,
1897                      ts->info->data_offset);
1898             put_packet(s, buf);
1899             break;
1900         }
1901 #else /* !CONFIG_USER_ONLY */
1902         else if (strncmp(p, "Rcmd,", 5) == 0) {
1903             int len = strlen(p + 5);
1904
1905             if ((len % 2) != 0) {
1906                 put_packet(s, "E01");
1907                 break;
1908             }
1909             hextomem(mem_buf, p + 5, len);
1910             len = len / 2;
1911             mem_buf[len++] = 0;
1912             qemu_chr_be_write(s->mon_chr, mem_buf, len);
1913             put_packet(s, "OK");
1914             break;
1915         }
1916 #endif /* !CONFIG_USER_ONLY */
1917         if (strncmp(p, "Supported", 9) == 0) {
1918             snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);
1919 #ifdef GDB_CORE_XML
1920             pstrcat(buf, sizeof(buf), ";qXfer:features:read+");
1921 #endif
1922             put_packet(s, buf);
1923             break;
1924         }
1925 #ifdef GDB_CORE_XML
1926         if (strncmp(p, "Xfer:features:read:", 19) == 0) {
1927             const char *xml;
1928             target_ulong total_len;
1929
1930             gdb_has_xml = 1;
1931             p += 19;
1932             xml = get_feature_xml(p, &p);
1933             if (!xml) {
1934                 snprintf(buf, sizeof(buf), "E00");
1935                 put_packet(s, buf);
1936                 break;
1937             }
1938
1939             if (*p == ':')
1940                 p++;
1941             addr = strtoul(p, (char **)&p, 16);
1942             if (*p == ',')
1943                 p++;
1944             len = strtoul(p, (char **)&p, 16);
1945
1946             total_len = strlen(xml);
1947             if (addr > total_len) {
1948                 snprintf(buf, sizeof(buf), "E00");
1949                 put_packet(s, buf);
1950                 break;
1951             }
1952             if (len > (MAX_PACKET_LENGTH - 5) / 2)
1953                 len = (MAX_PACKET_LENGTH - 5) / 2;
1954             if (len < total_len - addr) {
1955                 buf[0] = 'm';
1956                 len = memtox(buf + 1, xml + addr, len);
1957             } else {
1958                 buf[0] = 'l';
1959                 len = memtox(buf + 1, xml + addr, total_len - addr);
1960             }
1961             put_packet_binary(s, buf, len + 1);
1962             break;
1963         }
1964 #endif
1965         /* Unrecognised 'q' command.  */
1966         goto unknown_command;
1967
1968     default:
1969     unknown_command:
1970         /* put empty packet */
1971         buf[0] = '\0';
1972         put_packet(s, buf);
1973         break;
1974     }
1975     return RS_IDLE;
1976 }
1977
1978 void gdb_set_stop_cpu(CPUState *cpu)
1979 {
1980     gdbserver_state->c_cpu = cpu;
1981     gdbserver_state->g_cpu = cpu;
1982 }
1983
1984 #ifndef CONFIG_USER_ONLY
1985 static void gdb_vm_state_change(void *opaque, int running, RunState state)
1986 {
1987     GDBState *s = gdbserver_state;
1988     CPUArchState *env = s->c_cpu->env_ptr;
1989     CPUState *cpu = s->c_cpu;
1990     char buf[256];
1991     const char *type;
1992     int ret;
1993
1994     if (running || s->state == RS_INACTIVE) {
1995         return;
1996     }
1997     /* Is there a GDB syscall waiting to be sent?  */
1998     if (s->current_syscall_cb) {
1999         put_packet(s, s->syscall_buf);
2000         return;
2001     }
2002     switch (state) {
2003     case RUN_STATE_DEBUG:
2004         if (env->watchpoint_hit) {
2005             switch (env->watchpoint_hit->flags & BP_MEM_ACCESS) {
2006             case BP_MEM_READ:
2007                 type = "r";
2008                 break;
2009             case BP_MEM_ACCESS:
2010                 type = "a";
2011                 break;
2012             default:
2013                 type = "";
2014                 break;
2015             }
2016             snprintf(buf, sizeof(buf),
2017                      "T%02xthread:%02x;%swatch:" TARGET_FMT_lx ";",
2018                      GDB_SIGNAL_TRAP, cpu_index(cpu), type,
2019                      env->watchpoint_hit->vaddr);
2020             env->watchpoint_hit = NULL;
2021             goto send_packet;
2022         }
2023         tb_flush(env);
2024         ret = GDB_SIGNAL_TRAP;
2025         break;
2026     case RUN_STATE_PAUSED:
2027         ret = GDB_SIGNAL_INT;
2028         break;
2029     case RUN_STATE_SHUTDOWN:
2030         ret = GDB_SIGNAL_QUIT;
2031         break;
2032     case RUN_STATE_IO_ERROR:
2033         ret = GDB_SIGNAL_IO;
2034         break;
2035     case RUN_STATE_WATCHDOG:
2036         ret = GDB_SIGNAL_ALRM;
2037         break;
2038     case RUN_STATE_INTERNAL_ERROR:
2039         ret = GDB_SIGNAL_ABRT;
2040         break;
2041     case RUN_STATE_SAVE_VM:
2042     case RUN_STATE_RESTORE_VM:
2043         return;
2044     case RUN_STATE_FINISH_MIGRATE:
2045         ret = GDB_SIGNAL_XCPU;
2046         break;
2047     default:
2048         ret = GDB_SIGNAL_UNKNOWN;
2049         break;
2050     }
2051     snprintf(buf, sizeof(buf), "T%02xthread:%02x;", ret, cpu_index(cpu));
2052
2053 send_packet:
2054     put_packet(s, buf);
2055
2056     /* disable single step if it was enabled */
2057     cpu_single_step(cpu, 0);
2058 }
2059 #endif
2060
2061 /* Send a gdb syscall request.
2062    This accepts limited printf-style format specifiers, specifically:
2063     %x  - target_ulong argument printed in hex.
2064     %lx - 64-bit argument printed in hex.
2065     %s  - string pointer (target_ulong) and length (int) pair.  */
2066 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
2067 {
2068     va_list va;
2069     char *p;
2070     char *p_end;
2071     target_ulong addr;
2072     uint64_t i64;
2073     GDBState *s;
2074
2075     s = gdbserver_state;
2076     if (!s)
2077         return;
2078     s->current_syscall_cb = cb;
2079 #ifndef CONFIG_USER_ONLY
2080     vm_stop(RUN_STATE_DEBUG);
2081 #endif
2082     va_start(va, fmt);
2083     p = s->syscall_buf;
2084     p_end = &s->syscall_buf[sizeof(s->syscall_buf)];
2085     *(p++) = 'F';
2086     while (*fmt) {
2087         if (*fmt == '%') {
2088             fmt++;
2089             switch (*fmt++) {
2090             case 'x':
2091                 addr = va_arg(va, target_ulong);
2092                 p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
2093                 break;
2094             case 'l':
2095                 if (*(fmt++) != 'x')
2096                     goto bad_format;
2097                 i64 = va_arg(va, uint64_t);
2098                 p += snprintf(p, p_end - p, "%" PRIx64, i64);
2099                 break;
2100             case 's':
2101                 addr = va_arg(va, target_ulong);
2102                 p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
2103                               addr, va_arg(va, int));
2104                 break;
2105             default:
2106             bad_format:
2107                 fprintf(stderr, "gdbstub: Bad syscall format string '%s'\n",
2108                         fmt - 1);
2109                 break;
2110             }
2111         } else {
2112             *(p++) = *(fmt++);
2113         }
2114     }
2115     *p = 0;
2116     va_end(va);
2117 #ifdef CONFIG_USER_ONLY
2118     put_packet(s, s->syscall_buf);
2119     gdb_handlesig(s->c_cpu, 0);
2120 #else
2121     /* In this case wait to send the syscall packet until notification that
2122        the CPU has stopped.  This must be done because if the packet is sent
2123        now the reply from the syscall request could be received while the CPU
2124        is still in the running state, which can cause packets to be dropped
2125        and state transition 'T' packets to be sent while the syscall is still
2126        being processed.  */
2127     cpu_exit(s->c_cpu);
2128 #endif
2129 }
2130
2131 static void gdb_read_byte(GDBState *s, int ch)
2132 {
2133     int i, csum;
2134     uint8_t reply;
2135
2136 #ifndef CONFIG_USER_ONLY
2137     if (s->last_packet_len) {
2138         /* Waiting for a response to the last packet.  If we see the start
2139            of a new command then abandon the previous response.  */
2140         if (ch == '-') {
2141 #ifdef DEBUG_GDB
2142             printf("Got NACK, retransmitting\n");
2143 #endif
2144             put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
2145         }
2146 #ifdef DEBUG_GDB
2147         else if (ch == '+')
2148             printf("Got ACK\n");
2149         else
2150             printf("Got '%c' when expecting ACK/NACK\n", ch);
2151 #endif
2152         if (ch == '+' || ch == '$')
2153             s->last_packet_len = 0;
2154         if (ch != '$')
2155             return;
2156     }
2157     if (runstate_is_running()) {
2158         /* when the CPU is running, we cannot do anything except stop
2159            it when receiving a char */
2160         vm_stop(RUN_STATE_PAUSED);
2161     } else
2162 #endif
2163     {
2164         switch(s->state) {
2165         case RS_IDLE:
2166             if (ch == '$') {
2167                 s->line_buf_index = 0;
2168                 s->state = RS_GETLINE;
2169             }
2170             break;
2171         case RS_GETLINE:
2172             if (ch == '#') {
2173             s->state = RS_CHKSUM1;
2174             } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
2175                 s->state = RS_IDLE;
2176             } else {
2177             s->line_buf[s->line_buf_index++] = ch;
2178             }
2179             break;
2180         case RS_CHKSUM1:
2181             s->line_buf[s->line_buf_index] = '\0';
2182             s->line_csum = fromhex(ch) << 4;
2183             s->state = RS_CHKSUM2;
2184             break;
2185         case RS_CHKSUM2:
2186             s->line_csum |= fromhex(ch);
2187             csum = 0;
2188             for(i = 0; i < s->line_buf_index; i++) {
2189                 csum += s->line_buf[i];
2190             }
2191             if (s->line_csum != (csum & 0xff)) {
2192                 reply = '-';
2193                 put_buffer(s, &reply, 1);
2194                 s->state = RS_IDLE;
2195             } else {
2196                 reply = '+';
2197                 put_buffer(s, &reply, 1);
2198                 s->state = gdb_handle_packet(s, s->line_buf);
2199             }
2200             break;
2201         default:
2202             abort();
2203         }
2204     }
2205 }
2206
2207 /* Tell the remote gdb that the process has exited.  */
2208 void gdb_exit(CPUArchState *env, int code)
2209 {
2210   GDBState *s;
2211   char buf[4];
2212
2213   s = gdbserver_state;
2214   if (!s) {
2215       return;
2216   }
2217 #ifdef CONFIG_USER_ONLY
2218   if (gdbserver_fd < 0 || s->fd < 0) {
2219       return;
2220   }
2221 #endif
2222
2223   snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
2224   put_packet(s, buf);
2225
2226 #ifndef CONFIG_USER_ONLY
2227   if (s->chr) {
2228       qemu_chr_delete(s->chr);
2229   }
2230 #endif
2231 }
2232
2233 #ifdef CONFIG_USER_ONLY
2234 int
2235 gdb_queuesig (void)
2236 {
2237     GDBState *s;
2238
2239     s = gdbserver_state;
2240
2241     if (gdbserver_fd < 0 || s->fd < 0)
2242         return 0;
2243     else
2244         return 1;
2245 }
2246
2247 int
2248 gdb_handlesig(CPUState *cpu, int sig)
2249 {
2250     CPUArchState *env = cpu->env_ptr;
2251     GDBState *s;
2252     char buf[256];
2253     int n;
2254
2255     s = gdbserver_state;
2256     if (gdbserver_fd < 0 || s->fd < 0) {
2257         return sig;
2258     }
2259
2260     /* disable single step if it was enabled */
2261     cpu_single_step(cpu, 0);
2262     tb_flush(env);
2263
2264     if (sig != 0) {
2265         snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
2266         put_packet(s, buf);
2267     }
2268     /* put_packet() might have detected that the peer terminated the
2269        connection.  */
2270     if (s->fd < 0) {
2271         return sig;
2272     }
2273
2274     sig = 0;
2275     s->state = RS_IDLE;
2276     s->running_state = 0;
2277     while (s->running_state == 0) {
2278         n = read(s->fd, buf, 256);
2279         if (n > 0) {
2280             int i;
2281
2282             for (i = 0; i < n; i++) {
2283                 gdb_read_byte(s, buf[i]);
2284             }
2285         } else if (n == 0 || errno != EAGAIN) {
2286             /* XXX: Connection closed.  Should probably wait for another
2287                connection before continuing.  */
2288             return sig;
2289         }
2290     }
2291     sig = s->signal;
2292     s->signal = 0;
2293     return sig;
2294 }
2295
2296 /* Tell the remote gdb that the process has exited due to SIG.  */
2297 void gdb_signalled(CPUArchState *env, int sig)
2298 {
2299     GDBState *s;
2300     char buf[4];
2301
2302     s = gdbserver_state;
2303     if (gdbserver_fd < 0 || s->fd < 0) {
2304         return;
2305     }
2306
2307     snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
2308     put_packet(s, buf);
2309 }
2310
2311 static void gdb_accept(void)
2312 {
2313     GDBState *s;
2314     struct sockaddr_in sockaddr;
2315     socklen_t len;
2316     int fd;
2317
2318     for(;;) {
2319         len = sizeof(sockaddr);
2320         fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
2321         if (fd < 0 && errno != EINTR) {
2322             perror("accept");
2323             return;
2324         } else if (fd >= 0) {
2325 #ifndef _WIN32
2326             fcntl(fd, F_SETFD, FD_CLOEXEC);
2327 #endif
2328             break;
2329         }
2330     }
2331
2332     /* set short latency */
2333     socket_set_nodelay(fd);
2334
2335     s = g_malloc0(sizeof(GDBState));
2336     s->c_cpu = first_cpu;
2337     s->g_cpu = first_cpu;
2338     s->fd = fd;
2339     gdb_has_xml = 0;
2340
2341     gdbserver_state = s;
2342
2343     fcntl(fd, F_SETFL, O_NONBLOCK);
2344 }
2345
2346 static int gdbserver_open(int port)
2347 {
2348     struct sockaddr_in sockaddr;
2349     int fd, val, ret;
2350
2351     fd = socket(PF_INET, SOCK_STREAM, 0);
2352     if (fd < 0) {
2353         perror("socket");
2354         return -1;
2355     }
2356 #ifndef _WIN32
2357     fcntl(fd, F_SETFD, FD_CLOEXEC);
2358 #endif
2359
2360     /* allow fast reuse */
2361     val = 1;
2362     qemu_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
2363
2364     sockaddr.sin_family = AF_INET;
2365     sockaddr.sin_port = htons(port);
2366     sockaddr.sin_addr.s_addr = 0;
2367     ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
2368     if (ret < 0) {
2369         perror("bind");
2370         close(fd);
2371         return -1;
2372     }
2373     ret = listen(fd, 0);
2374     if (ret < 0) {
2375         perror("listen");
2376         close(fd);
2377         return -1;
2378     }
2379     return fd;
2380 }
2381
2382 int gdbserver_start(int port)
2383 {
2384     gdbserver_fd = gdbserver_open(port);
2385     if (gdbserver_fd < 0)
2386         return -1;
2387     /* accept connections */
2388     gdb_accept();
2389     return 0;
2390 }
2391
2392 /* Disable gdb stub for child processes.  */
2393 void gdbserver_fork(CPUArchState *env)
2394 {
2395     GDBState *s = gdbserver_state;
2396     if (gdbserver_fd < 0 || s->fd < 0)
2397       return;
2398     close(s->fd);
2399     s->fd = -1;
2400     cpu_breakpoint_remove_all(env, BP_GDB);
2401     cpu_watchpoint_remove_all(env, BP_GDB);
2402 }
2403 #else
2404 static int gdb_chr_can_receive(void *opaque)
2405 {
2406   /* We can handle an arbitrarily large amount of data.
2407    Pick the maximum packet size, which is as good as anything.  */
2408   return MAX_PACKET_LENGTH;
2409 }
2410
2411 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
2412 {
2413     int i;
2414
2415     for (i = 0; i < size; i++) {
2416         gdb_read_byte(gdbserver_state, buf[i]);
2417     }
2418 }
2419
2420 static void gdb_chr_event(void *opaque, int event)
2421 {
2422     switch (event) {
2423     case CHR_EVENT_OPENED:
2424         vm_stop(RUN_STATE_PAUSED);
2425         gdb_has_xml = 0;
2426         break;
2427     default:
2428         break;
2429     }
2430 }
2431
2432 static void gdb_monitor_output(GDBState *s, const char *msg, int len)
2433 {
2434     char buf[MAX_PACKET_LENGTH];
2435
2436     buf[0] = 'O';
2437     if (len > (MAX_PACKET_LENGTH/2) - 1)
2438         len = (MAX_PACKET_LENGTH/2) - 1;
2439     memtohex(buf + 1, (uint8_t *)msg, len);
2440     put_packet(s, buf);
2441 }
2442
2443 static int gdb_monitor_write(CharDriverState *chr, const uint8_t *buf, int len)
2444 {
2445     const char *p = (const char *)buf;
2446     int max_sz;
2447
2448     max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
2449     for (;;) {
2450         if (len <= max_sz) {
2451             gdb_monitor_output(gdbserver_state, p, len);
2452             break;
2453         }
2454         gdb_monitor_output(gdbserver_state, p, max_sz);
2455         p += max_sz;
2456         len -= max_sz;
2457     }
2458     return len;
2459 }
2460
2461 #ifndef _WIN32
2462 static void gdb_sigterm_handler(int signal)
2463 {
2464     if (runstate_is_running()) {
2465         vm_stop(RUN_STATE_PAUSED);
2466     }
2467 }
2468 #endif
2469
2470 int gdbserver_start(const char *device)
2471 {
2472     GDBState *s;
2473     char gdbstub_device_name[128];
2474     CharDriverState *chr = NULL;
2475     CharDriverState *mon_chr;
2476
2477     if (!device)
2478         return -1;
2479     if (strcmp(device, "none") != 0) {
2480         if (strstart(device, "tcp:", NULL)) {
2481             /* enforce required TCP attributes */
2482             snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
2483                      "%s,nowait,nodelay,server", device);
2484             device = gdbstub_device_name;
2485         }
2486 #ifndef _WIN32
2487         else if (strcmp(device, "stdio") == 0) {
2488             struct sigaction act;
2489
2490             memset(&act, 0, sizeof(act));
2491             act.sa_handler = gdb_sigterm_handler;
2492             sigaction(SIGINT, &act, NULL);
2493         }
2494 #endif
2495         chr = qemu_chr_new("gdb", device, NULL);
2496         if (!chr)
2497             return -1;
2498
2499         qemu_chr_fe_claim_no_fail(chr);
2500         qemu_chr_add_handlers(chr, gdb_chr_can_receive, gdb_chr_receive,
2501                               gdb_chr_event, NULL);
2502     }
2503
2504     s = gdbserver_state;
2505     if (!s) {
2506         s = g_malloc0(sizeof(GDBState));
2507         gdbserver_state = s;
2508
2509         qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
2510
2511         /* Initialize a monitor terminal for gdb */
2512         mon_chr = g_malloc0(sizeof(*mon_chr));
2513         mon_chr->chr_write = gdb_monitor_write;
2514         monitor_init(mon_chr, 0);
2515     } else {
2516         if (s->chr)
2517             qemu_chr_delete(s->chr);
2518         mon_chr = s->mon_chr;
2519         memset(s, 0, sizeof(GDBState));
2520     }
2521     s->c_cpu = first_cpu;
2522     s->g_cpu = first_cpu;
2523     s->chr = chr;
2524     s->state = chr ? RS_IDLE : RS_INACTIVE;
2525     s->mon_chr = mon_chr;
2526     s->current_syscall_cb = NULL;
2527
2528     return 0;
2529 }
2530 #endif