Statistics
| Branch: | Revision:

root / gdbstub.c @ 986a2998

History | View | Annotate | Download (44.8 kB)

1
/*
2
 * gdb server stub
3
 *
4
 * Copyright (c) 2003-2005 Fabrice Bellard
5
 *
6
 * This library is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2 of the License, or (at your option) any later version.
10
 *
11
 * This library is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18
 */
19
#include "config.h"
20
#include "qemu-common.h"
21
#ifdef CONFIG_USER_ONLY
22
#include <stdlib.h>
23
#include <stdio.h>
24
#include <stdarg.h>
25
#include <string.h>
26
#include <errno.h>
27
#include <unistd.h>
28
#include <fcntl.h>
29

    
30
#include "qemu.h"
31
#else
32
#include "monitor/monitor.h"
33
#include "sysemu/char.h"
34
#include "sysemu/sysemu.h"
35
#include "exec/gdbstub.h"
36
#endif
37

    
38
#define MAX_PACKET_LENGTH 4096
39

    
40
#include "cpu.h"
41
#include "qemu/sockets.h"
42
#include "sysemu/kvm.h"
43
#include "qemu/bitops.h"
44

    
45
static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
46
                                         uint8_t *buf, int len, bool is_write)
47
{
48
    CPUClass *cc = CPU_GET_CLASS(cpu);
49

    
50
    if (cc->memory_rw_debug) {
51
        return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
52
    }
53
    return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
54
}
55

    
56
enum {
57
    GDB_SIGNAL_0 = 0,
58
    GDB_SIGNAL_INT = 2,
59
    GDB_SIGNAL_QUIT = 3,
60
    GDB_SIGNAL_TRAP = 5,
61
    GDB_SIGNAL_ABRT = 6,
62
    GDB_SIGNAL_ALRM = 14,
63
    GDB_SIGNAL_IO = 23,
64
    GDB_SIGNAL_XCPU = 24,
65
    GDB_SIGNAL_UNKNOWN = 143
66
};
67

    
68
#ifdef CONFIG_USER_ONLY
69

    
70
/* Map target signal numbers to GDB protocol signal numbers and vice
71
 * versa.  For user emulation's currently supported systems, we can
72
 * assume most signals are defined.
73
 */
74

    
75
static int gdb_signal_table[] = {
76
    0,
77
    TARGET_SIGHUP,
78
    TARGET_SIGINT,
79
    TARGET_SIGQUIT,
80
    TARGET_SIGILL,
81
    TARGET_SIGTRAP,
82
    TARGET_SIGABRT,
83
    -1, /* SIGEMT */
84
    TARGET_SIGFPE,
85
    TARGET_SIGKILL,
86
    TARGET_SIGBUS,
87
    TARGET_SIGSEGV,
88
    TARGET_SIGSYS,
89
    TARGET_SIGPIPE,
90
    TARGET_SIGALRM,
91
    TARGET_SIGTERM,
92
    TARGET_SIGURG,
93
    TARGET_SIGSTOP,
94
    TARGET_SIGTSTP,
95
    TARGET_SIGCONT,
96
    TARGET_SIGCHLD,
97
    TARGET_SIGTTIN,
98
    TARGET_SIGTTOU,
99
    TARGET_SIGIO,
100
    TARGET_SIGXCPU,
101
    TARGET_SIGXFSZ,
102
    TARGET_SIGVTALRM,
103
    TARGET_SIGPROF,
104
    TARGET_SIGWINCH,
105
    -1, /* SIGLOST */
106
    TARGET_SIGUSR1,
107
    TARGET_SIGUSR2,
108
#ifdef TARGET_SIGPWR
109
    TARGET_SIGPWR,
110
#else
111
    -1,
112
#endif
113
    -1, /* SIGPOLL */
114
    -1,
115
    -1,
116
    -1,
117
    -1,
118
    -1,
119
    -1,
120
    -1,
121
    -1,
122
    -1,
123
    -1,
124
    -1,
125
#ifdef __SIGRTMIN
126
    __SIGRTMIN + 1,
127
    __SIGRTMIN + 2,
128
    __SIGRTMIN + 3,
129
    __SIGRTMIN + 4,
130
    __SIGRTMIN + 5,
131
    __SIGRTMIN + 6,
132
    __SIGRTMIN + 7,
133
    __SIGRTMIN + 8,
134
    __SIGRTMIN + 9,
135
    __SIGRTMIN + 10,
136
    __SIGRTMIN + 11,
137
    __SIGRTMIN + 12,
138
    __SIGRTMIN + 13,
139
    __SIGRTMIN + 14,
140
    __SIGRTMIN + 15,
141
    __SIGRTMIN + 16,
142
    __SIGRTMIN + 17,
143
    __SIGRTMIN + 18,
144
    __SIGRTMIN + 19,
145
    __SIGRTMIN + 20,
146
    __SIGRTMIN + 21,
147
    __SIGRTMIN + 22,
148
    __SIGRTMIN + 23,
149
    __SIGRTMIN + 24,
150
    __SIGRTMIN + 25,
151
    __SIGRTMIN + 26,
152
    __SIGRTMIN + 27,
153
    __SIGRTMIN + 28,
154
    __SIGRTMIN + 29,
155
    __SIGRTMIN + 30,
156
    __SIGRTMIN + 31,
157
    -1, /* SIGCANCEL */
158
    __SIGRTMIN,
159
    __SIGRTMIN + 32,
160
    __SIGRTMIN + 33,
161
    __SIGRTMIN + 34,
162
    __SIGRTMIN + 35,
163
    __SIGRTMIN + 36,
164
    __SIGRTMIN + 37,
165
    __SIGRTMIN + 38,
166
    __SIGRTMIN + 39,
167
    __SIGRTMIN + 40,
168
    __SIGRTMIN + 41,
169
    __SIGRTMIN + 42,
170
    __SIGRTMIN + 43,
171
    __SIGRTMIN + 44,
172
    __SIGRTMIN + 45,
173
    __SIGRTMIN + 46,
174
    __SIGRTMIN + 47,
175
    __SIGRTMIN + 48,
176
    __SIGRTMIN + 49,
177
    __SIGRTMIN + 50,
178
    __SIGRTMIN + 51,
179
    __SIGRTMIN + 52,
180
    __SIGRTMIN + 53,
181
    __SIGRTMIN + 54,
182
    __SIGRTMIN + 55,
183
    __SIGRTMIN + 56,
184
    __SIGRTMIN + 57,
185
    __SIGRTMIN + 58,
186
    __SIGRTMIN + 59,
187
    __SIGRTMIN + 60,
188
    __SIGRTMIN + 61,
189
    __SIGRTMIN + 62,
190
    __SIGRTMIN + 63,
191
    __SIGRTMIN + 64,
192
    __SIGRTMIN + 65,
193
    __SIGRTMIN + 66,
194
    __SIGRTMIN + 67,
195
    __SIGRTMIN + 68,
196
    __SIGRTMIN + 69,
197
    __SIGRTMIN + 70,
198
    __SIGRTMIN + 71,
199
    __SIGRTMIN + 72,
200
    __SIGRTMIN + 73,
201
    __SIGRTMIN + 74,
202
    __SIGRTMIN + 75,
203
    __SIGRTMIN + 76,
204
    __SIGRTMIN + 77,
205
    __SIGRTMIN + 78,
206
    __SIGRTMIN + 79,
207
    __SIGRTMIN + 80,
208
    __SIGRTMIN + 81,
209
    __SIGRTMIN + 82,
210
    __SIGRTMIN + 83,
211
    __SIGRTMIN + 84,
212
    __SIGRTMIN + 85,
213
    __SIGRTMIN + 86,
214
    __SIGRTMIN + 87,
215
    __SIGRTMIN + 88,
216
    __SIGRTMIN + 89,
217
    __SIGRTMIN + 90,
218
    __SIGRTMIN + 91,
219
    __SIGRTMIN + 92,
220
    __SIGRTMIN + 93,
221
    __SIGRTMIN + 94,
222
    __SIGRTMIN + 95,
223
    -1, /* SIGINFO */
224
    -1, /* UNKNOWN */
225
    -1, /* DEFAULT */
226
    -1,
227
    -1,
228
    -1,
229
    -1,
230
    -1,
231
    -1
232
#endif
233
};
234
#else
235
/* In system mode we only need SIGINT and SIGTRAP; other signals
236
   are not yet supported.  */
