gdbstub: x86: Refactor register access
[qemu] / 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, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA  02110-1301 USA
19  */
20 #include "config.h"
21 #include "qemu-common.h"
22 #ifdef CONFIG_USER_ONLY
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <stdarg.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30
31 #include "qemu.h"
32 #else
33 #include "monitor.h"
34 #include "qemu-char.h"
35 #include "sysemu.h"
36 #include "gdbstub.h"
37 #endif
38
39 #define MAX_PACKET_LENGTH 4096
40
41 #include "qemu_socket.h"
42 #include "kvm.h"
43
44
45 enum {
46     GDB_SIGNAL_0 = 0,
47     GDB_SIGNAL_INT = 2,
48     GDB_SIGNAL_TRAP = 5,
49     GDB_SIGNAL_UNKNOWN = 143
50 };
51
52 #ifdef CONFIG_USER_ONLY
53
54 /* Map target signal numbers to GDB protocol signal numbers and vice
55  * versa.  For user emulation's currently supported systems, we can
56  * assume most signals are defined.
57  */
58
59 static int gdb_signal_table[] = {
60     0,
61     TARGET_SIGHUP,
62     TARGET_SIGINT,
63     TARGET_SIGQUIT,
64     TARGET_SIGILL,
65     TARGET_SIGTRAP,
66     TARGET_SIGABRT,
67     -1, /* SIGEMT */
68     TARGET_SIGFPE,
69     TARGET_SIGKILL,
70     TARGET_SIGBUS,
71     TARGET_SIGSEGV,
72     TARGET_SIGSYS,
73     TARGET_SIGPIPE,
74     TARGET_SIGALRM,
75     TARGET_SIGTERM,
76     TARGET_SIGURG,
77     TARGET_SIGSTOP,
78     TARGET_SIGTSTP,
79     TARGET_SIGCONT,
80     TARGET_SIGCHLD,
81     TARGET_SIGTTIN,
82     TARGET_SIGTTOU,
83     TARGET_SIGIO,
84     TARGET_SIGXCPU,
85     TARGET_SIGXFSZ,
86     TARGET_SIGVTALRM,
87     TARGET_SIGPROF,
88     TARGET_SIGWINCH,
89     -1, /* SIGLOST */
90     TARGET_SIGUSR1,
91     TARGET_SIGUSR2,
92 #ifdef TARGET_SIGPWR
93     TARGET_SIGPWR,
94 #else
95     -1,
96 #endif
97     -1, /* SIGPOLL */
98     -1,
99     -1,
100     -1,
101     -1,
102     -1,
103     -1,
104     -1,
105     -1,
106     -1,
107     -1,
108     -1,
109 #ifdef __SIGRTMIN
110     __SIGRTMIN + 1,
111     __SIGRTMIN + 2,
112     __SIGRTMIN + 3,
113     __SIGRTMIN + 4,
114     __SIGRTMIN + 5,
115     __SIGRTMIN + 6,
116     __SIGRTMIN + 7,
117     __SIGRTMIN + 8,
118     __SIGRTMIN + 9,
119     __SIGRTMIN + 10,
120     __SIGRTMIN + 11,
121     __SIGRTMIN + 12,
122     __SIGRTMIN + 13,
123     __SIGRTMIN + 14,
124     __SIGRTMIN + 15,
125     __SIGRTMIN + 16,
126     __SIGRTMIN + 17,
127     __SIGRTMIN + 18,
128     __SIGRTMIN + 19,
129     __SIGRTMIN + 20,
130     __SIGRTMIN + 21,
131     __SIGRTMIN + 22,
132     __SIGRTMIN + 23,
133     __SIGRTMIN + 24,
134     __SIGRTMIN + 25,
135     __SIGRTMIN + 26,
136     __SIGRTMIN + 27,
137     __SIGRTMIN + 28,
138     __SIGRTMIN + 29,
139     __SIGRTMIN + 30,
140     __SIGRTMIN + 31,
141     -1, /* SIGCANCEL */
142     __SIGRTMIN,
143     __SIGRTMIN + 32,
144     __SIGRTMIN + 33,
145     __SIGRTMIN + 34,
146     __SIGRTMIN + 35,
147     __SIGRTMIN + 36,
148     __SIGRTMIN + 37,
149     __SIGRTMIN + 38,
150     __SIGRTMIN + 39,
151     __SIGRTMIN + 40,
152     __SIGRTMIN + 41,
153     __SIGRTMIN + 42,
154     __SIGRTMIN + 43,
155     __SIGRTMIN + 44,
156     __SIGRTMIN + 45,
157     __SIGRTMIN + 46,
158     __SIGRTMIN + 47,
159     __SIGRTMIN + 48,
160     __SIGRTMIN + 49,
161     __SIGRTMIN + 50,
162     __SIGRTMIN + 51,
163     __SIGRTMIN + 52,
164     __SIGRTMIN + 53,
165     __SIGRTMIN + 54,
166     __SIGRTMIN + 55,
167     __SIGRTMIN + 56,
168     __SIGRTMIN + 57,
169     __SIGRTMIN + 58,
170     __SIGRTMIN + 59,
171     __SIGRTMIN + 60,
172     __SIGRTMIN + 61,
173     __SIGRTMIN + 62,
174     __SIGRTMIN + 63,
175     __SIGRTMIN + 64,
176     __SIGRTMIN + 65,
177     __SIGRTMIN + 66,
178     __SIGRTMIN + 67,
179     __SIGRTMIN + 68,
180     __SIGRTMIN + 69,
181     __SIGRTMIN + 70,
182     __SIGRTMIN + 71,
183     __SIGRTMIN + 72,
184     __SIGRTMIN + 73,
185     __SIGRTMIN + 74,
186     __SIGRTMIN + 75,
187     __SIGRTMIN + 76,
188     __SIGRTMIN + 77,
189     __SIGRTMIN + 78,
190     __SIGRTMIN + 79,
191     __SIGRTMIN + 80,
192     __SIGRTMIN + 81,
193     __SIGRTMIN + 82,
194     __SIGRTMIN + 83,
195     __SIGRTMIN + 84,
196     __SIGRTMIN + 85,
197     __SIGRTMIN + 86,
198     __SIGRTMIN + 87,
199     __SIGRTMIN + 88,
200     __SIGRTMIN + 89,
201     __SIGRTMIN + 90,
202     __SIGRTMIN + 91,
203     __SIGRTMIN + 92,
204     __SIGRTMIN + 93,
205     __SIGRTMIN + 94,
206     __SIGRTMIN + 95,
207     -1, /* SIGINFO */
208     -1, /* UNKNOWN */
209     -1, /* DEFAULT */
210     -1,
211     -1,
212     -1,
213     -1,
214     -1,
215     -1
216 #endif
217 };
218 #else
219 /* In system mode we only need SIGINT and SIGTRAP; other signals
220    are not yet supported.  */
221
222 enum {
223     TARGET_SIGINT = 2,
224     TARGET_SIGTRAP = 5
225 };
226
227 static int gdb_signal_table[] = {
228     -1,
229     -1,
230     TARGET_SIGINT,
231     -1,
232     -1,
233     TARGET_SIGTRAP
234 };
235 #endif
236
237 #ifdef CONFIG_USER_ONLY
238 static int target_signal_to_gdb (int sig)
239 {
240     int i;
241     for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
242         if (gdb_signal_table[i] == sig)
243             return i;
244     return GDB_SIGNAL_UNKNOWN;
245 }
246 #endif
247
248 static int gdb_signal_to_target (int sig)
249 {
250     if (sig < ARRAY_SIZE (gdb_signal_table))
251         return gdb_signal_table[sig];
252     else
253         return -1;
254 }
255
256 //#define DEBUG_GDB
257
258 typedef struct GDBRegisterState {
259     int base_reg;
260     int num_regs;
261     gdb_reg_cb get_reg;
262     gdb_reg_cb set_reg;
263     const char *xml;
264     struct GDBRegisterState *next;
265 } GDBRegisterState;
266
267 enum RSState {
268     RS_INACTIVE,
269     RS_IDLE,
270     RS_GETLINE,
271     RS_CHKSUM1,
272     RS_CHKSUM2,
273     RS_SYSCALL,
274 };
275 typedef struct GDBState {
276     CPUState *c_cpu; /* current CPU for step/continue ops */
277     CPUState *g_cpu; /* current CPU for other ops */
278     CPUState *query_cpu; /* for q{f|s}ThreadInfo */
279     enum RSState state; /* parsing state */
280     char line_buf[MAX_PACKET_LENGTH];
281     int line_buf_index;
282     int line_csum;
283     uint8_t last_packet[MAX_PACKET_LENGTH + 4];
284     int last_packet_len;
285     int signal;
286 #ifdef CONFIG_USER_ONLY
287     int fd;
288     int running_state;
289 #else
290     CharDriverState *chr;
291     CharDriverState *mon_chr;
292 #endif
293 } GDBState;
294
295 /* By default use no IRQs and no timers while single stepping so as to
296  * make single stepping like an ICE HW step.
297  */
298 static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
299
300 static GDBState *gdbserver_state;
301
302 /* This is an ugly hack to cope with both new and old gdb.
303    If gdb sends qXfer:features:read then assume we're talking to a newish
304    gdb that understands target descriptions.  */
305 static int gdb_has_xml;
306
307 #ifdef CONFIG_USER_ONLY
308 /* XXX: This is not thread safe.  Do we care?  */
309 static int gdbserver_fd = -1;
310
311 static int get_char(GDBState *s)
312 {
313     uint8_t ch;
314     int ret;
315
316     for(;;) {
317         ret = recv(s->fd, &ch, 1, 0);
318         if (ret < 0) {
319             if (errno == ECONNRESET)
320                 s->fd = -1;
321             if (errno != EINTR && errno != EAGAIN)
322                 return -1;
323         } else if (ret == 0) {
324             close(s->fd);
325             s->fd = -1;
326             return -1;
327         } else {
328             break;
329         }
330     }
331     return ch;
332 }
333 #endif
334
335 static gdb_syscall_complete_cb gdb_current_syscall_cb;
336
337 static enum {
338     GDB_SYS_UNKNOWN,
339     GDB_SYS_ENABLED,
340     GDB_SYS_DISABLED,
341 } gdb_syscall_mode;
342
343 /* If gdb is connected when the first semihosting syscall occurs then use
344    remote gdb syscalls.  Otherwise use native file IO.  */
345 int use_gdb_syscalls(void)
346 {
347     if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
348         gdb_syscall_mode = (gdbserver_state ? GDB_SYS_ENABLED
349                                             : GDB_SYS_DISABLED);
350     }
351     return gdb_syscall_mode == GDB_SYS_ENABLED;
352 }
353
354 /* Resume execution.  */
355 static inline void gdb_continue(GDBState *s)
356 {
357 #ifdef CONFIG_USER_ONLY
358     s->running_state = 1;
359 #else
360     vm_start();
361 #endif
362 }
363
364 static void put_buffer(GDBState *s, const uint8_t *buf, int len)
365 {
366 #ifdef CONFIG_USER_ONLY
367     int ret;
368
369     while (len > 0) {
370         ret = send(s->fd, buf, len, 0);
371         if (ret < 0) {
372             if (errno != EINTR && errno != EAGAIN)
373                 return;
374         } else {
375             buf += ret;
376             len -= ret;
377         }
378     }
379 #else
380     qemu_chr_write(s->chr, buf, len);
381 #endif
382 }
383
384 static inline int fromhex(int v)
385 {
386     if (v >= '0' && v <= '9')
387         return v - '0';
388     else if (v >= 'A' && v <= 'F')
389         return v - 'A' + 10;
390     else if (v >= 'a' && v <= 'f')
391         return v - 'a' + 10;
392     else
393         return 0;
394 }
395
396 static inline int tohex(int v)
397 {
398     if (v < 10)
399         return v + '0';
400     else
401         return v - 10 + 'a';
402 }
403
404 static void memtohex(char *buf, const uint8_t *mem, int len)
405 {
406     int i, c;
407     char *q;
408     q = buf;
409     for(i = 0; i < len; i++) {
410         c = mem[i];
411         *q++ = tohex(c >> 4);
412         *q++ = tohex(c & 0xf);
413     }
414     *q = '\0';
415 }
416
417 static void hextomem(uint8_t *mem, const char *buf, int len)
418 {
419     int i;
420
421     for(i = 0; i < len; i++) {
422         mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
423         buf += 2;
424     }
425 }
426
427 /* return -1 if error, 0 if OK */
428 static int put_packet_binary(GDBState *s, const char *buf, int len)
429 {
430     int csum, i;
431     uint8_t *p;
432
433     for(;;) {
434         p = s->last_packet;
435         *(p++) = '$';
436         memcpy(p, buf, len);
437         p += len;
438         csum = 0;
439         for(i = 0; i < len; i++) {
440             csum += buf[i];
441         }
442         *(p++) = '#';
443         *(p++) = tohex((csum >> 4) & 0xf);
444         *(p++) = tohex((csum) & 0xf);
445
446         s->last_packet_len = p - s->last_packet;
447         put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
448
449 #ifdef CONFIG_USER_ONLY
450         i = get_char(s);
451         if (i < 0)
452             return -1;
453         if (i == '+')
454             break;
455 #else
456         break;
457 #endif
458     }
459     return 0;
460 }
461
462 /* return -1 if error, 0 if OK */
463 static int put_packet(GDBState *s, const char *buf)
464 {
465 #ifdef DEBUG_GDB
466     printf("reply='%s'\n", buf);
467 #endif
468
469     return put_packet_binary(s, buf, strlen(buf));
470 }
471
472 /* The GDB remote protocol transfers values in target byte order.  This means
473    we can use the raw memory access routines to access the value buffer.
474    Conveniently, these also handle the case where the buffer is mis-aligned.
475  */
476 #define GET_REG8(val) do { \
477     stb_p(mem_buf, val); \
478     return 1; \
479     } while(0)
480 #define GET_REG16(val) do { \
481     stw_p(mem_buf, val); \
482     return 2; \
483     } while(0)
484 #define GET_REG32(val) do { \
485     stl_p(mem_buf, val); \
486     return 4; \
487     } while(0)
488 #define GET_REG64(val) do { \
489     stq_p(mem_buf, val); \
490     return 8; \
491     } while(0)
492
493 #if TARGET_LONG_BITS == 64
494 #define GET_REGL(val) GET_REG64(val)
495 #define ldtul_p(addr) ldq_p(addr)
496 #else
497 #define GET_REGL(val) GET_REG32(val)
498 #define ldtul_p(addr) ldl_p(addr)
499 #endif
500
501 #if defined(TARGET_I386)
502
503 #ifdef TARGET_X86_64
504 static const int gpr_map[16] = {
505     R_EAX, R_EBX, R_ECX, R_EDX, R_ESI, R_EDI, R_EBP, R_ESP,
506     8, 9, 10, 11, 12, 13, 14, 15
507 };
508 #else
509 static const int gpr_map[8] = {0, 1, 2, 3, 4, 5, 6, 7};
510 #endif
511
512 #define NUM_CORE_REGS (CPU_NB_REGS * 2 + 25)
513
514 #define IDX_IP_REG      CPU_NB_REGS
515 #define IDX_FLAGS_REG   (IDX_IP_REG + 1)
516 #define IDX_SEG_REGS    (IDX_FLAGS_REG + 1)
517 #define IDX_FP_REGS     (IDX_SEG_REGS + 6)
518 #define IDX_XMM_REGS    (IDX_FP_REGS + 16)
519 #define IDX_MXCSR_REG   (IDX_XMM_REGS + CPU_NB_REGS)
520
521 static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)
522 {
523     if (n < CPU_NB_REGS) {
524         GET_REGL(env->regs[gpr_map[n]]);
525     } else if (n >= IDX_FP_REGS && n < IDX_FP_REGS + 8) {
526 #ifdef USE_X86LDOUBLE
527         /* FIXME: byteswap float values - after fixing fpregs layout. */
528         memcpy(mem_buf, &env->fpregs[n - IDX_FP_REGS], 10);
529 #else
530         memset(mem_buf, 0, 10);
531 #endif
532         return 10;
533     } else if (n >= IDX_XMM_REGS && n < IDX_XMM_REGS + CPU_NB_REGS) {
534         n -= IDX_XMM_REGS;
535         stq_p(mem_buf, env->xmm_regs[n].XMM_Q(0));
536         stq_p(mem_buf + 8, env->xmm_regs[n].XMM_Q(1));
537         return 16;
538     } else {
539         switch (n) {
540         case IDX_IP_REG:    GET_REGL(env->eip);
541         case IDX_FLAGS_REG: GET_REG32(env->eflags);
542
543         case IDX_SEG_REGS:     GET_REG32(env->segs[R_CS].selector);
544         case IDX_SEG_REGS + 1: GET_REG32(env->segs[R_SS].selector);
545         case IDX_SEG_REGS + 2: GET_REG32(env->segs[R_DS].selector);
546         case IDX_SEG_REGS + 3: GET_REG32(env->segs[R_ES].selector);
547         case IDX_SEG_REGS + 4: GET_REG32(env->segs[R_FS].selector);
548         case IDX_SEG_REGS + 5: GET_REG32(env->segs[R_GS].selector);
549
550         case IDX_FP_REGS + 8:  GET_REG32(env->fpuc);
551         case IDX_FP_REGS + 9:  GET_REG32((env->fpus & ~0x3800) |
552                                          (env->fpstt & 0x7) << 11);
553         case IDX_FP_REGS + 10: GET_REG32(0); /* ftag */
554         case IDX_FP_REGS + 11: GET_REG32(0); /* fiseg */
555         case IDX_FP_REGS + 12: GET_REG32(0); /* fioff */
556         case IDX_FP_REGS + 13: GET_REG32(0); /* foseg */
557         case IDX_FP_REGS + 14: GET_REG32(0); /* fooff */
558         case IDX_FP_REGS + 15: GET_REG32(0); /* fop */
559
560         case IDX_MXCSR_REG: GET_REG32(env->mxcsr);
561         }
562     }
563     return 0;
564 }
565
566 static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)
567 {
568     uint32_t tmp;
569
570     if (n < CPU_NB_REGS) {
571         env->regs[gpr_map[n]] = ldtul_p(mem_buf);
572         return sizeof(target_ulong);
573     } else if (n >= IDX_FP_REGS && n < IDX_FP_REGS + 8) {
574 #ifdef USE_X86LDOUBLE
575         /* FIXME: byteswap float values - after fixing fpregs layout. */
576         memcpy(&env->fpregs[n - IDX_FP_REGS], mem_buf, 10);
577 #endif
578         return 10;
579     } else if (n >= IDX_XMM_REGS && n < IDX_XMM_REGS + CPU_NB_REGS) {
580         n -= IDX_XMM_REGS;
581         env->xmm_regs[n].XMM_Q(0) = ldq_p(mem_buf);
582         env->xmm_regs[n].XMM_Q(1) = ldq_p(mem_buf + 8);
583         return 16;
584     } else {
585         switch (n) {
586         case IDX_IP_REG:
587             env->eip = ldtul_p(mem_buf);
588             return sizeof(target_ulong);
589         case IDX_FLAGS_REG:
590             env->eflags = ldl_p(mem_buf);
591             return 4;
592
593 #if defined(CONFIG_USER_ONLY)
594 #define LOAD_SEG(index, sreg)\
595             tmp = ldl_p(mem_buf);\
596             if (tmp != env->segs[sreg].selector)\
597                 cpu_x86_load_seg(env, sreg, tmp);\
598             return 4
599 #else
600 /* FIXME: Honor segment registers.  Needs to avoid raising an exception
601    when the selector is invalid.  */
602 #define LOAD_SEG(index, sreg) return 4
603 #endif
604         case IDX_SEG_REGS:     LOAD_SEG(10, R_CS);
605         case IDX_SEG_REGS + 1: LOAD_SEG(11, R_SS);
606         case IDX_SEG_REGS + 2: LOAD_SEG(12, R_DS);
607         case IDX_SEG_REGS + 3: LOAD_SEG(13, R_ES);
608         case IDX_SEG_REGS + 4: LOAD_SEG(14, R_FS);
609         case IDX_SEG_REGS + 5: LOAD_SEG(15, R_GS);
610
611         case IDX_FP_REGS + 8:
612             env->fpuc = ldl_p(mem_buf);
613             return 4;
614         case IDX_FP_REGS + 9:
615             tmp = ldl_p(mem_buf);
616             env->fpstt = (tmp >> 11) & 7;
617             env->fpus = tmp & ~0x3800;
618             return 4;
619         case IDX_FP_REGS + 10: /* ftag */  return 4;
620         case IDX_FP_REGS + 11: /* fiseg */ return 4;
621         case IDX_FP_REGS + 12: /* fioff */ return 4;
622         case IDX_FP_REGS + 13: /* foseg */ return 4;
623         case IDX_FP_REGS + 14: /* fooff */ return 4;
624         case IDX_FP_REGS + 15: /* fop */   return 4;
625
626         case IDX_MXCSR_REG:
627             env->mxcsr = ldl_p(mem_buf);
628             return 4;
629         }
630     }
631     /* Unrecognised register.  */
632     return 0;
633 }
634
635 #elif defined (TARGET_PPC)
636
637 /* Old gdb always expects FP registers.  Newer (xml-aware) gdb only
638    expects whatever the target description contains.  Due to a
639    historical mishap the FP registers appear in between core integer
640    regs and PC, MSR, CR, and so forth.  We hack round this by giving the
641    FP regs zero size when talking to a newer gdb.  */
642 #define NUM_CORE_REGS 71
643 #if defined (TARGET_PPC64)
644 #define GDB_CORE_XML "power64-core.xml"
645 #else
646 #define GDB_CORE_XML "power-core.xml"
647 #endif
648
649 static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)
650 {
651     if (n < 32) {
652         /* gprs */
653         GET_REGL(env->gpr[n]);
654     } else if (n < 64) {
655         /* fprs */
656         if (gdb_has_xml)
657             return 0;
658         stfq_p(mem_buf, env->fpr[n-32]);
659         return 8;
660     } else {
661         switch (n) {
662         case 64: GET_REGL(env->nip);
663         case 65: GET_REGL(env->msr);
664         case 66:
665             {
666                 uint32_t cr = 0;
667                 int i;
668                 for (i = 0; i < 8; i++)
669                     cr |= env->crf[i] << (32 - ((i + 1) * 4));
670                 GET_REG32(cr);
671             }
672         case 67: GET_REGL(env->lr);
673         case 68: GET_REGL(env->ctr);
674         case 69: GET_REGL(env->xer);
675         case 70:
676             {
677                 if (gdb_has_xml)
678                     return 0;
679                 GET_REG32(0); /* fpscr */
680             }
681         }
682     }
683     return 0;
684 }
685
686 static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)
687 {
688     if (n < 32) {
689         /* gprs */
690         env->gpr[n] = ldtul_p(mem_buf);
691         return sizeof(target_ulong);
692     } else if (n < 64) {
693         /* fprs */
694         if (gdb_has_xml)
695             return 0;
696         env->fpr[n-32] = ldfq_p(mem_buf);
697         return 8;
698     } else {
699         switch (n) {
700         case 64:
701             env->nip = ldtul_p(mem_buf);
702             return sizeof(target_ulong);
703         case 65:
704             ppc_store_msr(env, ldtul_p(mem_buf));
705             return sizeof(target_ulong);
706         case 66:
707             {
708                 uint32_t cr = ldl_p(mem_buf);
709                 int i;
710                 for (i = 0; i < 8; i++)
711                     env->crf[i] = (cr >> (32 - ((i + 1) * 4))) & 0xF;
712                 return 4;
713             }
714         case 67:
715             env->lr = ldtul_p(mem_buf);
716             return sizeof(target_ulong);
717         case 68:
718             env->ctr = ldtul_p(mem_buf);
719             return sizeof(target_ulong);
720         case 69:
721             env->xer = ldtul_p(mem_buf);
722             return sizeof(target_ulong);
723         case 70:
724             /* fpscr */
725             if (gdb_has_xml)
726                 return 0;
727             return 4;
728         }
729     }
730     return 0;
731 }
732
733 #elif defined (TARGET_SPARC)
734
735 #if defined(TARGET_SPARC64) && !defined(TARGET_ABI32)
736 #define NUM_CORE_REGS 86
737 #else
738 #define NUM_CORE_REGS 72
739 #endif
740
741 #ifdef TARGET_ABI32
742 #define GET_REGA(val) GET_REG32(val)
743 #else
744 #define GET_REGA(val) GET_REGL(val)
745 #endif
746
747 static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)
748 {
749     if (n < 8) {
750         /* g0..g7 */
751         GET_REGA(env->gregs[n]);
752     }
753     if (n < 32) {
754         /* register window */
755         GET_REGA(env->regwptr[n - 8]);
756     }
757 #if defined(TARGET_ABI32) || !defined(TARGET_SPARC64)
758     if (n < 64) {
759         /* fprs */
760         GET_REG32(*((uint32_t *)&env->fpr[n - 32]));
761     }
762     /* Y, PSR, WIM, TBR, PC, NPC, FPSR, CPSR */
763     switch (n) {
764     case 64: GET_REGA(env->y);
765     case 65: GET_REGA(GET_PSR(env));
766     case 66: GET_REGA(env->wim);
767     case 67: GET_REGA(env->tbr);
768     case 68: GET_REGA(env->pc);
769     case 69: GET_REGA(env->npc);
770     case 70: GET_REGA(env->fsr);
771     case 71: GET_REGA(0); /* csr */
772     default: GET_REGA(0);
773     }
774 #else
775     if (n < 64) {
776         /* f0-f31 */
777         GET_REG32(*((uint32_t *)&env->fpr[n - 32]));
778     }
779     if (n < 80) {
780         /* f32-f62 (double width, even numbers only) */
781         uint64_t val;
782
783         val = (uint64_t)*((uint32_t *)&env->fpr[(n - 64) * 2 + 32]) << 32;
784         val |= *((uint32_t *)&env->fpr[(n - 64) * 2 + 33]);
785         GET_REG64(val);
786     }
787     switch (n) {
788     case 80: GET_REGL(env->pc);
789     case 81: GET_REGL(env->npc);
790     case 82: GET_REGL(((uint64_t)GET_CCR(env) << 32) |
791                            ((env->asi & 0xff) << 24) |
792                            ((env->pstate & 0xfff) << 8) |
793                            GET_CWP64(env));
794     case 83: GET_REGL(env->fsr);
795     case 84: GET_REGL(env->fprs);
796     case 85: GET_REGL(env->y);
797     }
798 #endif
799     return 0;
800 }
801
802 static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)
803 {
804 #if defined(TARGET_ABI32)
805     abi_ulong tmp;
806
807     tmp = ldl_p(mem_buf);
808 #else
809     target_ulong tmp;
810
811     tmp = ldtul_p(mem_buf);
812 #endif
813
814     if (n < 8) {
815         /* g0..g7 */
816         env->gregs[n] = tmp;
817     } else if (n < 32) {
818         /* register window */
819         env->regwptr[n - 8] = tmp;
820     }
821 #if defined(TARGET_ABI32) || !defined(TARGET_SPARC64)
822     else if (n < 64) {
823         /* fprs */
824         *((uint32_t *)&env->fpr[n - 32]) = tmp;
825     } else {
826         /* Y, PSR, WIM, TBR, PC, NPC, FPSR, CPSR */
827         switch (n) {
828         case 64: env->y = tmp; break;
829         case 65: PUT_PSR(env, tmp); break;
830         case 66: env->wim = tmp; break;
831         case 67: env->tbr = tmp; break;
832         case 68: env->pc = tmp; break;
833         case 69: env->npc = tmp; break;
834         case 70: env->fsr = tmp; break;
835         default: return 0;
836         }
837     }
838     return 4;
839 #else
840     else if (n < 64) {
841         /* f0-f31 */
842         env->fpr[n] = ldfl_p(mem_buf);
843         return 4;
844     } else if (n < 80) {
845         /* f32-f62 (double width, even numbers only) */
846         *((uint32_t *)&env->fpr[(n - 64) * 2 + 32]) = tmp >> 32;
847         *((uint32_t *)&env->fpr[(n - 64) * 2 + 33]) = tmp;
848     } else {
849         switch (n) {
850         case 80: env->pc = tmp; break;
851         case 81: env->npc = tmp; break;
852         case 82:
853             PUT_CCR(env, tmp >> 32);
854             env->asi = (tmp >> 24) & 0xff;
855             env->pstate = (tmp >> 8) & 0xfff;
856             PUT_CWP64(env, tmp & 0xff);
857             break;
858         case 83: env->fsr = tmp; break;
859         case 84: env->fprs = tmp; break;
860         case 85: env->y = tmp; break;
861         default: return 0;
862         }
863     }
864     return 8;
865 #endif
866 }
867 #elif defined (TARGET_ARM)
868
869 /* Old gdb always expect FPA registers.  Newer (xml-aware) gdb only expect
870    whatever the target description contains.  Due to a historical mishap
871    the FPA registers appear in between core integer regs and the CPSR.
872    We hack round this by giving the FPA regs zero size when talking to a
873    newer gdb.  */
874 #define NUM_CORE_REGS 26
875 #define GDB_CORE_XML "arm-core.xml"
876
877 static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)
878 {
879     if (n < 16) {
880         /* Core integer register.  */
881         GET_REG32(env->regs[n]);
882     }
883     if (n < 24) {
884         /* FPA registers.  */
885         if (gdb_has_xml)
886             return 0;
887         memset(mem_buf, 0, 12);
888         return 12;
889     }
890     switch (n) {
891     case 24:
892         /* FPA status register.  */
893         if (gdb_has_xml)
894             return 0;
895         GET_REG32(0);
896     case 25:
897         /* CPSR */
898         GET_REG32(cpsr_read(env));
899     }
900     /* Unknown register.  */
901     return 0;
902 }
903
904 static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)
905 {
906     uint32_t tmp;
907
908     tmp = ldl_p(mem_buf);
909
910     /* Mask out low bit of PC to workaround gdb bugs.  This will probably
911        cause problems if we ever implement the Jazelle DBX extensions.  */
912     if (n == 15)
913         tmp &= ~1;
914
915     if (n < 16) {
916         /* Core integer register.  */
917         env->regs[n] = tmp;
918         return 4;
919     }
920     if (n < 24) { /* 16-23 */
921         /* FPA registers (ignored).  */
922         if (gdb_has_xml)
923             return 0;
924         return 12;
925     }
926     switch (n) {
927     case 24:
928         /* FPA status register (ignored).  */
929         if (gdb_has_xml)
930             return 0;
931         return 4;
932     case 25:
933         /* CPSR */
934         cpsr_write (env, tmp, 0xffffffff);
935         return 4;
936     }
937     /* Unknown register.  */
938     return 0;
939 }
940
941 #elif defined (TARGET_M68K)
942
943 #define NUM_CORE_REGS 18
944
945 #define GDB_CORE_XML "cf-core.xml"
946
947 static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)
948 {
949     if (n < 8) {
950         /* D0-D7 */
951         GET_REG32(env->dregs[n]);
952     } else if (n < 16) {
953         /* A0-A7 */
954         GET_REG32(env->aregs[n - 8]);
955     } else {
956         switch (n) {
957         case 16: GET_REG32(env->sr);
958         case 17: GET_REG32(env->pc);
959         }
960     }
961     /* FP registers not included here because they vary between
962        ColdFire and m68k.  Use XML bits for these.  */
963     return 0;
964 }
965
966 static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)
967 {
968     uint32_t tmp;
969
970     tmp = ldl_p(mem_buf);
971
972     if (n < 8) {
973         /* D0-D7 */
974         env->dregs[n] = tmp;
975     } else if (n < 8) {
976         /* A0-A7 */
977         env->aregs[n - 8] = tmp;
978     } else {
979         switch (n) {
980         case 16: env->sr = tmp; break;
981         case 17: env->pc = tmp; break;
982         default: return 0;
983         }
984     }
985     return 4;
986 }
987 #elif defined (TARGET_MIPS)
988
989 #define NUM_CORE_REGS 73
990
991 static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)
992 {
993     if (n < 32) {
994         GET_REGL(env->active_tc.gpr[n]);
995     }
996     if (env->CP0_Config1 & (1 << CP0C1_FP)) {
997         if (n >= 38 && n < 70) {
998             if (env->CP0_Status & (1 << CP0St_FR))
999                 GET_REGL(env->active_fpu.fpr[n - 38].d);
1000             else
1001                 GET_REGL(env->active_fpu.fpr[n - 38].w[FP_ENDIAN_IDX]);
1002         }
1003         switch (n) {
1004         case 70: GET_REGL((int32_t)env->active_fpu.fcr31);
1005         case 71: GET_REGL((int32_t)env->active_fpu.fcr0);
1006         }
1007     }
1008     switch (n) {
1009     case 32: GET_REGL((int32_t)env->CP0_Status);
1010     case 33: GET_REGL(env->active_tc.LO[0]);
1011     case 34: GET_REGL(env->active_tc.HI[0]);
1012     case 35: GET_REGL(env->CP0_BadVAddr);
1013     case 36: GET_REGL((int32_t)env->CP0_Cause);
1014     case 37: GET_REGL(env->active_tc.PC);
1015     case 72: GET_REGL(0); /* fp */
1016     case 89: GET_REGL((int32_t)env->CP0_PRid);
1017     }
1018     if (n >= 73 && n <= 88) {
1019         /* 16 embedded regs.  */
1020         GET_REGL(0);
1021     }
1022
1023     return 0;
1024 }
1025
1026 /* convert MIPS rounding mode in FCR31 to IEEE library */
1027 static unsigned int ieee_rm[] =
1028   {
1029     float_round_nearest_even,
1030     float_round_to_zero,
1031     float_round_up,
1032     float_round_down
1033   };
1034 #define RESTORE_ROUNDING_MODE \
1035     set_float_rounding_mode(ieee_rm[env->active_fpu.fcr31 & 3], &env->active_fpu.fp_status)
1036
1037 static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)
1038 {
1039     target_ulong tmp;
1040
1041     tmp = ldtul_p(mem_buf);
1042
1043     if (n < 32) {
1044         env->active_tc.gpr[n] = tmp;
1045         return sizeof(target_ulong);
1046     }
1047     if (env->CP0_Config1 & (1 << CP0C1_FP)
1048             && n >= 38 && n < 73) {
1049         if (n < 70) {
1050             if (env->CP0_Status & (1 << CP0St_FR))
1051               env->active_fpu.fpr[n - 38].d = tmp;
1052             else
1053               env->active_fpu.fpr[n - 38].w[FP_ENDIAN_IDX] = tmp;
1054         }
1055         switch (n) {
1056         case 70:
1057             env->active_fpu.fcr31 = tmp & 0xFF83FFFF;
1058             /* set rounding mode */
1059             RESTORE_ROUNDING_MODE;
1060 #ifndef CONFIG_SOFTFLOAT
1061             /* no floating point exception for native float */
1062             SET_FP_ENABLE(env->active_fpu.fcr31, 0);
1063 #endif
1064             break;
1065         case 71: env->active_fpu.fcr0 = tmp; break;
1066         }
1067         return sizeof(target_ulong);
1068     }
1069     switch (n) {
1070     case 32: env->CP0_Status = tmp; break;
1071     case 33: env->active_tc.LO[0] = tmp; break;
1072     case 34: env->active_tc.HI[0] = tmp; break;
1073     case 35: env->CP0_BadVAddr = tmp; break;
1074     case 36: env->CP0_Cause = tmp; break;
1075     case 37: env->active_tc.PC = tmp; break;
1076     case 72: /* fp, ignored */ break;
1077     default: 
1078         if (n > 89)
1079             return 0;
1080         /* Other registers are readonly.  Ignore writes.  */
1081         break;
1082     }
1083
1084     return sizeof(target_ulong);
1085 }
1086 #elif defined (TARGET_SH4)
1087
1088 /* Hint: Use "set architecture sh4" in GDB to see fpu registers */
1089 /* FIXME: We should use XML for this.  */
1090
1091 #define NUM_CORE_REGS 59
1092
1093 static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)
1094 {
1095     if (n < 8) {
1096         if ((env->sr & (SR_MD | SR_RB)) == (SR_MD | SR_RB)) {
1097             GET_REGL(env->gregs[n + 16]);
1098         } else {
1099             GET_REGL(env->gregs[n]);
1100         }
1101     } else if (n < 16) {
1102         GET_REGL(env->gregs[n - 8]);
1103     } else if (n >= 25 && n < 41) {
1104         GET_REGL(env->fregs[(n - 25) + ((env->fpscr & FPSCR_FR) ? 16 : 0)]);
1105     } else if (n >= 43 && n < 51) {
1106         GET_REGL(env->gregs[n - 43]);
1107     } else if (n >= 51 && n < 59) {
1108         GET_REGL(env->gregs[n - (51 - 16)]);
1109     }
1110     switch (n) {
1111     case 16: GET_REGL(env->pc);
1112     case 17: GET_REGL(env->pr);
1113     case 18: GET_REGL(env->gbr);
1114     case 19: GET_REGL(env->vbr);
1115     case 20: GET_REGL(env->mach);
1116     case 21: GET_REGL(env->macl);
1117     case 22: GET_REGL(env->sr);
1118     case 23: GET_REGL(env->fpul);
1119     case 24: GET_REGL(env->fpscr);
1120     case 41: GET_REGL(env->ssr);
1121     case 42: GET_REGL(env->spc);
1122     }
1123
1124     return 0;
1125 }
1126
1127 static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)
1128 {
1129     uint32_t tmp;
1130
1131     tmp = ldl_p(mem_buf);
1132
1133     if (n < 8) {
1134         if ((env->sr & (SR_MD | SR_RB)) == (SR_MD | SR_RB)) {
1135             env->gregs[n + 16] = tmp;
1136         } else {
1137             env->gregs[n] = tmp;
1138         }
1139         return 4;
1140     } else if (n < 16) {
1141         env->gregs[n - 8] = tmp;
1142         return 4;
1143     } else if (n >= 25 && n < 41) {
1144         env->fregs[(n - 25) + ((env->fpscr & FPSCR_FR) ? 16 : 0)] = tmp;
1145     } else if (n >= 43 && n < 51) {
1146         env->gregs[n - 43] = tmp;
1147         return 4;
1148     } else if (n >= 51 && n < 59) {
1149         env->gregs[n - (51 - 16)] = tmp;
1150         return 4;
1151     }
1152     switch (n) {
1153     case 16: env->pc = tmp;
1154     case 17: env->pr = tmp;
1155     case 18: env->gbr = tmp;
1156     case 19: env->vbr = tmp;
1157     case 20: env->mach = tmp;
1158     case 21: env->macl = tmp;
1159     case 22: env->sr = tmp;
1160     case 23: env->fpul = tmp;
1161     case 24: env->fpscr = tmp;
1162     case 41: env->ssr = tmp;
1163     case 42: env->spc = tmp;
1164     default: return 0;
1165     }
1166
1167     return 4;
1168 }
1169 #elif defined (TARGET_MICROBLAZE)
1170
1171 #define NUM_CORE_REGS (32 + 5)
1172
1173 static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)
1174 {
1175     if (n < 32) {
1176         GET_REG32(env->regs[n]);
1177     } else {
1178         GET_REG32(env->sregs[n - 32]);
1179     }
1180     return 0;
1181 }
1182
1183 static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)
1184 {
1185     uint32_t tmp;
1186
1187     if (n > NUM_CORE_REGS)
1188         return 0;
1189
1190     tmp = ldl_p(mem_buf);
1191
1192     if (n < 32) {
1193         env->regs[n] = tmp;
1194     } else {
1195         env->sregs[n - 32] = tmp;
1196     }
1197     return 4;
1198 }
1199 #elif defined (TARGET_CRIS)
1200
1201 #define NUM_CORE_REGS 49
1202
1203 static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)
1204 {
1205     uint8_t srs;
1206
1207     srs = env->pregs[PR_SRS];
1208     if (n < 16) {
1209         GET_REG32(env->regs[n]);
1210     }
1211
1212     if (n >= 21 && n < 32) {
1213         GET_REG32(env->pregs[n - 16]);
1214     }
1215     if (n >= 33 && n < 49) {
1216         GET_REG32(env->sregs[srs][n - 33]);
1217     }
1218     switch (n) {
1219     case 16: GET_REG8(env->pregs[0]);
1220     case 17: GET_REG8(env->pregs[1]);
1221     case 18: GET_REG32(env->pregs[2]);
1222     case 19: GET_REG8(srs);
1223     case 20: GET_REG16(env->pregs[4]);
1224     case 32: GET_REG32(env->pc);
1225     }
1226
1227     return 0;
1228 }
1229
1230 static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)
1231 {
1232     uint32_t tmp;
1233
1234     if (n > 49)
1235         return 0;
1236
1237     tmp = ldl_p(mem_buf);
1238
1239     if (n < 16) {
1240         env->regs[n] = tmp;
1241     }
1242
1243     if (n >= 21 && n < 32) {
1244         env->pregs[n - 16] = tmp;
1245     }
1246
1247     /* FIXME: Should support function regs be writable?  */
1248     switch (n) {
1249     case 16: return 1;
1250     case 17: return 1;
1251     case 18: env->pregs[PR_PID] = tmp; break;
1252     case 19: return 1;
1253     case 20: return 2;
1254     case 32: env->pc = tmp; break;
1255     }
1256
1257     return 4;
1258 }
1259 #elif defined (TARGET_ALPHA)
1260
1261 #define NUM_CORE_REGS 65
1262
1263 static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)
1264 {
1265     if (n < 31) {
1266        GET_REGL(env->ir[n]);
1267     }
1268     else if (n == 31) {
1269        GET_REGL(0);
1270     }
1271     else if (n<63) {
1272        uint64_t val;
1273
1274        val=*((uint64_t *)&env->fir[n-32]);
1275        GET_REGL(val);
1276     }
1277     else if (n==63) {
1278        GET_REGL(env->fpcr);
1279     }
1280     else if (n==64) {
1281        GET_REGL(env->pc);
1282     }
1283     else {
1284        GET_REGL(0);
1285     }
1286
1287     return 0;
1288 }
1289
1290 static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)
1291 {
1292     target_ulong tmp;
1293     tmp = ldtul_p(mem_buf);
1294
1295     if (n < 31) {
1296         env->ir[n] = tmp;
1297     }
1298
1299     if (n > 31 && n < 63) {
1300         env->fir[n - 32] = ldfl_p(mem_buf);
1301     }
1302
1303     if (n == 64 ) {
1304        env->pc=tmp;
1305     }
1306
1307     return 8;
1308 }
1309 #else
1310
1311 #define NUM_CORE_REGS 0
1312
1313 static int cpu_gdb_read_register(CPUState *env, uint8_t *mem_buf, int n)
1314 {
1315     return 0;
1316 }
1317
1318 static int cpu_gdb_write_register(CPUState *env, uint8_t *mem_buf, int n)
1319 {
1320     return 0;
1321 }
1322
1323 #endif
1324
1325 static int num_g_regs = NUM_CORE_REGS;
1326
1327 #ifdef GDB_CORE_XML
1328 /* Encode data using the encoding for 'x' packets.  */
1329 static int memtox(char *buf, const char *mem, int len)
1330 {
1331     char *p = buf;
1332     char c;
1333
1334     while (len--) {
1335         c = *(mem++);
1336         switch (c) {
1337         case '#': case '$': case '*': case '}':
1338             *(p++) = '}';
1339             *(p++) = c ^ 0x20;
1340             break;
1341         default:
1342             *(p++) = c;
1343             break;
1344         }
1345     }
1346     return p - buf;
1347 }
1348
1349 static const char *get_feature_xml(const char *p, const char **newp)
1350 {
1351     extern const char *const xml_builtin[][2];
1352     size_t len;
1353     int i;
1354     const char *name;
1355     static char target_xml[1024];
1356
1357     len = 0;
1358     while (p[len] && p[len] != ':')
1359         len++;
1360     *newp = p + len;
1361
1362     name = NULL;
1363     if (strncmp(p, "target.xml", len) == 0) {
1364         /* Generate the XML description for this CPU.  */
1365         if (!target_xml[0]) {
1366             GDBRegisterState *r;
1367
1368             snprintf(target_xml, sizeof(target_xml),
1369                      "<?xml version=\"1.0\"?>"
1370                      "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
1371                      "<target>"
1372                      "<xi:include href=\"%s\"/>",
1373                      GDB_CORE_XML);
1374
1375             for (r = first_cpu->gdb_regs; r; r = r->next) {
1376                 pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
1377                 pstrcat(target_xml, sizeof(target_xml), r->xml);
1378                 pstrcat(target_xml, sizeof(target_xml), "\"/>");
1379             }
1380             pstrcat(target_xml, sizeof(target_xml), "</target>");
1381         }
1382         return target_xml;
1383     }
1384     for (i = 0; ; i++) {
1385         name = xml_builtin[i][0];
1386         if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
1387             break;
1388     }
1389     return name ? xml_builtin[i][1] : NULL;
1390 }
1391 #endif
1392
1393 static int gdb_read_register(CPUState *env, uint8_t *mem_buf, int reg)
1394 {
1395     GDBRegisterState *r;
1396
1397     if (reg < NUM_CORE_REGS)
1398         return cpu_gdb_read_register(env, mem_buf, reg);
1399
1400     for (r = env->gdb_regs; r; r = r->next) {
1401         if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
1402             return r->get_reg(env, mem_buf, reg - r->base_reg);
1403         }
1404     }
1405     return 0;
1406 }
1407
1408 static int gdb_write_register(CPUState *env, uint8_t *mem_buf, int reg)
1409 {
1410     GDBRegisterState *r;
1411
1412     if (reg < NUM_CORE_REGS)
1413         return cpu_gdb_write_register(env, mem_buf, reg);
1414
1415     for (r = env->gdb_regs; r; r = r->next) {
1416         if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
1417             return r->set_reg(env, mem_buf, reg - r->base_reg);
1418         }
1419     }
1420     return 0;
1421 }
1422
1423 /* Register a supplemental set of CPU registers.  If g_pos is nonzero it
1424    specifies the first register number and these registers are included in
1425    a standard "g" packet.  Direction is relative to gdb, i.e. get_reg is
1426    gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
1427  */
1428
1429 void gdb_register_coprocessor(CPUState * env,
1430                              gdb_reg_cb get_reg, gdb_reg_cb set_reg,
1431                              int num_regs, const char *xml, int g_pos)
1432 {
1433     GDBRegisterState *s;
1434     GDBRegisterState **p;
1435     static int last_reg = NUM_CORE_REGS;
1436
1437     s = (GDBRegisterState *)qemu_mallocz(sizeof(GDBRegisterState));
1438     s->base_reg = last_reg;
1439     s->num_regs = num_regs;
1440     s->get_reg = get_reg;
1441     s->set_reg = set_reg;
1442     s->xml = xml;
1443     p = &env->gdb_regs;
1444     while (*p) {
1445         /* Check for duplicates.  */
1446         if (strcmp((*p)->xml, xml) == 0)
1447             return;
1448         p = &(*p)->next;
1449     }
1450     /* Add to end of list.  */
1451     last_reg += num_regs;
1452     *p = s;
1453     if (g_pos) {
1454         if (g_pos != s->base_reg) {
1455             fprintf(stderr, "Error: Bad gdb register numbering for '%s'\n"
1456                     "Expected %d got %d\n", xml, g_pos, s->base_reg);
1457         } else {
1458             num_g_regs = last_reg;
1459         }
1460     }
1461 }
1462
1463 #ifndef CONFIG_USER_ONLY
1464 static const int xlat_gdb_type[] = {
1465     [GDB_WATCHPOINT_WRITE]  = BP_GDB | BP_MEM_WRITE,
1466     [GDB_WATCHPOINT_READ]   = BP_GDB | BP_MEM_READ,
1467     [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
1468 };
1469 #endif
1470
1471 static int gdb_breakpoint_insert(target_ulong addr, target_ulong len, int type)
1472 {
1473     CPUState *env;
1474     int err = 0;
1475
1476     if (kvm_enabled())
1477         return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
1478
1479     switch (type) {
1480     case GDB_BREAKPOINT_SW:
1481     case GDB_BREAKPOINT_HW:
1482         for (env = first_cpu; env != NULL; env = env->next_cpu) {
1483             err = cpu_breakpoint_insert(env, addr, BP_GDB, NULL);
1484             if (err)
1485                 break;
1486         }
1487         return err;
1488 #ifndef CONFIG_USER_ONLY
1489     case GDB_WATCHPOINT_WRITE:
1490     case GDB_WATCHPOINT_READ:
1491     case GDB_WATCHPOINT_ACCESS:
1492         for (env = first_cpu; env != NULL; env = env->next_cpu) {
1493             err = cpu_watchpoint_insert(env, addr, len, xlat_gdb_type[type],
1494                                         NULL);
1495             if (err)
1496                 break;
1497         }
1498         return err;
1499 #endif
1500     default:
1501         return -ENOSYS;
1502     }
1503 }
1504
1505 static int gdb_breakpoint_remove(target_ulong addr, target_ulong len, int type)
1506 {
1507     CPUState *env;
1508     int err = 0;
1509
1510     if (kvm_enabled())
1511         return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
1512
1513     switch (type) {
1514     case GDB_BREAKPOINT_SW:
1515     case GDB_BREAKPOINT_HW:
1516         for (env = first_cpu; env != NULL; env = env->next_cpu) {
1517             err = cpu_breakpoint_remove(env, addr, BP_GDB);
1518             if (err)
1519                 break;
1520         }
1521         return err;
1522 #ifndef CONFIG_USER_ONLY
1523     case GDB_WATCHPOINT_WRITE:
1524     case GDB_WATCHPOINT_READ:
1525     case GDB_WATCHPOINT_ACCESS:
1526         for (env = first_cpu; env != NULL; env = env->next_cpu) {
1527             err = cpu_watchpoint_remove(env, addr, len, xlat_gdb_type[type]);
1528             if (err)
1529                 break;
1530         }
1531         return err;
1532 #endif
1533     default:
1534         return -ENOSYS;
1535     }
1536 }
1537
1538 static void gdb_breakpoint_remove_all(void)
1539 {
1540     CPUState *env;
1541
1542     if (kvm_enabled()) {
1543         kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
1544         return;
1545     }
1546
1547     for (env = first_cpu; env != NULL; env = env->next_cpu) {
1548         cpu_breakpoint_remove_all(env, BP_GDB);
1549 #ifndef CONFIG_USER_ONLY
1550         cpu_watchpoint_remove_all(env, BP_GDB);
1551 #endif
1552     }
1553 }
1554
1555 static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
1556 {
1557 #if defined(TARGET_I386)
1558     s->c_cpu->eip = pc;
1559     cpu_synchronize_state(s->c_cpu, 1);
1560 #elif defined (TARGET_PPC)
1561     s->c_cpu->nip = pc;
1562 #elif defined (TARGET_SPARC)
1563     s->c_cpu->pc = pc;
1564     s->c_cpu->npc = pc + 4;
1565 #elif defined (TARGET_ARM)
1566     s->c_cpu->regs[15] = pc;
1567 #elif defined (TARGET_SH4)
1568     s->c_cpu->pc = pc;
1569 #elif defined (TARGET_MIPS)
1570     s->c_cpu->active_tc.PC = pc;
1571 #elif defined (TARGET_MICROBLAZE)
1572     s->c_cpu->sregs[SR_PC] = pc;
1573 #elif defined (TARGET_CRIS)
1574     s->c_cpu->pc = pc;
1575 #elif defined (TARGET_ALPHA)
1576     s->c_cpu->pc = pc;
1577 #endif
1578 }
1579
1580 static inline int gdb_id(CPUState *env)
1581 {
1582 #if defined(CONFIG_USER_ONLY) && defined(USE_NPTL)
1583     return env->host_tid;
1584 #else
1585     return env->cpu_index + 1;
1586 #endif
1587 }
1588
1589 static CPUState *find_cpu(uint32_t thread_id)
1590 {
1591     CPUState *env;
1592
1593     for (env = first_cpu; env != NULL; env = env->next_cpu) {
1594         if (gdb_id(env) == thread_id) {
1595             return env;
1596         }
1597     }
1598
1599     return NULL;
1600 }
1601
1602 static int gdb_handle_packet(GDBState *s, const char *line_buf)
1603 {
1604     CPUState *env;
1605     const char *p;
1606     uint32_t thread;
1607     int ch, reg_size, type, res;
1608     char buf[MAX_PACKET_LENGTH];
1609     uint8_t mem_buf[MAX_PACKET_LENGTH];
1610     uint8_t *registers;
1611     target_ulong addr, len;
1612
1613 #ifdef DEBUG_GDB
1614     printf("command='%s'\n", line_buf);
1615 #endif
1616     p = line_buf;
1617     ch = *p++;
1618     switch(ch) {
1619     case '?':
1620         /* TODO: Make this return the correct value for user-mode.  */
1621         snprintf(buf, sizeof(buf), "T%02xthread:%02x;", GDB_SIGNAL_TRAP,
1622                  gdb_id(s->c_cpu));
1623         put_packet(s, buf);
1624         /* Remove all the breakpoints when this query is issued,
1625          * because gdb is doing and initial connect and the state
1626          * should be cleaned up.
1627          */
1628         gdb_breakpoint_remove_all();
1629         break;
1630     case 'c':
1631         if (*p != '\0') {
1632             addr = strtoull(p, (char **)&p, 16);
1633             gdb_set_cpu_pc(s, addr);
1634         }
1635         s->signal = 0;
1636         gdb_continue(s);
1637         return RS_IDLE;
1638     case 'C':
1639         s->signal = gdb_signal_to_target (strtoul(p, (char **)&p, 16));
1640         if (s->signal == -1)
1641             s->signal = 0;
1642         gdb_continue(s);
1643         return RS_IDLE;
1644     case 'v':
1645         if (strncmp(p, "Cont", 4) == 0) {
1646             int res_signal, res_thread;
1647
1648             p += 4;
1649             if (*p == '?') {
1650                 put_packet(s, "vCont;c;C;s;S");
1651                 break;
1652             }
1653             res = 0;
1654             res_signal = 0;
1655             res_thread = 0;
1656             while (*p) {
1657                 int action, signal;
1658
1659                 if (*p++ != ';') {
1660                     res = 0;
1661                     break;
1662                 }
1663                 action = *p++;
1664                 signal = 0;
1665                 if (action == 'C' || action == 'S') {
1666                     signal = strtoul(p, (char **)&p, 16);
1667                 } else if (action != 'c' && action != 's') {
1668                     res = 0;
1669                     break;
1670                 }
1671                 thread = 0;
1672                 if (*p == ':') {
1673                     thread = strtoull(p+1, (char **)&p, 16);
1674                 }
1675                 action = tolower(action);
1676                 if (res == 0 || (res == 'c' && action == 's')) {
1677                     res = action;
1678                     res_signal = signal;
1679                     res_thread = thread;
1680                 }
1681             }
1682             if (res) {
1683                 if (res_thread != -1 && res_thread != 0) {
1684                     env = find_cpu(res_thread);
1685                     if (env == NULL) {
1686                         put_packet(s, "E22");
1687                         break;
1688                     }
1689                     s->c_cpu = env;
1690                 }
1691                 if (res == 's') {
1692                     cpu_single_step(s->c_cpu, sstep_flags);
1693                 }
1694                 s->signal = res_signal;
1695                 gdb_continue(s);
1696                 return RS_IDLE;
1697             }
1698             break;
1699         } else {
1700             goto unknown_command;
1701         }
1702     case 'k':
1703         /* Kill the target */
1704         fprintf(stderr, "\nQEMU: Terminated via GDBstub\n");
1705         exit(0);
1706     case 'D':
1707         /* Detach packet */
1708         gdb_breakpoint_remove_all();
1709         gdb_continue(s);
1710         put_packet(s, "OK");
1711         break;
1712     case 's':
1713         if (*p != '\0') {
1714             addr = strtoull(p, (char **)&p, 16);
1715             gdb_set_cpu_pc(s, addr);
1716         }
1717         cpu_single_step(s->c_cpu, sstep_flags);
1718         gdb_continue(s);
1719         return RS_IDLE;
1720     case 'F':
1721         {
1722             target_ulong ret;
1723             target_ulong err;
1724
1725             ret = strtoull(p, (char **)&p, 16);
1726             if (*p == ',') {
1727                 p++;
1728                 err = strtoull(p, (char **)&p, 16);
1729             } else {
1730                 err = 0;
1731             }
1732             if (*p == ',')
1733                 p++;
1734             type = *p;
1735             if (gdb_current_syscall_cb)
1736                 gdb_current_syscall_cb(s->c_cpu, ret, err);
1737             if (type == 'C') {
1738                 put_packet(s, "T02");
1739             } else {
1740                 gdb_continue(s);
1741             }
1742         }
1743         break;
1744     case 'g':
1745         cpu_synchronize_state(s->g_cpu, 0);
1746         len = 0;
1747         for (addr = 0; addr < num_g_regs; addr++) {
1748             reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);
1749             len += reg_size;
1750         }
1751         memtohex(buf, mem_buf, len);
1752         put_packet(s, buf);
1753         break;
1754     case 'G':
1755         registers = mem_buf;
1756         len = strlen(p) / 2;
1757         hextomem((uint8_t *)registers, p, len);
1758         for (addr = 0; addr < num_g_regs && len > 0; addr++) {
1759             reg_size = gdb_write_register(s->g_cpu, registers, addr);
1760             len -= reg_size;
1761             registers += reg_size;
1762         }
1763         cpu_synchronize_state(s->g_cpu, 1);
1764         put_packet(s, "OK");
1765         break;
1766     case 'm':
1767         addr = strtoull(p, (char **)&p, 16);
1768         if (*p == ',')
1769             p++;
1770         len = strtoull(p, NULL, 16);
1771         if (cpu_memory_rw_debug(s->g_cpu, addr, mem_buf, len, 0) != 0) {
1772             put_packet (s, "E14");
1773         } else {
1774             memtohex(buf, mem_buf, len);
1775             put_packet(s, buf);
1776         }
1777         break;
1778     case 'M':
1779         addr = strtoull(p, (char **)&p, 16);
1780         if (*p == ',')
1781             p++;
1782         len = strtoull(p, (char **)&p, 16);
1783         if (*p == ':')
1784             p++;
1785         hextomem(mem_buf, p, len);
1786         if (cpu_memory_rw_debug(s->g_cpu, addr, mem_buf, len, 1) != 0)
1787             put_packet(s, "E14");
1788         else
1789             put_packet(s, "OK");
1790         break;
1791     case 'p':
1792         /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
1793            This works, but can be very slow.  Anything new enough to
1794            understand XML also knows how to use this properly.  */
1795         if (!gdb_has_xml)
1796             goto unknown_command;
1797         addr = strtoull(p, (char **)&p, 16);
1798         reg_size = gdb_read_register(s->g_cpu, mem_buf, addr);
1799         if (reg_size) {
1800             memtohex(buf, mem_buf, reg_size);
1801             put_packet(s, buf);
1802         } else {
1803             put_packet(s, "E14");
1804         }
1805         break;
1806     case 'P':
1807         if (!gdb_has_xml)
1808             goto unknown_command;
1809         addr = strtoull(p, (char **)&p, 16);
1810         if (*p == '=')
1811             p++;
1812         reg_size = strlen(p) / 2;
1813         hextomem(mem_buf, p, reg_size);
1814         gdb_write_register(s->g_cpu, mem_buf, addr);
1815         put_packet(s, "OK");
1816         break;
1817     case 'Z':
1818     case 'z':
1819         type = strtoul(p, (char **)&p, 16);
1820         if (*p == ',')
1821             p++;
1822         addr = strtoull(p, (char **)&p, 16);
1823         if (*p == ',')
1824             p++;
1825         len = strtoull(p, (char **)&p, 16);
1826         if (ch == 'Z')
1827             res = gdb_breakpoint_insert(addr, len, type);
1828         else
1829             res = gdb_breakpoint_remove(addr, len, type);
1830         if (res >= 0)
1831              put_packet(s, "OK");
1832         else if (res == -ENOSYS)
1833             put_packet(s, "");
1834         else
1835             put_packet(s, "E22");
1836         break;
1837     case 'H':
1838         type = *p++;
1839         thread = strtoull(p, (char **)&p, 16);
1840         if (thread == -1 || thread == 0) {
1841             put_packet(s, "OK");
1842             break;
1843         }
1844         env = find_cpu(thread);
1845         if (env == NULL) {
1846             put_packet(s, "E22");
1847             break;
1848         }
1849         switch (type) {
1850         case 'c':
1851             s->c_cpu = env;
1852             put_packet(s, "OK");
1853             break;
1854         case 'g':
1855             s->g_cpu = env;
1856             put_packet(s, "OK");
1857             break;
1858         default:
1859              put_packet(s, "E22");
1860              break;
1861         }
1862         break;
1863     case 'T':
1864         thread = strtoull(p, (char **)&p, 16);
1865         env = find_cpu(thread);
1866
1867         if (env != NULL) {
1868             put_packet(s, "OK");
1869         } else {
1870             put_packet(s, "E22");
1871         }
1872         break;
1873     case 'q':
1874     case 'Q':
1875         /* parse any 'q' packets here */
1876         if (!strcmp(p,"qemu.sstepbits")) {
1877             /* Query Breakpoint bit definitions */
1878             snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1879                      SSTEP_ENABLE,
1880                      SSTEP_NOIRQ,
1881                      SSTEP_NOTIMER);
1882             put_packet(s, buf);
1883             break;
1884         } else if (strncmp(p,"qemu.sstep",10) == 0) {
1885             /* Display or change the sstep_flags */
1886             p += 10;
1887             if (*p != '=') {
1888                 /* Display current setting */
1889                 snprintf(buf, sizeof(buf), "0x%x", sstep_flags);
1890                 put_packet(s, buf);
1891                 break;
1892             }
1893             p++;
1894             type = strtoul(p, (char **)&p, 16);
1895             sstep_flags = type;
1896             put_packet(s, "OK");
1897             break;
1898         } else if (strcmp(p,"C") == 0) {
1899             /* "Current thread" remains vague in the spec, so always return
1900              *  the first CPU (gdb returns the first thread). */
1901             put_packet(s, "QC1");
1902             break;
1903         } else if (strcmp(p,"fThreadInfo") == 0) {
1904             s->query_cpu = first_cpu;
1905             goto report_cpuinfo;
1906         } else if (strcmp(p,"sThreadInfo") == 0) {
1907         report_cpuinfo:
1908             if (s->query_cpu) {
1909                 snprintf(buf, sizeof(buf), "m%x", gdb_id(s->query_cpu));
1910                 put_packet(s, buf);
1911                 s->query_cpu = s->query_cpu->next_cpu;
1912             } else
1913                 put_packet(s, "l");
1914             break;
1915         } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {
1916             thread = strtoull(p+16, (char **)&p, 16);
1917             env = find_cpu(thread);
1918             if (env != NULL) {
1919                 cpu_synchronize_state(env, 0);
1920                 len = snprintf((char *)mem_buf, sizeof(mem_buf),
1921                                "CPU#%d [%s]", env->cpu_index,
1922                                env->halted ? "halted " : "running");
1923                 memtohex(buf, mem_buf, len);
1924                 put_packet(s, buf);
1925             }
1926             break;
1927         }
1928 #ifdef CONFIG_USER_ONLY
1929         else if (strncmp(p, "Offsets", 7) == 0) {
1930             TaskState *ts = s->c_cpu->opaque;
1931
1932             snprintf(buf, sizeof(buf),
1933                      "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
1934                      ";Bss=" TARGET_ABI_FMT_lx,
1935                      ts->info->code_offset,
1936                      ts->info->data_offset,
1937                      ts->info->data_offset);
1938             put_packet(s, buf);
1939             break;
1940         }
1941 #else /* !CONFIG_USER_ONLY */
1942         else if (strncmp(p, "Rcmd,", 5) == 0) {
1943             int len = strlen(p + 5);
1944
1945             if ((len % 2) != 0) {
1946                 put_packet(s, "E01");
1947                 break;
1948             }
1949             hextomem(mem_buf, p + 5, len);
1950             len = len / 2;
1951             mem_buf[len++] = 0;
1952             qemu_chr_read(s->mon_chr, mem_buf, len);
1953             put_packet(s, "OK");
1954             break;
1955         }
1956 #endif /* !CONFIG_USER_ONLY */
1957         if (strncmp(p, "Supported", 9) == 0) {
1958             snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);
1959 #ifdef GDB_CORE_XML
1960             pstrcat(buf, sizeof(buf), ";qXfer:features:read+");
1961 #endif
1962             put_packet(s, buf);
1963             break;
1964         }
1965 #ifdef GDB_CORE_XML
1966         if (strncmp(p, "Xfer:features:read:", 19) == 0) {
1967             const char *xml;
1968             target_ulong total_len;
1969
1970             gdb_has_xml = 1;
1971             p += 19;
1972             xml = get_feature_xml(p, &p);
1973             if (!xml) {
1974                 snprintf(buf, sizeof(buf), "E00");
1975                 put_packet(s, buf);
1976                 break;
1977             }
1978
1979             if (*p == ':')
1980                 p++;
1981             addr = strtoul(p, (char **)&p, 16);
1982             if (*p == ',')
1983                 p++;
1984             len = strtoul(p, (char **)&p, 16);
1985
1986             total_len = strlen(xml);
1987             if (addr > total_len) {
1988                 snprintf(buf, sizeof(buf), "E00");
1989                 put_packet(s, buf);
1990                 break;
1991             }
1992             if (len > (MAX_PACKET_LENGTH - 5) / 2)
1993                 len = (MAX_PACKET_LENGTH - 5) / 2;
1994             if (len < total_len - addr) {
1995                 buf[0] = 'm';
1996                 len = memtox(buf + 1, xml + addr, len);
1997             } else {
1998                 buf[0] = 'l';
1999                 len = memtox(buf + 1, xml + addr, total_len - addr);
2000             }
2001             put_packet_binary(s, buf, len + 1);
2002             break;
2003         }
2004 #endif
2005         /* Unrecognised 'q' command.  */
2006         goto unknown_command;
2007
2008     default:
2009     unknown_command:
2010         /* put empty packet */
2011         buf[0] = '\0';
2012         put_packet(s, buf);
2013         break;
2014     }
2015     return RS_IDLE;
2016 }
2017
2018 void gdb_set_stop_cpu(CPUState *env)
2019 {
2020     gdbserver_state->c_cpu = env;
2021     gdbserver_state->g_cpu = env;
2022 }
2023
2024 #ifndef CONFIG_USER_ONLY
2025 static void gdb_vm_state_change(void *opaque, int running, int reason)
2026 {
2027     GDBState *s = gdbserver_state;
2028     CPUState *env = s->c_cpu;
2029     char buf[256];
2030     const char *type;
2031     int ret;
2032
2033     if (running || (reason != EXCP_DEBUG && reason != EXCP_INTERRUPT) ||
2034         s->state == RS_INACTIVE || s->state == RS_SYSCALL)
2035         return;
2036
2037     /* disable single step if it was enable */
2038     cpu_single_step(env, 0);
2039
2040     if (reason == EXCP_DEBUG) {
2041         if (env->watchpoint_hit) {
2042             switch (env->watchpoint_hit->flags & BP_MEM_ACCESS) {
2043             case BP_MEM_READ:
2044                 type = "r";
2045                 break;
2046             case BP_MEM_ACCESS:
2047                 type = "a";
2048                 break;
2049             default:
2050                 type = "";
2051                 break;
2052             }
2053             snprintf(buf, sizeof(buf),
2054                      "T%02xthread:%02x;%swatch:" TARGET_FMT_lx ";",
2055                      GDB_SIGNAL_TRAP, gdb_id(env), type,
2056                      env->watchpoint_hit->vaddr);
2057             put_packet(s, buf);
2058             env->watchpoint_hit = NULL;
2059             return;
2060         }
2061         tb_flush(env);
2062         ret = GDB_SIGNAL_TRAP;
2063     } else {
2064         ret = GDB_SIGNAL_INT;
2065     }
2066     snprintf(buf, sizeof(buf), "T%02xthread:%02x;", ret, gdb_id(env));
2067     put_packet(s, buf);
2068 }
2069 #endif
2070
2071 /* Send a gdb syscall request.
2072    This accepts limited printf-style format specifiers, specifically:
2073     %x  - target_ulong argument printed in hex.
2074     %lx - 64-bit argument printed in hex.
2075     %s  - string pointer (target_ulong) and length (int) pair.  */
2076 void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
2077 {
2078     va_list va;
2079     char buf[256];
2080     char *p;
2081     target_ulong addr;
2082     uint64_t i64;
2083     GDBState *s;
2084
2085     s = gdbserver_state;
2086     if (!s)
2087         return;
2088     gdb_current_syscall_cb = cb;
2089     s->state = RS_SYSCALL;
2090 #ifndef CONFIG_USER_ONLY
2091     vm_stop(EXCP_DEBUG);
2092 #endif
2093     s->state = RS_IDLE;
2094     va_start(va, fmt);
2095     p = buf;
2096     *(p++) = 'F';
2097     while (*fmt) {
2098         if (*fmt == '%') {
2099             fmt++;
2100             switch (*fmt++) {
2101             case 'x':
2102                 addr = va_arg(va, target_ulong);
2103                 p += snprintf(p, &buf[sizeof(buf)] - p, TARGET_FMT_lx, addr);
2104                 break;
2105             case 'l':
2106                 if (*(fmt++) != 'x')
2107                     goto bad_format;
2108                 i64 = va_arg(va, uint64_t);
2109                 p += snprintf(p, &buf[sizeof(buf)] - p, "%" PRIx64, i64);
2110                 break;
2111             case 's':
2112                 addr = va_arg(va, target_ulong);
2113                 p += snprintf(p, &buf[sizeof(buf)] - p, TARGET_FMT_lx "/%x",
2114                               addr, va_arg(va, int));
2115                 break;
2116             default:
2117             bad_format:
2118                 fprintf(stderr, "gdbstub: Bad syscall format string '%s'\n",
2119                         fmt - 1);
2120                 break;
2121             }
2122         } else {
2123             *(p++) = *(fmt++);
2124         }
2125     }
2126     *p = 0;
2127     va_end(va);
2128     put_packet(s, buf);
2129 #ifdef CONFIG_USER_ONLY
2130     gdb_handlesig(s->c_cpu, 0);
2131 #else
2132     cpu_exit(s->c_cpu);
2133 #endif
2134 }
2135
2136 static void gdb_read_byte(GDBState *s, int ch)
2137 {
2138     int i, csum;
2139     uint8_t reply;
2140
2141 #ifndef CONFIG_USER_ONLY
2142     if (s->last_packet_len) {
2143         /* Waiting for a response to the last packet.  If we see the start
2144            of a new command then abandon the previous response.  */
2145         if (ch == '-') {
2146 #ifdef DEBUG_GDB
2147             printf("Got NACK, retransmitting\n");
2148 #endif
2149             put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
2150         }
2151 #ifdef DEBUG_GDB
2152         else if (ch == '+')
2153             printf("Got ACK\n");
2154         else
2155             printf("Got '%c' when expecting ACK/NACK\n", ch);
2156 #endif
2157         if (ch == '+' || ch == '$')
2158             s->last_packet_len = 0;
2159         if (ch != '$')
2160             return;
2161     }
2162     if (vm_running) {
2163         /* when the CPU is running, we cannot do anything except stop
2164            it when receiving a char */
2165         vm_stop(EXCP_INTERRUPT);
2166     } else
2167 #endif
2168     {
2169         switch(s->state) {
2170         case RS_IDLE:
2171             if (ch == '$') {
2172                 s->line_buf_index = 0;
2173                 s->state = RS_GETLINE;
2174             }
2175             break;
2176         case RS_GETLINE:
2177             if (ch == '#') {
2178             s->state = RS_CHKSUM1;
2179             } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
2180                 s->state = RS_IDLE;
2181             } else {
2182             s->line_buf[s->line_buf_index++] = ch;
2183             }
2184             break;
2185         case RS_CHKSUM1:
2186             s->line_buf[s->line_buf_index] = '\0';
2187             s->line_csum = fromhex(ch) << 4;
2188             s->state = RS_CHKSUM2;
2189             break;
2190         case RS_CHKSUM2:
2191             s->line_csum |= fromhex(ch);
2192             csum = 0;
2193             for(i = 0; i < s->line_buf_index; i++) {
2194                 csum += s->line_buf[i];
2195             }
2196             if (s->line_csum != (csum & 0xff)) {
2197                 reply = '-';
2198                 put_buffer(s, &reply, 1);
2199                 s->state = RS_IDLE;
2200             } else {
2201                 reply = '+';
2202                 put_buffer(s, &reply, 1);
2203                 s->state = gdb_handle_packet(s, s->line_buf);
2204             }
2205             break;
2206         default:
2207             abort();
2208         }
2209     }
2210 }
2211
2212 #ifdef CONFIG_USER_ONLY
2213 int
2214 gdb_queuesig (void)
2215 {
2216     GDBState *s;
2217
2218     s = gdbserver_state;
2219
2220     if (gdbserver_fd < 0 || s->fd < 0)
2221         return 0;
2222     else
2223         return 1;
2224 }
2225
2226 int
2227 gdb_handlesig (CPUState *env, int sig)
2228 {
2229   GDBState *s;
2230   char buf[256];
2231   int n;
2232
2233   s = gdbserver_state;
2234   if (gdbserver_fd < 0 || s->fd < 0)
2235     return sig;
2236
2237   /* disable single step if it was enabled */
2238   cpu_single_step(env, 0);
2239   tb_flush(env);
2240
2241   if (sig != 0)
2242     {
2243       snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb (sig));
2244       put_packet(s, buf);
2245     }
2246   /* put_packet() might have detected that the peer terminated the 
2247      connection.  */
2248   if (s->fd < 0)
2249       return sig;
2250
2251   sig = 0;
2252   s->state = RS_IDLE;
2253   s->running_state = 0;
2254   while (s->running_state == 0) {
2255       n = read (s->fd, buf, 256);
2256       if (n > 0)
2257         {
2258           int i;
2259
2260           for (i = 0; i < n; i++)
2261             gdb_read_byte (s, buf[i]);
2262         }
2263       else if (n == 0 || errno != EAGAIN)
2264         {
2265           /* XXX: Connection closed.  Should probably wait for annother
2266              connection before continuing.  */
2267           return sig;
2268         }
2269   }
2270   sig = s->signal;
2271   s->signal = 0;
2272   return sig;
2273 }
2274
2275 /* Tell the remote gdb that the process has exited.  */
2276 void gdb_exit(CPUState *env, int code)
2277 {
2278   GDBState *s;
2279   char buf[4];
2280
2281   s = gdbserver_state;
2282   if (gdbserver_fd < 0 || s->fd < 0)
2283     return;
2284
2285   snprintf(buf, sizeof(buf), "W%02x", code);
2286   put_packet(s, buf);
2287 }
2288
2289 /* Tell the remote gdb that the process has exited due to SIG.  */
2290 void gdb_signalled(CPUState *env, int sig)
2291 {
2292   GDBState *s;
2293   char buf[4];
2294
2295   s = gdbserver_state;
2296   if (gdbserver_fd < 0 || s->fd < 0)
2297     return;
2298
2299   snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb (sig));
2300   put_packet(s, buf);
2301 }
2302
2303 static void gdb_accept(void)
2304 {
2305     GDBState *s;
2306     struct sockaddr_in sockaddr;
2307     socklen_t len;
2308     int val, fd;
2309
2310     for(;;) {
2311         len = sizeof(sockaddr);
2312         fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
2313         if (fd < 0 && errno != EINTR) {
2314             perror("accept");
2315             return;
2316         } else if (fd >= 0) {
2317             break;
2318         }
2319     }
2320
2321     /* set short latency */
2322     val = 1;
2323     setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2324
2325     s = qemu_mallocz(sizeof(GDBState));
2326     s->c_cpu = first_cpu;
2327     s->g_cpu = first_cpu;
2328     s->fd = fd;
2329     gdb_has_xml = 0;
2330
2331     gdbserver_state = s;
2332
2333     fcntl(fd, F_SETFL, O_NONBLOCK);
2334 }
2335
2336 static int gdbserver_open(int port)
2337 {
2338     struct sockaddr_in sockaddr;
2339     int fd, val, ret;
2340
2341     fd = socket(PF_INET, SOCK_STREAM, 0);
2342     if (fd < 0) {
2343         perror("socket");
2344         return -1;
2345     }
2346
2347     /* allow fast reuse */
2348     val = 1;
2349     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
2350
2351     sockaddr.sin_family = AF_INET;
2352     sockaddr.sin_port = htons(port);
2353     sockaddr.sin_addr.s_addr = 0;
2354     ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
2355     if (ret < 0) {
2356         perror("bind");
2357         return -1;
2358     }
2359     ret = listen(fd, 0);
2360     if (ret < 0) {
2361         perror("listen");
2362         return -1;
2363     }
2364     return fd;
2365 }
2366
2367 int gdbserver_start(int port)
2368 {
2369     gdbserver_fd = gdbserver_open(port);
2370     if (gdbserver_fd < 0)
2371         return -1;
2372     /* accept connections */
2373     gdb_accept();
2374     return 0;
2375 }
2376
2377 /* Disable gdb stub for child processes.  */
2378 void gdbserver_fork(CPUState *env)
2379 {
2380     GDBState *s = gdbserver_state;
2381     if (gdbserver_fd < 0 || s->fd < 0)
2382       return;
2383     close(s->fd);
2384     s->fd = -1;
2385     cpu_breakpoint_remove_all(env, BP_GDB);
2386     cpu_watchpoint_remove_all(env, BP_GDB);
2387 }
2388 #else
2389 static int gdb_chr_can_receive(void *opaque)
2390 {
2391   /* We can handle an arbitrarily large amount of data.
2392    Pick the maximum packet size, which is as good as anything.  */
2393   return MAX_PACKET_LENGTH;
2394 }
2395
2396 static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
2397 {
2398     int i;
2399
2400     for (i = 0; i < size; i++) {
2401         gdb_read_byte(gdbserver_state, buf[i]);
2402     }
2403 }
2404
2405 static void gdb_chr_event(void *opaque, int event)
2406 {
2407     switch (event) {
2408     case CHR_EVENT_RESET:
2409         vm_stop(EXCP_INTERRUPT);
2410         gdb_has_xml = 0;
2411         break;
2412     default:
2413         break;
2414     }
2415 }
2416
2417 static void gdb_monitor_output(GDBState *s, const char *msg, int len)
2418 {
2419     char buf[MAX_PACKET_LENGTH];
2420
2421     buf[0] = 'O';
2422     if (len > (MAX_PACKET_LENGTH/2) - 1)
2423         len = (MAX_PACKET_LENGTH/2) - 1;
2424     memtohex(buf + 1, (uint8_t *)msg, len);
2425     put_packet(s, buf);
2426 }
2427
2428 static int gdb_monitor_write(CharDriverState *chr, const uint8_t *buf, int len)
2429 {
2430     const char *p = (const char *)buf;
2431     int max_sz;
2432
2433     max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
2434     for (;;) {
2435         if (len <= max_sz) {
2436             gdb_monitor_output(gdbserver_state, p, len);
2437             break;
2438         }
2439         gdb_monitor_output(gdbserver_state, p, max_sz);
2440         p += max_sz;
2441         len -= max_sz;
2442     }
2443     return len;
2444 }
2445
2446 #ifndef _WIN32
2447 static void gdb_sigterm_handler(int signal)
2448 {
2449     if (vm_running)
2450         vm_stop(EXCP_INTERRUPT);
2451 }
2452 #endif
2453
2454 int gdbserver_start(const char *device)
2455 {
2456     GDBState *s;
2457     char gdbstub_device_name[128];
2458     CharDriverState *chr = NULL;
2459     CharDriverState *mon_chr;
2460
2461     if (!device)
2462         return -1;
2463     if (strcmp(device, "none") != 0) {
2464         if (strstart(device, "tcp:", NULL)) {
2465             /* enforce required TCP attributes */
2466             snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
2467                      "%s,nowait,nodelay,server", device);
2468             device = gdbstub_device_name;
2469         }
2470 #ifndef _WIN32
2471         else if (strcmp(device, "stdio") == 0) {
2472             struct sigaction act;
2473
2474             memset(&act, 0, sizeof(act));
2475             act.sa_handler = gdb_sigterm_handler;
2476             sigaction(SIGINT, &act, NULL);
2477         }
2478 #endif
2479         chr = qemu_chr_open("gdb", device, NULL);
2480         if (!chr)
2481             return -1;
2482
2483         qemu_chr_add_handlers(chr, gdb_chr_can_receive, gdb_chr_receive,
2484                               gdb_chr_event, NULL);
2485     }
2486
2487     s = gdbserver_state;
2488     if (!s) {
2489         s = qemu_mallocz(sizeof(GDBState));
2490         gdbserver_state = s;
2491
2492         qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
2493
2494         /* Initialize a monitor terminal for gdb */
2495         mon_chr = qemu_mallocz(sizeof(*mon_chr));
2496         mon_chr->chr_write = gdb_monitor_write;
2497         monitor_init(mon_chr, 0);
2498     } else {
2499         if (s->chr)
2500             qemu_chr_close(s->chr);
2501         mon_chr = s->mon_chr;
2502         memset(s, 0, sizeof(GDBState));
2503     }
2504     s->c_cpu = first_cpu;
2505     s->g_cpu = first_cpu;
2506     s->chr = chr;
2507     s->state = chr ? RS_IDLE : RS_INACTIVE;
2508     s->mon_chr = mon_chr;
2509
2510     return 0;
2511 }
2512 #endif