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