237

    
238
enum {
239
    TARGET_SIGINT = 2,
240
    TARGET_SIGTRAP = 5
241
};
242

    
243
static int gdb_signal_table[] = {
244
    -1,
245
    -1,
246
    TARGET_SIGINT,
247
    -1,
248
    -1,
249
    TARGET_SIGTRAP
250
};
251
#endif
252

    
253
#ifdef CONFIG_USER_ONLY
254
static int target_signal_to_gdb (int sig)
255
{
256
    int i;
257
    for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
258
        if (gdb_signal_table[i] == sig)
259
            return i;
260
    return GDB_SIGNAL_UNKNOWN;
261
}
262
#endif
263

    
264
static int gdb_signal_to_target (int sig)
265
{
266
    if (sig < ARRAY_SIZE (gdb_signal_table))
267
        return gdb_signal_table[sig];
268
    else
269
        return -1;
270
}
271

    
272
//#define DEBUG_GDB
273

    
274
typedef struct GDBRegisterState {
275
    int base_reg;
276
    int num_regs;
277
    gdb_reg_cb get_reg;
278
    gdb_reg_cb set_reg;
279
    const char *xml;
280
    struct GDBRegisterState *next;
281
} GDBRegisterState;
282

    
283
enum RSState {
284
    RS_INACTIVE,
285
    RS_IDLE,
286
    RS_GETLINE,
287
    RS_CHKSUM1,
288
    RS_CHKSUM2,
289
};
290
typedef struct GDBState {
291
    CPUState *c_cpu; /* current CPU for step/continue ops */
292
    CPUState *g_cpu; /* current CPU for other ops */
293
    CPUState *query_cpu; /* for q{f|s}ThreadInfo */
294
    enum RSState state; /* parsing state */
295
    char line_buf[MAX_PACKET_LENGTH];
296
    int line_buf_index;
297
    int line_csum;
298
    uint8_t last_packet[MAX_PACKET_LENGTH + 4];
299
    int last_packet_len;
300
    int signal;
301
#ifdef CONFIG_USER_ONLY
302
    int fd;
303
    int running_state;
304
#else
305
    CharDriverState *chr;
306
    CharDriverState *mon_chr;
307
#endif
308
    char syscall_buf[256];
309
    gdb_syscall_complete_cb current_syscall_cb;
310
} GDBState;
311

    
312
/* By default use no IRQs and no timers while single stepping so as to
313
 * make single stepping like an ICE HW step.
314
 */
315
static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
316

    
317
static GDBState *gdbserver_state;
318

    
319
/* This is an ugly hack to cope with both new and old gdb.
320
   If gdb sends qXfer:features:read then assume we're talking to a newish
321
   gdb that understands target descriptions.  */
322
static int gdb_has_xml;
323

    
324
#ifdef CONFIG_USER_ONLY
325
/* XXX: This is not thread safe.  Do we care?  */
326
static int gdbserver_fd = -1;
327

    
328
static int get_char(GDBState *s)
329
{
330
    uint8_t ch;
331
    int ret;
332

    
333
    for(;;) {
334
        ret = qemu_recv(s->fd, &ch, 1, 0);
335
        if (ret < 0) {
336
            if (errno == ECONNRESET)
337
                s->fd = -1;
338
            if (errno != EINTR && errno != EAGAIN)
339
                return -1;
340
        } else if (ret == 0) {
341
            close(s->fd);
342
            s->fd = -1;
343
            return -1;
344
        } else {
345
            break;
346
        }
347
    }
348
    return ch;
349
}
350
#endif
351

    
352
static enum {
353
    GDB_SYS_UNKNOWN,
354
    GDB_SYS_ENABLED,
355
    GDB_SYS_DISABLED,
356
} gdb_syscall_mode;
357

    
358
/* If gdb is connected when the first semihosting syscall occurs then use
359
   remote gdb syscalls.  Otherwise use native file IO.  */
360
int use_gdb_syscalls(void)
361
{
362
    if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
363
        gdb_syscall_mode = (gdbserver_state ? GDB_SYS_ENABLED
364
                                            : GDB_SYS_DISABLED);
365
    }
366
    return gdb_syscall_mode == GDB_SYS_ENABLED;
367
}
368

    
369
/* Resume execution.  */
370
static inline void gdb_continue(GDBState *s)
371
{
372
#ifdef CONFIG_USER_ONLY
373
    s->running_state = 1;
374
#else
375
    if (runstate_check(RUN_STATE_GUEST_PANICKED)) {
376
        runstate_set(RUN_STATE_DEBUG);
377
    }
378
    if (!runstate_needs_reset()) {
379
        vm_start();
380
    }
381
#endif
382
}
383

    
384
static void put_buffer(GDBState *s, const uint8_t *buf, int len)
385
{
386
#ifdef CONFIG_USER_ONLY
387
    int ret;
388

    
389
    while (len > 0) {
390
        ret = send(s->fd, buf, len, 0);
391
        if (ret < 0) {
392
            if (errno != EINTR && errno != EAGAIN)
393
                return;
394
        } else {
395
            buf += ret;
396
            len -= ret;
397
        }
398
    }
399
#else
400
    qemu_chr_fe_write(s->chr, buf, len);
401
#endif
402
}
403

    
404
static inline int fromhex(int v)
405
{
406
    if (v >= '0' && v <= '9')
407
        return v - '0';
408
    else if (v >= 'A' && v <= 'F')
409
        return v - 'A' + 10;
410
    else if (v >= 'a' && v <= 'f')
411
        return v - 'a' + 10;
412
    else
413
        return 0;
414
}
415

    
416
static inline int tohex(int v)
417
{
418
    if (v < 10)
419
        return v + '0';
420
    else
421
        return v - 10 + 'a';
422
}
423

    
424
static void memtohex(char *buf, const uint8_t *mem, int len)
425
{
426
    int i, c;
427
    char *q;
428
    q = buf;
429
    for(i = 0; i < len; i++) {
430
        c = mem[i];
431
        *q++ = tohex(c >> 4);
432
        *q++ = tohex(c & 0xf);
433
    }
434
    *q = '\0';
435
}
436

    
437
static void hextomem(uint8_t *mem, const char *buf, int len)
438
{
439
    int i;
440

    
441
    for(i = 0; i < len; i++) {
442
        mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
443
        buf += 2;
444
    }
445
}
446

    
447
/* return -1 if error, 0 if OK */
448
static int put_packet_binary(GDBState *s, const char *buf, int len)
449
{
450
    int csum, i;
451
    uint8_t *p;
452

    
453
    for(;;) {
454
        p = s->last_packet;
455
        *(p++) = '$';
456
        memcpy(p, buf, len);
457
        p += len;
458
        csum = 0;
459
        for(i = 0; i < len; i++) {
460
            csum += buf[i];
461
        }
462
        *(p++) = '#';
463
        *(p++) = tohex((csum >> 4) & 0xf);
464
        *(p++) = tohex((csum) & 0xf);
465

    
466
        s->last_packet_len = p - s->last_packet;
467
        put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
468

    
469
#ifdef CONFIG_USER_ONLY
470
        i = get_char(s);
471
        if (i < 0)
472
            return -1;
473
        if (i == '+')
474
            break;
475
#else
476
        break;
477
#endif
478
    }
479
    return 0;
480
}
481

    
482
/* return -1 if error, 0 if OK */
483
static int put_packet(GDBState *s, const char *buf)
484
{
485
#ifdef DEBUG_GDB
486
    printf("reply='%s'\n", buf);
487
#endif
488

    
489
    return put_packet_binary(s, buf, strlen(buf));
490
}
491

    
492
#if defined(TARGET_I386)
493

    
494
#include "target-i386/gdbstub.c"
495

    
496
#elif defined (TARGET_PPC)
497

    
498
#if defined (TARGET_PPC64)
499
#define GDB_CORE_XML "power64-core.xml"
500
#else
501
#define GDB_CORE_XML "power-core.xml"
502
#endif
503

    
504
#include "target-ppc/gdbstub.c"
505

    
506
#elif defined (TARGET_SPARC)
507

    
508
#include "target-sparc/gdbstub.c"
509

    
510
#elif defined (TARGET_ARM)
511

    
512
#define GDB_CORE_XML "arm-core.xml"
513

    
514
#include "target-arm/gdbstub.c"
515

    
516
#elif defined (TARGET_M68K)
517

    
518
#define GDB_CORE_XML "cf-core.xml"
519

    
520
#include "target-m68k/gdbstub.c"
521

    
522
#elif defined (TARGET_MIPS)
523

    
524
#include "target-mips/gdbstub.c"
525

    
526
#elif defined(TARGET_OPENRISC)
527

    
528
#include "target-openrisc/gdbstub.c"
529

    
530
#elif defined (TARGET_SH4)
531

    
532
#include "target-sh4/gdbstub.c"
533

    
534
#elif defined (TARGET_MICROBLAZE)
535

    
536
#include "target-microblaze/gdbstub.c"
537

    
538
#elif defined (TARGET_CRIS)
539

    
540
#include "target-cris/gdbstub.c"
541

    
542
#elif defined (TARGET_ALPHA)
543

    
544
#include "target-alpha/gdbstub.c"
545

    
546
#elif defined (TARGET_S390X)
547

    
548
#include "target-s390x/gdbstub.c"
549

    
550
#elif defined (TARGET_LM32)
551

    
552
#include "target-lm32/gdbstub.c"
553

    
554
#elif defined(TARGET_XTENSA)
555

    
556
#include "target-xtensa/gdbstub.c"
557

    
558
#else
559

    
560
static int cpu_gdb_read_register(CPUArchState *env, uint8_t *mem_buf, int n)
561
{
562
    return 0;
563
}
564

    
565
static int cpu_gdb_write_register(CPUArchState *env, uint8_t *mem_buf, int n)
566
{
567
    return 0;
568
}
569

    
570
#endif
571

    
572
#ifdef GDB_CORE_XML
573
/* Encode data using the encoding for 'x' packets.  */
574
static int memtox(char *buf, const char *mem, int len)
575
{
576
    char *p = buf;
577
    char c;
578

    
579
    while (len--) {
580
        c = *(mem++);
581
        switch (c) {
582
        case '#': case '$': case '*': case '}':
583
            *(p++) = '}';
584
            *(p++) = c ^ 0x20;
585
            break;
586
        default:
587
            *(p++) = c;
588
            break;
589
        }
590
    }
591
    return p - buf;
592
}
593

    
594
static const char *get_feature_xml(const char *p, const char **newp)
595
{
596
    size_t len;
597
    int i;
598
    const char *name;
599
    static char target_xml[1024];
600

    
601
    len = 0;
602
    while (p[len] && p[len] != ':')
603
        len++;
604
    *newp = p + len;
605

    
606
    name = NULL;
607
    if (strncmp(p, "target.xml", len) == 0) {
608
        /* Generate the XML description for this CPU.  */
609
        if (!target_xml[0]) {
610
            GDBRegisterState *r;
611
            CPUState *cpu = first_cpu;
612

    
613
            snprintf(target_xml, sizeof(target_xml),
614
                     "<?xml version=\"1.0\"?>"
615
                     "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
616
                     "<target>"
617
                     "<xi:include href=\"%s\"/>",
618
                     GDB_CORE_XML);
619

    
620
            for (r = cpu->gdb_regs; r; r = r->next) {
621
                pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
622
                pstrcat(target_xml, sizeof(target_xml), r->xml);
623
                pstrcat(target_xml, sizeof(target_xml), "\"/>");
624
            }
625
            pstrcat(target_xml, sizeof(target_xml), "</target>");
626
        }
627
        return target_xml;
628
    }
629
    for (i = 0; ; i++) {
630
        name = xml_builtin[i][0];
631
        if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
632
            break;
633
    }
634
    return name ? xml_builtin[i][1] : NULL;
635
}
636
#endif
637

    
638
static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
639
{
640
    CPUClass *cc = CPU_GET_CLASS(cpu);
641
    CPUArchState *env = cpu->env_ptr;
642
    GDBRegisterState *r;
643

    
644
    if (reg < cc->gdb_num_core_regs) {
645
        return cpu_gdb_read_register(env, mem_buf, reg);
646
    }
647

    
648
    for (r = cpu->gdb_regs; r; r = r->next) {
649
        if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
650
            return r->get_reg(env, mem_buf, reg - r->base_reg);
651
        }
652
    }
653
    return 0;
654
}
655

    
656
static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
657
{
658
    CPUClass *cc = CPU_GET_CLASS(cpu);
659
    CPUArchState *env = cpu->env_ptr;
660
    GDBRegisterState *r;
661

    
662
    if (reg < cc->gdb_num_core_regs) {
663
        return cpu_gdb_write_register(env, mem_buf, reg);
664
    }
665

    
666
    for (r = cpu->gdb_regs; r; r = r->next) {
667
        if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
668
            return r->set_reg(env, mem_buf, reg - r->base_reg);
669
        }
670
    }
671
    return 0;
672
}
673

    
674
/* Register a supplemental set of CPU registers.  If g_pos is nonzero it
675
   specifies the first register number and these registers are included in
676
   a standard "g" packet.  Direction is relative to gdb, i.e. get_reg is
677
   gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
678
 */
679

    
680
void gdb_register_coprocessor(CPUState *cpu,
681
                              gdb_reg_cb get_reg, gdb_reg_cb set_reg,
682
                              int num_regs, const char *xml, int g_pos)
683
{
684
    GDBRegisterState *s;
685
    GDBRegisterState **p;
686

    
687
    p = &cpu->gdb_regs;
688
    while (*p) {
689
        /* Check for duplicates.  */
690
        if (strcmp((*p)->xml, xml) == 0)
691
            return;
692
        p = &(*p)->next;
693
    }
694

    
695
    s = g_new0(GDBRegisterState, 1);
696
    s->base_reg = cpu->gdb_num_regs;
697
    s->num_regs = num_regs;
698
    s->get_reg = get_reg;
699
    s->set_reg = set_reg;
700
    s->xml = xml;
701

    
702
    /* Add to end of list.  */
703
    cpu->gdb_num_regs += num_regs;
704
    *p = s;
705
    if (g_pos) {
706
        if (g_pos != s->base_reg) {
707
            fprintf(stderr, "Error: Bad gdb register numbering for '%s'\n"
708
                    "Expected %d got %d\n", xml, g_pos, s->base_reg);
709
        }
710
    }
711
}
712

    
713
#ifndef CONFIG_USER_ONLY
714
static const int xlat_gdb_type[] = {
715
    [GDB_WATCHPOINT_WRITE]  = BP_GDB | BP_MEM_WRITE,
716
    [GDB_WATCHPOINT_READ]   = BP_GDB | BP_MEM_READ,
717
    [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
718
};
719
#endif
720

    
721
static int gdb_breakpoint_insert(target_ulong addr, target_ulong len, int type)
722
{
723
    CPUState *cpu;
724
    CPUArchState *env;
725
    int err = 0;
726

    
727
    if (kvm_enabled()) {
728
        return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
729
    }
730

    
731
    switch (type) {
732
    case GDB_BREAKPOINT_SW:
733
    case GDB_BREAKPOINT_HW:
734
        for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
735
            env = cpu->env_ptr;
736
            err = cpu_breakpoint_insert(env, addr, BP_GDB, NULL);
737
            if (err)
738
                break;
739
        }
740
        return err;
741
#ifndef CONFIG_USER_ONLY
742
    case GDB_WATCHPOINT_WRITE:
743
    case GDB_WATCHPOINT_READ:
744
    case GDB_WATCHPOINT_ACCESS:
745
        for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
746
            env = cpu->env_ptr;
747
            err = cpu_watchpoint_insert(env, addr, len, xlat_gdb_type[type],
748
                                        NULL);
749
            if (err)
750
                break;
751
        }
752
        return err;
753
#endif
754
    default:
755
        return -ENOSYS;
756
    }
757
}
758

    
759
static int gdb_breakpoint_remove(target_ulong addr, target_ulong len, int type)
760
{
761
    CPUState *cpu;
762
    CPUArchState *env;
763
    int err = 0;
764

    
765
    if (kvm_enabled()) {
766
        return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
767
    }
768

    
769
    switch (type) {
770
    case GDB_BREAKPOINT_SW:
771
    case GDB_BREAKPOINT_HW:
772
        for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
773
            env = cpu->env_ptr;
774
            err = cpu_breakpoint_remove(env, addr, BP_GDB);
775
            if (err)
776
                break;
777
        }
778
        return err;
779
#ifndef CONFIG_USER_ONLY
780
    case GDB_WATCHPOINT_WRITE:
781
    case GDB_WATCHPOINT_READ:
782
    case GDB_WATCHPOINT_ACCESS:
783
        for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
784
            env = cpu->env_ptr;
785
            err = cpu_watchpoint_remove(env, addr, len, xlat_gdb_type[type]);
786
            if (err)
787
                break;
788
        }
789
        return err;
790
#endif
791
    default:
792
        return -ENOSYS;
793
    }
794
}
795

    
796
static void gdb_breakpoint_remove_all(void)
797
{
798
    CPUState *cpu;
799
    CPUArchState *env;
800

    
801
    if (kvm_enabled()) {
802
        kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
803
        return;
804
    }
805

    
806
    for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
807
        env = cpu->env_ptr;
808
        cpu_breakpoint_remove_all(env, BP_GDB);
809
#ifndef CONFIG_USER_ONLY
810
        cpu_watchpoint_remove_all(env, BP_GDB);
811
#endif
812
    }
813
}
814

    
815
static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
816
{
817
    CPUState *cpu = s->c_cpu;
818
    CPUClass *cc = CPU_GET_CLASS(cpu);
819

    
820
    cpu_synchronize_state(cpu);
821
    if (cc->set_pc) {
822
        cc->set_pc(cpu, pc);
823
    }
824
}
825

    
826
static CPUState *find_cpu(uint32_t thread_id)
827
{
828
    CPUState *cpu;
829

    
830
    for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {
831
        if (cpu_index(cpu) == thread_id) {
832
            return cpu;
833
        }
834
    }
835

    
836
    return NULL;
837
}
838

    
839
static int gdb_handle_packet(GDBState *s, const char *line_buf)
840
{
841
    CPUState *cpu;
842
    const char *p;
843
    uint32_t thread;
844
    int ch, reg_size, type, res;
845
    char buf[MAX_PACKET_LENGTH];
846
    uint8_t mem_buf[MAX_PACKET_LENGTH];
847
    uint8_t *registers;
848
    target_ulong addr, len;
849

    
850
#ifdef DEBUG_GDB
851
    printf("command='%s'\n", line_buf);
852
#endif
853
    p = line_buf;
854
    ch = *p++;
855
    switch(ch) {
856
    case '?':
857
        /* TODO: Make this return the correct value for user-mode.  */
858
        snprintf(buf, sizeof(buf), "T%02xthread:%02x;", GDB_SIGNAL_TRAP,
859
                 cpu_index(s->c_cpu));
860
        put_packet(s, buf);
861
        /* Remove all the breakpoints when this query is issued,
862
         * because gdb is doing and initial connect and the state
863
         * should be cleaned up.
864
         */
865
        gdb_breakpoint_remove_all();
866
        break;
867
    case 'c':
868
        if (*p != '\0') {
869
            addr = strtoull(p, (char **)&p, 16);
870
            gdb_set_cpu_pc(s, addr);
871
        }
872
        s->signal = 0;
873
        gdb_continue(s);
874
        return RS_IDLE;
875
    case 'C':
876
        s->signal = gdb_signal_to_target (strtoul(p, (char **)&p, 16));
877
        if (s->signal == -1)
878
            s->signal = 0;
879
        gdb_continue(s);
880
        return RS_IDLE;
881
    case 'v':
882
        if (strncmp(p, "Cont", 4) == 0) {
883
            int res_signal, res_thread;
884

    
885
            p += 4;
886
            if (*p == '?') {
887
                put_packet(s, "vCont;c;C;s;S");
888
                break;
889
            }
890
            res = 0;
891
            res_signal = 0;
892
            res_thread = 0;
893
            while (*p) {
894
                int action, signal;
895

    
896
                if (*p++ != ';') {
897
                    res = 0;
898
                    break;
899
                }
900
                action = *p++;
901
                signal = 0;
902
                if (action == 'C' || action == 'S') {
903
                    signal = strtoul(p, (char **)&p, 16);
904
                } else if (action != 'c' && action != 's') {
905
                    res = 0;
906
                    break;
907
                }
908
                thread = 0;
909
                if (*p == ':') {
910
                    thread = strtoull(p+1, (char **)&p, 16);
911
                }
912
                action = tolower(action);
913
                if (res == 0 || (res == 'c' && action == 's')) {
914
                    res = action;
915
                    res_signal = signal;
916
                    res_thread = thread;
917
                }
918
            }
919
            if (res) {
920
                if (res_thread != -1 && res_thread != 0) {
921
                    cpu = find_cpu(res_thread);
922
                    if (cpu == NULL) {
923
                        put_packet(s, "E22");
924
                        break;
925
                    }
926
                    s->c_cpu = cpu;
927
                }
928
                if (res == 's') {
929
                    cpu_single_step(s->c_cpu, sstep_flags);
930
                }
931
                s->signal = res_signal;
932
                gdb_continue(s);
933
                return RS_IDLE;
934
            }
935
            break;
936
        } else {
937
            goto unknown_command;
938
        }
939
    case 'k':
940
#ifdef CONFIG_USER_ONLY
941
        /* Kill the target */
942
        fprintf(stderr, "\nQEMU: Terminated via GDBstub\n");
943
        exit(0);
944
#endif
945
    case 'D':
946
        /* Detach packet */
947
        gdb_breakpoint_remove_all();
948
        gdb_syscall_mode = GDB_SYS_DISABLED;
949
        gdb_continue(s);
950
        put_packet(s, "OK");
951
        break;
952
    case 's':
953
        if (*p != '\0') {
954
            addr = strtoull(p, (char **)&p, 16);
955
            gdb_set_cpu_pc(s, addr);
956
        }
957
        cpu_single_step(s->c_cpu, sstep_flags);
958
        gdb_continue(s);
959
        return RS_IDLE;
960
    case 'F':
961
        {
962
            target_ulong ret;
963
            target_ulong err;
964

    
965
            ret = strtoull(p, (char **)&p, 16);
966
            if (*p == ',') {
967
                p++;
968
                err = strtoull(p, (char **)&p, 16);
969
            } else {
970
                err = 0;
971
            }
972
            if (*p == ',')
973
                p++;
974
            type = *p;
975
            if (s->current_syscall_cb) {
976
                s->current_syscall_cb(s->c_cpu, ret, err);
977
                s->current_syscall_cb = NULL;
978
            }
979
            if (type == 'C') {
980
                put_packet(s, "T02");
981
            } else {
982
                gdb_continue(s);
983
            }
984
        }
985
        break;
986
    case 'g':
987
        cpu_synchronize_state(s->g_cpu);
988
        len = 0;
989
        for (addr = 0; addr < s->g_cpu->gdb_num_regs; addr++) {
990
            reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);
991
            len += reg_size;
992
        }
993
        memtohex(buf, mem_buf, len);
994
        put_packet(s, buf);
995
        break;
996
    case 'G':
997
        cpu_synchronize_state(s->g_cpu);
998
        registers = mem_buf;
999
        len = strlen(p) / 2;
1000
        hextomem((uint8_t *)registers, p, len);
1001
        for (addr = 0; addr < s->g_cpu->gdb_num_regs && len > 0; addr++) {
1002
            reg_size = gdb_write_register(s->g_cpu, registers, addr);
1003
            len -= reg_size;
1004
            registers += reg_size;
1005
        }
1006
        put_packet(s, "OK");
1007
        break;
1008
    case 'm':
1009
        addr = strtoull(p, (char **)&p, 16);
1010
        if (*p == ',')
1011
            p++;
1012
        len = strtoull(p, NULL, 16);
1013
        if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len, false) != 0) {
1014
            put_packet (s, "E14");
1015
        } else {
1016
            memtohex(buf, mem_buf, len);
1017
            put_packet(s, buf);
1018
        }
1019
        break;
1020
    case 'M':
1021
        addr = strtoull(p, (char **)&p, 16);
1022
        if (*p == ',')
1023
            p++;
1024
        len = strtoull(p, (char **)&p, 16);
1025
        if (*p == ':')
1026
            p++;
1027
        hextomem(mem_buf, p, len);
1028
        if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len,
1029
                                   true) != 0) {
1030
            put_packet(s, "E14");
1031
        } else {
1032
            put_packet(s, "OK");
1033
        }
1034
        break;
1035
    case 'p':
1036
        /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
1037
           This works, but can be very slow.  Anything new enough to
1038
           understand XML also knows how to use this properly.  */
1039
        if (!gdb_has_xml)
1040
            goto unknown_command;
1041
        addr = strtoull(p, (char **)&p, 16);
1042
        reg_size = gdb_read_register(s->g_cpu, mem_buf, addr);
1043
        if (reg_size) {
1044
            memtohex(buf, mem_buf, reg_size);
1045
            put_packet(s, buf);
1046
        } else {
1047
            put_packet(s, "E14");
1048
        }
1049
        break;
1050
    case 'P':
1051
        if (!gdb_has_xml)
1052
            goto unknown_command;
1053
        addr = strtoull(p, (char **)&p, 16);
1054
        if (*p == '=')
1055
            p++;
1056
        reg_size = strlen(p) / 2;
1057
        hextomem(mem_buf, p, reg_size);
1058
        gdb_write_register(s->g_cpu, mem_buf, addr);
1059
        put_packet(s, "OK");
1060
        break;
1061
    case 'Z':
1062
    case 'z':
1063
        type = strtoul(p, (char **)&p, 16);
1064
        if (*p == ',')
1065
            p++;
1066
        addr = strtoull(p, (char **)&p, 16);
1067
        if (*p == ',')
1068
            p++;
1069
        len = strtoull(p, (char **)&p, 16);
1070
        if (ch == 'Z')
1071
            res = gdb_breakpoint_insert(addr, len, type);
1072
        else
1073
            res = gdb_breakpoint_remove(addr, len, type);
1074
        if (res >= 0)
1075
             put_packet(s, "OK");
1076
        else if (res == -ENOSYS)
1077
            put_packet(s, "");
1078
        else
1079
            put_packet(s, "E22");
1080
        break;
1081
    case 'H':
1082
        type = *p++;
1083
        thread = strtoull(p, (char **)&p, 16);
1084
        if (thread == -1 || thread == 0) {
1085
            put_packet(s, "OK");
1086
            break;
1087
        }
1088
        cpu = find_cpu(thread);
1089
        if (cpu == NULL) {
1090
            put_packet(s, "E22");
1091
            break;
1092
        }
1093
        switch (type) {
1094
        case 'c':
1095
            s->c_cpu = cpu;
1096
            put_packet(s, "OK");
1097
            break;
1098
        case 'g':
1099
            s->g_cpu = cpu;
1100
            put_packet(s, "OK");
1101
            break;
1102
        default:
1103
             put_packet(s, "E22");
1104
             break;
1105
        }
1106
        break;
1107
    case 'T':
1108
        thread = strtoull(p, (char **)&p, 16);
1109
        cpu = find_cpu(thread);
1110

    
1111
        if (cpu != NULL) {
1112
            put_packet(s, "OK");
1113
        } else {
1114
            put_packet(s, "E22");
1115
        }
1116
        break;
1117
    case 'q':
1118
    case 'Q':
1119
        /* parse any 'q' packets here */
1120
        if (!strcmp(p,"qemu.sstepbits")) {
1121
            /* Query Breakpoint bit definitions */
1122
            snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1123
                     SSTEP_ENABLE,
1124
                     SSTEP_NOIRQ,
1125
                     SSTEP_NOTIMER);
1126
            put_packet(s, buf);
1127
            break;
1128
        } else if (strncmp(p,"qemu.sstep",10) == 0) {
1129
            /* Display or change the sstep_flags */
1130
            p += 10;
1131
            if (*p != '=') {
1132
                /* Display current setting */
1133
                snprintf(buf, sizeof(buf), "0x%x", sstep_flags);
1134
                put_packet(s, buf);
1135
                break;
1136
            }
1137
            p++;
1138
            type = strtoul(p, (char **)&p, 16);
1139
            sstep_flags = type;
1140
            put_packet(s, "OK");
1141
            break;
1142
        } else if (strcmp(p,"C") == 0) {
1143
            /* "Current thread" remains vague in the spec, so always return
1144
             *  the first CPU (gdb returns the first thread). */
1145
            put_packet(s, "QC1");
1146
            break;
1147
        } else if (strcmp(p,"fThreadInfo") == 0) {
1148
            s->query_cpu = first_cpu;
1149
            goto report_cpuinfo;
1150
        } else if (strcmp(p,"sThreadInfo") == 0) {
1151
        report_cpuinfo:
1152
            if (s->query_cpu) {
1153
                snprintf(buf, sizeof(buf), "m%x", cpu_index(s->query_cpu));
1154
                put_packet(s, buf);
1155
                s->query_cpu = s->query_cpu->next_cpu;
1156
            } else
1157
                put_packet(s, "l");
1158
            break;
1159
        } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {
1160
            thread = strtoull(p+16, (char **)&p, 16);
1161
            cpu = find_cpu(thread);
1162
            if (cpu != NULL) {
1163
                cpu_synchronize_state(cpu);
1164
                len = snprintf((char *)mem_buf, sizeof(mem_buf),
1165
                               "CPU#%d [%s]", cpu->cpu_index,
1166
                               cpu->halted ? "halted " : "running");
1167
                memtohex(buf, mem_buf, len);
1168
                put_packet(s, buf);
1169
            }
1170
            break;
1171
        }
1172
#ifdef CONFIG_USER_ONLY
1173
        else if (strncmp(p, "Offsets", 7) == 0) {
1174
            CPUArchState *env = s->c_cpu->env_ptr;
1175
            TaskState *ts = env->opaque;
1176

    
1177
            snprintf(buf, sizeof(buf),
1178
                     "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
1179
                     ";Bss=" TARGET_ABI_FMT_lx,
1180
                     ts->info->code_offset,
1181
                     ts->info->data_offset,
1182
                     ts->info->data_offset);
1183
            put_packet(s, buf);
1184
            break;
1185
        }
1186
#else /* !CONFIG_USER_ONLY */
1187
        else if (strncmp(p, "Rcmd,", 5) == 0) {
1188
            int len = strlen(p + 5);
1189

    
1190
            if ((len % 2) != 0) {
1191
                put_packet(s, "E01");
1192
                break;
1193
            }
1194
            hextomem(mem_buf, p + 5, len);
1195
            len = len / 2;
1196
            mem_buf[len++] = 0;
1197
            qemu_chr_be_write(s->mon_chr, mem_buf, len);
1198
            put_packet(s, "OK");
1199
            break;
1200
        }
1201
#endif /* !CONFIG_USER_ONLY */
1202
        if (strncmp(p, "Supported", 9) == 0) {
1203
            snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);
1204
#ifdef GDB_CORE_XML
1205
            pstrcat(buf, sizeof(buf), ";qXfer:features:read+");
1206
#endif
1207
            put_packet(s, buf);
1208
            break;
1209
        }
1210
#ifdef GDB_CORE_XML
1211
        if (strncmp(p, "Xfer:features:read:", 19) == 0) {
1212
            const char *xml;
1213
            target_ulong total_len;
1214

    
1215
            gdb_has_xml = 1;
1216
            p += 19;
1217
            xml = get_feature_xml(p, &p);
1218
            if (!xml) {
1219
                snprintf(buf, sizeof(buf), "E00");
1220
                put_packet(s, buf);
1221
                break;
1222
            }
1223

    
1224
            if (*p == ':')
1225
                p++;
1226
            addr = strtoul(p, (char **)&p, 16);
1227
            if (*p == ',')
1228
                p++;
1229
            len = strtoul(p, (char **)&p, 16);
1230

    
1231
            total_len = strlen(xml);
1232
            if (addr > total_len) {
1233
                snprintf(buf, sizeof(buf), "E00");
1234
                put_packet(s, buf);
1235
                break;
1236
            }
1237
            if (len > (MAX_PACKET_LENGTH - 5) / 2)
1238
                len = (MAX_PACKET_LENGTH - 5) / 2;
1239
            if (len < total_len - addr) {
1240
                buf[0] = 'm';
1241
                len = memtox(buf + 1, xml + addr, len);
1242
            } else {
1243
                buf[0] = 'l';
1244
                len = memtox(buf + 1, xml + addr, total_len - addr);
1245
            }
1246
            put_packet_binary(s, buf, len + 1);
1247
            break;
1248
        }
1249
#endif
1250
        /* Unrecognised 'q' command.  */
1251
        goto unknown_command;
1252

    
1253
    default:
1254
    unknown_command:
1255
        /* put empty packet */
1256
        buf[0] = '\0';
1257
        put_packet(s, buf);
1258
        break;
1259
    }
1260
    return RS_IDLE;
1261
}
1262

    
1263
void gdb_set_stop_cpu(CPUState *cpu)
1264
{
1265
    gdbserver_state->c_cpu = cpu;
1266
    gdbserver_state->g_cpu = cpu;
1267
}
1268

    
1269
#ifndef CONFIG_USER_ONLY
1270
static void gdb_vm_state_change(void *opaque, int running, RunState state)
1271
{
1272
    GDBState *s = gdbserver_state;
1273
    CPUArchState *env = s->c_cpu->env_ptr;
1274
    CPUState *cpu = s->c_cpu;
1275
    char buf[256];
1276
    const char *type;
1277
    int ret;
1278

    
1279
    if (running || s->state == RS_INACTIVE) {
1280
        return;
1281
    }
1282
    /* Is there a GDB syscall waiting to be sent?  */
1283
    if (s->current_syscall_cb) {
1284
        put_packet(s, s->syscall_buf);
1285
        return;
1286
    }
1287
    switch (state) {
1288
    case RUN_STATE_DEBUG:
1289
        if (env->watchpoint_hit) {
1290
            switch (env->watchpoint_hit->flags & BP_MEM_ACCESS) {
1291
            case BP_MEM_READ:
1292
                type = "r";
1293
                break;
1294
            case BP_MEM_ACCESS:
1295
                type = "a";
1296
                break;
1297
            default:
1298
                type = "";
1299
                break;
1300
            }
1301
            snprintf(buf, sizeof(buf),
1302
                     "T%02xthread:%02x;%swatch:" TARGET_FMT_lx ";",
1303
                     GDB_SIGNAL_TRAP, cpu_index(cpu), type,
1304
                     env->watchpoint_hit->vaddr);
1305
            env->watchpoint_hit = NULL;
1306
            goto send_packet;
1307
        }
1308
        tb_flush(env);
1309
        ret = GDB_SIGNAL_TRAP;
1310
        break;
1311
    case RUN_STATE_PAUSED:
1312
        ret = GDB_SIGNAL_INT;
1313
        break;
1314
    case RUN_STATE_SHUTDOWN:
1315
        ret = GDB_SIGNAL_QUIT;
1316
        break;
1317
    case RUN_STATE_IO_ERROR:
1318
        ret = GDB_SIGNAL_IO;
1319
        break;
1320
    case RUN_STATE_WATCHDOG:
1321
        ret = GDB_SIGNAL_ALRM;
1322
        break;
1323
    case RUN_STATE_INTERNAL_ERROR:
1324
        ret = GDB_SIGNAL_ABRT;
1325
        break;
1326
    case RUN_STATE_SAVE_VM:
1327
    case RUN_STATE_RESTORE_VM:
1328
        return;
1329
    case RUN_STATE_FINISH_MIGRATE:
1330
        ret = GDB_SIGNAL_XCPU;
1331
        break;
1332
    default:
1333
        ret = GDB_SIGNAL_UNKNOWN;
1334
        break;
1335
    }
1336
    snprintf(buf, sizeof(buf), "T%02xthread:%02x;", ret, cpu_index(cpu));
1337

    
1338
send_packet:
1339
    put_packet(s, buf);
1340

    
1341
    /* disable single step if it was enabled */
1342
    cpu_single_step(cpu, 0);
1343
}
1344
#endif
1345

    
1346
/* Send a gdb syscall request.
1347
   This accepts limited printf-style format specifiers, specifically:
1348
    %x  - target_ulong argument printed in hex.
1349
    %lx - 64-bit argument printed in hex.
1350
    %s  - string pointer (target_ulong) and length (int) pair.  */
1351
void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
1352
{
1353
    va_list va;
1354
    char *p;
1355
    char *p_end;
1356
    target_ulong addr;
1357
    uint64_t i64;
1358
    GDBState *s;
1359

    
1360
    s = gdbserver_state;
1361
    if (!s)
1362
        return;
1363
    s->current_syscall_cb = cb;
1364
#ifndef CONFIG_USER_ONLY
1365
    vm_stop(RUN_STATE_DEBUG);
1366
#endif
1367
    va_start(va, fmt);
1368
    p = s->syscall_buf;
1369
    p_end = &s->syscall_buf[sizeof(s->syscall_buf)];
1370
    *(p++) = 'F';
1371
    while (*fmt) {
1372
        if (*fmt == '%') {
1373
            fmt++;
1374
            switch (*fmt++) {
1375
            case 'x':
1376
                addr = va_arg(va, target_ulong);
1377
                p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
1378
                break;
1379
            case 'l':
1380
                if (*(fmt++) != 'x')
1381
                    goto bad_format;
1382
                i64 = va_arg(va, uint64_t);
1383
                p += snprintf(p, p_end - p, "%" PRIx64, i64);
1384
                break;
1385
            case 's':
1386
                addr = va_arg(va, target_ulong);
1387
                p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
1388
                              addr, va_arg(va, int));
1389
                break;
1390
            default:
1391
            bad_format:
1392
                fprintf(stderr, "gdbstub: Bad syscall format string '%s'\n",
1393
                        fmt - 1);
1394
                break;
1395
            }
1396
        } else {
1397
            *(p++) = *(fmt++);
1398
        }
1399
    }
1400
    *p = 0;
1401
    va_end(va);
1402
#ifdef CONFIG_USER_ONLY
1403
    put_packet(s, s->syscall_buf);
1404
    gdb_handlesig(s->c_cpu, 0);
1405
#else
1406
    /* In this case wait to send the syscall packet until notification that
1407
       the CPU has stopped.  This must be done because if the packet is sent
1408
       now the reply from the syscall request could be received while the CPU
1409
       is still in the running state, which can cause packets to be dropped
1410
       and state transition 'T' packets to be sent while the syscall is still
1411
       being processed.  */
1412
    cpu_exit(s->c_cpu);
1413
#endif
1414
}
1415

    
1416
static void gdb_read_byte(GDBState *s, int ch)
1417
{
1418
    int i, csum;
1419
    uint8_t reply;
1420

    
1421
#ifndef CONFIG_USER_ONLY
1422
    if (s->last_packet_len) {
1423
        /* Waiting for a response to the last packet.  If we see the start
1424
           of a new command then abandon the previous response.  */
1425
        if (ch == '-') {
1426
#ifdef DEBUG_GDB
1427
            printf("Got NACK, retransmitting\n");
1428
#endif
1429
            put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
1430
        }
1431
#ifdef DEBUG_GDB
1432
        else if (ch == '+')
1433
            printf("Got ACK\n");
1434
        else
1435
            printf("Got '%c' when expecting ACK/NACK\n", ch);
1436
#endif
1437
        if (ch == '+' || ch == '$')
1438
            s->last_packet_len = 0;
1439
        if (ch != '$')
1440
            return;
1441
    }
1442
    if (runstate_is_running()) {
1443
        /* when the CPU is running, we cannot do anything except stop
1444
           it when receiving a char */
1445
        vm_stop(RUN_STATE_PAUSED);
1446
    } else
1447
#endif
1448
    {
1449
        switch(s->state) {
1450
        case RS_IDLE:
1451
            if (ch == '$') {
1452
                s->line_buf_index = 0;
1453
                s->state = RS_GETLINE;
1454
            }
1455
            break;
1456
        case RS_GETLINE:
1457
            if (ch == '#') {
1458
            s->state = RS_CHKSUM1;
1459
            } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
1460
                s->state = RS_IDLE;
1461
            } else {
1462
            s->line_buf[s->line_buf_index++] = ch;
1463
            }
1464
            break;
1465
        case RS_CHKSUM1:
1466
            s->line_buf[s->line_buf_index] = '\0';
1467
            s->line_csum = fromhex(ch) << 4;
1468
            s->state = RS_CHKSUM2;
1469
            break;
1470
        case RS_CHKSUM2:
1471
            s->line_csum |= fromhex(ch);
1472
            csum = 0;
1473
            for(i = 0; i < s->line_buf_index; i++) {
1474
                csum += s->line_buf[i];
1475
            }
1476
            if (s->line_csum != (csum & 0xff)) {
1477
                reply = '-';
1478
                put_buffer(s, &reply, 1);
1479
                s->state = RS_IDLE;
1480
            } else {
1481
                reply = '+';
1482
                put_buffer(s, &reply, 1);
1483
                s->state = gdb_handle_packet(s, s->line_buf);
1484
            }
1485
            break;
1486
        default:
1487
            abort();
1488
        }
1489
    }
1490
}
1491

    
1492
/* Tell the remote gdb that the process has exited.  */
1493
void gdb_exit(CPUArchState *env, int code)
1494
{
1495
  GDBState *s;
1496
  char buf[4];
1497

    
1498
  s = gdbserver_state;
1499
  if (!s) {
1500
      return;
1501
  }
1502
#ifdef CONFIG_USER_ONLY
1503
  if (gdbserver_fd < 0 || s->fd < 0) {
1504
      return;
1505
  }
1506
#endif
1507

    
1508
  snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
1509
  put_packet(s, buf);
1510

    
1511
#ifndef CONFIG_USER_ONLY
1512
  if (s->chr) {
1513
      qemu_chr_delete(s->chr);
1514
  }
1515
#endif
1516
}
1517

    
1518
#ifdef CONFIG_USER_ONLY
1519
int
1520
gdb_queuesig (void)
1521
{
1522
    GDBState *s;
1523

    
1524
    s = gdbserver_state;
1525

    
1526
    if (gdbserver_fd < 0 || s->fd < 0)
1527
        return 0;
1528
    else
1529
        return 1;
1530
}
1531

    
1532
int
1533
gdb_handlesig(CPUState *cpu, int sig)
1534
{
1535
    CPUArchState *env = cpu->env_ptr;
1536
    GDBState *s;
1537
    char buf[256];
1538
    int n;
1539

    
1540
    s = gdbserver_state;
1541
    if (gdbserver_fd < 0 || s->fd < 0) {
1542
        return sig;
1543
    }
1544

    
1545
    /* disable single step if it was enabled */
1546
    cpu_single_step(cpu, 0);
1547
    tb_flush(env);
1548

    
1549
    if (sig != 0) {
1550
        snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
1551
        put_packet(s, buf);
1552
    }
1553
    /* put_packet() might have detected that the peer terminated the
1554
       connection.  */
1555
    if (s->fd < 0) {
1556
        return sig;
1557
    }
1558

    
1559
    sig = 0;
1560
    s->state = RS_IDLE;
1561
    s->running_state = 0;
1562
    while (s->running_state == 0) {
1563
        n = read(s->fd, buf, 256);
1564
        if (n > 0) {
1565
            int i;
1566

    
1567
            for (i = 0; i < n; i++) {
1568
                gdb_read_byte(s, buf[i]);
1569
            }
1570
        } else if (n == 0 || errno != EAGAIN) {
1571
            /* XXX: Connection closed.  Should probably wait for another
1572
               connection before continuing.  */
1573
            return sig;
1574
        }
1575
    }
1576
    sig = s->signal;
1577
    s->signal = 0;
1578
    return sig;
1579
}
1580

    
1581
/* Tell the remote gdb that the process has exited due to SIG.  */
1582
void gdb_signalled(CPUArchState *env, int sig)
1583
{
1584
    GDBState *s;
1585
    char buf[4];
1586

    
1587
    s = gdbserver_state;
1588
    if (gdbserver_fd < 0 || s->fd < 0) {
1589
        return;
1590
    }
1591

    
1592
    snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
1593
    put_packet(s, buf);
1594
}
1595

    
1596
static void gdb_accept(void)
1597
{
1598
    GDBState *s;
1599
    struct sockaddr_in sockaddr;
1600
    socklen_t len;
1601
    int fd;
1602

    
1603
    for(;;) {
1604
        len = sizeof(sockaddr);
1605
        fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
1606
        if (fd < 0 && errno != EINTR) {
1607
            perror("accept");
1608
            return;
1609
        } else if (fd >= 0) {
1610
#ifndef _WIN32
1611
            fcntl(fd, F_SETFD, FD_CLOEXEC);
1612
#endif
1613
            break;
1614
        }
1615
    }
1616

    
1617
    /* set short latency */
1618
    socket_set_nodelay(fd);
1619

    
1620
    s = g_malloc0(sizeof(GDBState));
1621
    s->c_cpu = first_cpu;
1622
    s->g_cpu = first_cpu;
1623
    s->fd = fd;
1624
    gdb_has_xml = 0;
1625

    
1626
    gdbserver_state = s;
1627

    
1628
    fcntl(fd, F_SETFL, O_NONBLOCK);
1629
}
1630

    
1631
static int gdbserver_open(int port)
1632
{
1633
    struct sockaddr_in sockaddr;
1634
    int fd, val, ret;
1635

    
1636
    fd = socket(PF_INET, SOCK_STREAM, 0);
1637
    if (fd < 0) {
1638
        perror("socket");
1639
        return -1;
1640
    }
1641
#ifndef _WIN32
1642
    fcntl(fd, F_SETFD, FD_CLOEXEC);
1643
#endif
1644

    
1645
    /* allow fast reuse */
1646
    val = 1;
1647
    qemu_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
1648

    
1649
    sockaddr.sin_family = AF_INET;
1650
    sockaddr.sin_port = htons(port);
1651
    sockaddr.sin_addr.s_addr = 0;
1652
    ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
1653
    if (ret < 0) {
1654
        perror("bind");
1655
        close(fd);
1656
        return -1;
1657
    }
1658
    ret = listen(fd, 0);
1659
    if (ret < 0) {
1660
        perror("listen");
1661
        close(fd);
1662
        return -1;
1663
    }
1664
    return fd;
1665
}
1666

    
1667
int gdbserver_start(int port)
1668
{
1669
    gdbserver_fd = gdbserver_open(port);
1670
    if (gdbserver_fd < 0)
1671
        return -1;
1672
    /* accept connections */
1673
    gdb_accept();
1674
    return 0;
1675
}
1676

    
1677
/* Disable gdb stub for child processes.  */
1678
void gdbserver_fork(CPUArchState *env)
1679
{
1680
    GDBState *s = gdbserver_state;
1681
    if (gdbserver_fd < 0 || s->fd < 0)
1682
      return;
1683
    close(s->fd);
1684
    s->fd = -1;
1685
    cpu_breakpoint_remove_all(env, BP_GDB);
1686
    cpu_watchpoint_remove_all(env, BP_GDB);
1687
}
1688
#else
1689
static int gdb_chr_can_receive(void *opaque)
1690
{
1691
  /* We can handle an arbitrarily large amount of data.
1692
   Pick the maximum packet size, which is as good as anything.  */
1693
  return MAX_PACKET_LENGTH;
1694
}
1695

    
1696
static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
1697
{
1698
    int i;
1699

    
1700
    for (i = 0; i < size; i++) {
1701
        gdb_read_byte(gdbserver_state, buf[i]);
1702
    }
1703
}
1704

    
1705
static void gdb_chr_event(void *opaque, int event)
1706
{
1707
    switch (event) {
1708
    case CHR_EVENT_OPENED:
1709
        vm_stop(RUN_STATE_PAUSED);
1710
        gdb_has_xml = 0;
1711
        break;
1712
    default:
1713
        break;
1714
    }
1715
}
1716

    
1717
static void gdb_monitor_output(GDBState *s, const char *msg, int len)
1718
{
1719
    char buf[MAX_PACKET_LENGTH];
1720

    
1721
    buf[0] = 'O';
1722
    if (len > (MAX_PACKET_LENGTH/2) - 1)
1723
        len = (MAX_PACKET_LENGTH/2) - 1;
1724
    memtohex(buf + 1, (uint8_t *)msg, len);
1725
    put_packet(s, buf);
1726
}
1727

    
1728
static int gdb_monitor_write(CharDriverState *chr, const uint8_t *buf, int len)
1729
{
1730
    const char *p = (const char *)buf;
1731
    int max_sz;
1732

    
1733
    max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
1734
    for (;;) {
1735
        if (len <= max_sz) {
1736
            gdb_monitor_output(gdbserver_state, p, len);
1737
            break;
1738
        }
1739
        gdb_monitor_output(gdbserver_state, p, max_sz);
1740
        p += max_sz;
1741
        len -= max_sz;
1742
    }
1743
    return len;
1744
}
1745

    
1746
#ifndef _WIN32
1747
static void gdb_sigterm_handler(int signal)
1748
{
1749
    if (runstate_is_running()) {
1750
        vm_stop(RUN_STATE_PAUSED);
1751
    }
1752
}
1753
#endif
1754

    
1755
int gdbserver_start(const char *device)
1756
{
1757
    GDBState *s;
1758
    char gdbstub_device_name[128];
1759
    CharDriverState *chr = NULL;
1760
    CharDriverState *mon_chr;
1761

    
1762
    if (!device)
1763
        return -1;
1764
    if (strcmp(device, "none") != 0) {
1765
        if (strstart(device, "tcp:", NULL)) {
1766
            /* enforce required TCP attributes */
1767
            snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
1768
                     "%s,nowait,nodelay,server", device);
1769
            device = gdbstub_device_name;
1770
        }
1771
#ifndef _WIN32
1772
        else if (strcmp(device, "stdio") == 0) {
1773
            struct sigaction act;
1774

    
1775
            memset(&act, 0, sizeof(act));
1776
            act.sa_handler = gdb_sigterm_handler;
1777
            sigaction(SIGINT, &act, NULL);
1778
        }
1779
#endif
1780
        chr = qemu_chr_new("gdb", device, NULL);
1781
        if (!chr)
1782
            return -1;
1783

    
1784
        qemu_chr_fe_claim_no_fail(chr);
1785
        qemu_chr_add_handlers(chr, gdb_chr_can_receive, gdb_chr_receive,
1786
                              gdb_chr_event, NULL);
1787
    }
1788

    
1789
    s = gdbserver_state;
1790
    if (!s) {
1791
        s = g_malloc0(sizeof(GDBState));
1792
        gdbserver_state = s;
1793

    
1794
        qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
1795

    
1796
        /* Initialize a monitor terminal for gdb */
1797
        mon_chr = g_malloc0(sizeof(*mon_chr));
1798
        mon_chr->chr_write = gdb_monitor_write;
1799
        monitor_init(mon_chr, 0);
1800
    } else {
1801
        if (s->chr)
1802
            qemu_chr_delete(s->chr);
1803
        mon_chr = s->mon_chr;
1804
        memset(s, 0, sizeof(GDBState));
1805
    }
1806
    s->c_cpu = first_cpu;
1807
    s->g_cpu = first_cpu;
1808
    s->chr = chr;
1809
    s->state = chr ? RS_IDLE : RS_INACTIVE;
1810
    s->mon_chr = mon_chr;
1811
    s->current_syscall_cb = NULL;
1812

    
1813
    return 0;
1814
}
1815
#endif