qemu/gdbstub.c
<<
>>
Prefs
   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 "qemu/osdep.h"
  20#include "qapi/error.h"
  21#include "qemu/cutils.h"
  22#include "cpu.h"
  23#ifdef CONFIG_USER_ONLY
  24#include "qemu.h"
  25#else
  26#include "monitor/monitor.h"
  27#include "sysemu/char.h"
  28#include "sysemu/sysemu.h"
  29#include "exec/gdbstub.h"
  30#endif
  31
  32#define MAX_PACKET_LENGTH 4096
  33
  34#include "qemu/sockets.h"
  35#include "sysemu/kvm.h"
  36#include "exec/semihost.h"
  37#include "exec/exec-all.h"
  38
  39#ifdef CONFIG_USER_ONLY
  40#define GDB_ATTACHED "0"
  41#else
  42#define GDB_ATTACHED "1"
  43#endif
  44
  45static 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
  56enum {
  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
  75static 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
 238enum {
 239    TARGET_SIGINT = 2,
 240    TARGET_SIGTRAP = 5
 241};
 242
 243static 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
 254static 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
 264static 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
 274typedef 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
 283enum RSState {
 284    RS_INACTIVE,
 285    RS_IDLE,
 286    RS_GETLINE,
 287    RS_CHKSUM1,
 288    RS_CHKSUM2,
 289};
 290typedef 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    CharBackend 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 */
 315static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
 316
 317static GDBState *gdbserver_state;
 318
 319bool gdb_has_xml;
 320
 321#ifdef CONFIG_USER_ONLY
 322/* XXX: This is not thread safe.  Do we care?  */
 323static int gdbserver_fd = -1;
 324
 325static int get_char(GDBState *s)
 326{
 327    uint8_t ch;
 328    int ret;
 329
 330    for(;;) {
 331        ret = qemu_recv(s->fd, &ch, 1, 0);
 332        if (ret < 0) {
 333            if (errno == ECONNRESET)
 334                s->fd = -1;
 335            if (errno != EINTR)
 336                return -1;
 337        } else if (ret == 0) {
 338            close(s->fd);
 339            s->fd = -1;
 340            return -1;
 341        } else {
 342            break;
 343        }
 344    }
 345    return ch;
 346}
 347#endif
 348
 349static enum {
 350    GDB_SYS_UNKNOWN,
 351    GDB_SYS_ENABLED,
 352    GDB_SYS_DISABLED,
 353} gdb_syscall_mode;
 354
 355/* Decide if either remote gdb syscalls or native file IO should be used. */
 356int use_gdb_syscalls(void)
 357{
 358    SemihostingTarget target = semihosting_get_target();
 359    if (target == SEMIHOSTING_TARGET_NATIVE) {
 360        /* -semihosting-config target=native */
 361        return false;
 362    } else if (target == SEMIHOSTING_TARGET_GDB) {
 363        /* -semihosting-config target=gdb */
 364        return true;
 365    }
 366
 367    /* -semihosting-config target=auto */
 368    /* On the first call check if gdb is connected and remember. */
 369    if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
 370        gdb_syscall_mode = (gdbserver_state ? GDB_SYS_ENABLED
 371                                            : GDB_SYS_DISABLED);
 372    }
 373    return gdb_syscall_mode == GDB_SYS_ENABLED;
 374}
 375
 376/* Resume execution.  */
 377static inline void gdb_continue(GDBState *s)
 378{
 379#ifdef CONFIG_USER_ONLY
 380    s->running_state = 1;
 381#else
 382    if (!runstate_needs_reset()) {
 383        vm_start();
 384    }
 385#endif
 386}
 387
 388static void put_buffer(GDBState *s, const uint8_t *buf, int len)
 389{
 390#ifdef CONFIG_USER_ONLY
 391    int ret;
 392
 393    while (len > 0) {
 394        ret = send(s->fd, buf, len, 0);
 395        if (ret < 0) {
 396            if (errno != EINTR)
 397                return;
 398        } else {
 399            buf += ret;
 400            len -= ret;
 401        }
 402    }
 403#else
 404    /* XXX this blocks entire thread. Rewrite to use
 405     * qemu_chr_fe_write and background I/O callbacks */
 406    qemu_chr_fe_write_all(&s->chr, buf, len);
 407#endif
 408}
 409
 410static inline int fromhex(int v)
 411{
 412    if (v >= '0' && v <= '9')
 413        return v - '0';
 414    else if (v >= 'A' && v <= 'F')
 415        return v - 'A' + 10;
 416    else if (v >= 'a' && v <= 'f')
 417        return v - 'a' + 10;
 418    else
 419        return 0;
 420}
 421
 422static inline int tohex(int v)
 423{
 424    if (v < 10)
 425        return v + '0';
 426    else
 427        return v - 10 + 'a';
 428}
 429
 430static void memtohex(char *buf, const uint8_t *mem, int len)
 431{
 432    int i, c;
 433    char *q;
 434    q = buf;
 435    for(i = 0; i < len; i++) {
 436        c = mem[i];
 437        *q++ = tohex(c >> 4);
 438        *q++ = tohex(c & 0xf);
 439    }
 440    *q = '\0';
 441}
 442
 443static void hextomem(uint8_t *mem, const char *buf, int len)
 444{
 445    int i;
 446
 447    for(i = 0; i < len; i++) {
 448        mem[i] = (fromhex(buf[0]) << 4) | fromhex(buf[1]);
 449        buf += 2;
 450    }
 451}
 452
 453/* return -1 if error, 0 if OK */
 454static int put_packet_binary(GDBState *s, const char *buf, int len)
 455{
 456    int csum, i;
 457    uint8_t *p;
 458
 459    for(;;) {
 460        p = s->last_packet;
 461        *(p++) = '$';
 462        memcpy(p, buf, len);
 463        p += len;
 464        csum = 0;
 465        for(i = 0; i < len; i++) {
 466            csum += buf[i];
 467        }
 468        *(p++) = '#';
 469        *(p++) = tohex((csum >> 4) & 0xf);
 470        *(p++) = tohex((csum) & 0xf);
 471
 472        s->last_packet_len = p - s->last_packet;
 473        put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
 474
 475#ifdef CONFIG_USER_ONLY
 476        i = get_char(s);
 477        if (i < 0)
 478            return -1;
 479        if (i == '+')
 480            break;
 481#else
 482        break;
 483#endif
 484    }
 485    return 0;
 486}
 487
 488/* return -1 if error, 0 if OK */
 489static int put_packet(GDBState *s, const char *buf)
 490{
 491#ifdef DEBUG_GDB
 492    printf("reply='%s'\n", buf);
 493#endif
 494
 495    return put_packet_binary(s, buf, strlen(buf));
 496}
 497
 498/* Encode data using the encoding for 'x' packets.  */
 499static int memtox(char *buf, const char *mem, int len)
 500{
 501    char *p = buf;
 502    char c;
 503
 504    while (len--) {
 505        c = *(mem++);
 506        switch (c) {
 507        case '#': case '$': case '*': case '}':
 508            *(p++) = '}';
 509            *(p++) = c ^ 0x20;
 510            break;
 511        default:
 512            *(p++) = c;
 513            break;
 514        }
 515    }
 516    return p - buf;
 517}
 518
 519static const char *get_feature_xml(const char *p, const char **newp,
 520                                   CPUClass *cc)
 521{
 522    size_t len;
 523    int i;
 524    const char *name;
 525    static char target_xml[1024];
 526
 527    len = 0;
 528    while (p[len] && p[len] != ':')
 529        len++;
 530    *newp = p + len;
 531
 532    name = NULL;
 533    if (strncmp(p, "target.xml", len) == 0) {
 534        /* Generate the XML description for this CPU.  */
 535        if (!target_xml[0]) {
 536            GDBRegisterState *r;
 537            CPUState *cpu = first_cpu;
 538
 539            pstrcat(target_xml, sizeof(target_xml),
 540                    "<?xml version=\"1.0\"?>"
 541                    "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
 542                    "<target>");
 543            if (cc->gdb_arch_name) {
 544                gchar *arch = cc->gdb_arch_name(cpu);
 545                pstrcat(target_xml, sizeof(target_xml), "<architecture>");
 546                pstrcat(target_xml, sizeof(target_xml), arch);
 547                pstrcat(target_xml, sizeof(target_xml), "</architecture>");
 548                g_free(arch);
 549            }
 550            pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
 551            pstrcat(target_xml, sizeof(target_xml), cc->gdb_core_xml_file);
 552            pstrcat(target_xml, sizeof(target_xml), "\"/>");
 553            for (r = cpu->gdb_regs; r; r = r->next) {
 554                pstrcat(target_xml, sizeof(target_xml), "<xi:include href=\"");
 555                pstrcat(target_xml, sizeof(target_xml), r->xml);
 556                pstrcat(target_xml, sizeof(target_xml), "\"/>");
 557            }
 558            pstrcat(target_xml, sizeof(target_xml), "</target>");
 559        }
 560        return target_xml;
 561    }
 562    for (i = 0; ; i++) {
 563        name = xml_builtin[i][0];
 564        if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
 565            break;
 566    }
 567    return name ? xml_builtin[i][1] : NULL;
 568}
 569
 570static int gdb_read_register(CPUState *cpu, uint8_t *mem_buf, int reg)
 571{
 572    CPUClass *cc = CPU_GET_CLASS(cpu);
 573    CPUArchState *env = cpu->env_ptr;
 574    GDBRegisterState *r;
 575
 576    if (reg < cc->gdb_num_core_regs) {
 577        return cc->gdb_read_register(cpu, mem_buf, reg);
 578    }
 579
 580    for (r = cpu->gdb_regs; r; r = r->next) {
 581        if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
 582            return r->get_reg(env, mem_buf, reg - r->base_reg);
 583        }
 584    }
 585    return 0;
 586}
 587
 588static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
 589{
 590    CPUClass *cc = CPU_GET_CLASS(cpu);
 591    CPUArchState *env = cpu->env_ptr;
 592    GDBRegisterState *r;
 593
 594    if (reg < cc->gdb_num_core_regs) {
 595        return cc->gdb_write_register(cpu, mem_buf, reg);
 596    }
 597
 598    for (r = cpu->gdb_regs; r; r = r->next) {
 599        if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
 600            return r->set_reg(env, mem_buf, reg - r->base_reg);
 601        }
 602    }
 603    return 0;
 604}
 605
 606/* Register a supplemental set of CPU registers.  If g_pos is nonzero it
 607   specifies the first register number and these registers are included in
 608   a standard "g" packet.  Direction is relative to gdb, i.e. get_reg is
 609   gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
 610 */
 611
 612void gdb_register_coprocessor(CPUState *cpu,
 613                              gdb_reg_cb get_reg, gdb_reg_cb set_reg,
 614                              int num_regs, const char *xml, int g_pos)
 615{
 616    GDBRegisterState *s;
 617    GDBRegisterState **p;
 618
 619    p = &cpu->gdb_regs;
 620    while (*p) {
 621        /* Check for duplicates.  */
 622        if (strcmp((*p)->xml, xml) == 0)
 623            return;
 624        p = &(*p)->next;
 625    }
 626
 627    s = g_new0(GDBRegisterState, 1);
 628    s->base_reg = cpu->gdb_num_regs;
 629    s->num_regs = num_regs;
 630    s->get_reg = get_reg;
 631    s->set_reg = set_reg;
 632    s->xml = xml;
 633
 634    /* Add to end of list.  */
 635    cpu->gdb_num_regs += num_regs;
 636    *p = s;
 637    if (g_pos) {
 638        if (g_pos != s->base_reg) {
 639            fprintf(stderr, "Error: Bad gdb register numbering for '%s'\n"
 640                    "Expected %d got %d\n", xml, g_pos, s->base_reg);
 641        } else {
 642            cpu->gdb_num_g_regs = cpu->gdb_num_regs;
 643        }
 644    }
 645}
 646
 647#ifndef CONFIG_USER_ONLY
 648/* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
 649static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
 650{
 651    static const int xlat[] = {
 652        [GDB_WATCHPOINT_WRITE]  = BP_GDB | BP_MEM_WRITE,
 653        [GDB_WATCHPOINT_READ]   = BP_GDB | BP_MEM_READ,
 654        [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
 655    };
 656
 657    CPUClass *cc = CPU_GET_CLASS(cpu);
 658    int cputype = xlat[gdbtype];
 659
 660    if (cc->gdb_stop_before_watchpoint) {
 661        cputype |= BP_STOP_BEFORE_ACCESS;
 662    }
 663    return cputype;
 664}
 665#endif
 666
 667static int gdb_breakpoint_insert(target_ulong addr, target_ulong len, int type)
 668{
 669    CPUState *cpu;
 670    int err = 0;
 671
 672    if (kvm_enabled()) {
 673        return kvm_insert_breakpoint(gdbserver_state->c_cpu, addr, len, type);
 674    }
 675
 676    switch (type) {
 677    case GDB_BREAKPOINT_SW:
 678    case GDB_BREAKPOINT_HW:
 679        CPU_FOREACH(cpu) {
 680            err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
 681            if (err) {
 682                break;
 683            }
 684        }
 685        return err;
 686#ifndef CONFIG_USER_ONLY
 687    case GDB_WATCHPOINT_WRITE:
 688    case GDB_WATCHPOINT_READ:
 689    case GDB_WATCHPOINT_ACCESS:
 690        CPU_FOREACH(cpu) {
 691            err = cpu_watchpoint_insert(cpu, addr, len,
 692                                        xlat_gdb_type(cpu, type), NULL);
 693            if (err) {
 694                break;
 695            }
 696        }
 697        return err;
 698#endif
 699    default:
 700        return -ENOSYS;
 701    }
 702}
 703
 704static int gdb_breakpoint_remove(target_ulong addr, target_ulong len, int type)
 705{
 706    CPUState *cpu;
 707    int err = 0;
 708
 709    if (kvm_enabled()) {
 710        return kvm_remove_breakpoint(gdbserver_state->c_cpu, addr, len, type);
 711    }
 712
 713    switch (type) {
 714    case GDB_BREAKPOINT_SW:
 715    case GDB_BREAKPOINT_HW:
 716        CPU_FOREACH(cpu) {
 717            err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
 718            if (err) {
 719                break;
 720            }
 721        }
 722        return err;
 723#ifndef CONFIG_USER_ONLY
 724    case GDB_WATCHPOINT_WRITE:
 725    case GDB_WATCHPOINT_READ:
 726    case GDB_WATCHPOINT_ACCESS:
 727        CPU_FOREACH(cpu) {
 728            err = cpu_watchpoint_remove(cpu, addr, len,
 729                                        xlat_gdb_type(cpu, type));
 730            if (err)
 731                break;
 732        }
 733        return err;
 734#endif
 735    default:
 736        return -ENOSYS;
 737    }
 738}
 739
 740static void gdb_breakpoint_remove_all(void)
 741{
 742    CPUState *cpu;
 743
 744    if (kvm_enabled()) {
 745        kvm_remove_all_breakpoints(gdbserver_state->c_cpu);
 746        return;
 747    }
 748
 749    CPU_FOREACH(cpu) {
 750        cpu_breakpoint_remove_all(cpu, BP_GDB);
 751#ifndef CONFIG_USER_ONLY
 752        cpu_watchpoint_remove_all(cpu, BP_GDB);
 753#endif
 754    }
 755}
 756
 757static void gdb_set_cpu_pc(GDBState *s, target_ulong pc)
 758{
 759    CPUState *cpu = s->c_cpu;
 760
 761    cpu_synchronize_state(cpu);
 762    cpu_set_pc(cpu, pc);
 763}
 764
 765static CPUState *find_cpu(uint32_t thread_id)
 766{
 767    CPUState *cpu;
 768
 769    CPU_FOREACH(cpu) {
 770        if (cpu_index(cpu) == thread_id) {
 771            return cpu;
 772        }
 773    }
 774
 775    return NULL;
 776}
 777
 778static int is_query_packet(const char *p, const char *query, char separator)
 779{
 780    unsigned int query_len = strlen(query);
 781
 782    return strncmp(p, query, query_len) == 0 &&
 783        (p[query_len] == '\0' || p[query_len] == separator);
 784}
 785
 786static int gdb_handle_packet(GDBState *s, const char *line_buf)
 787{
 788    CPUState *cpu;
 789    CPUClass *cc;
 790    const char *p;
 791    uint32_t thread;
 792    int ch, reg_size, type, res;
 793    char buf[MAX_PACKET_LENGTH];
 794    uint8_t mem_buf[MAX_PACKET_LENGTH];
 795    uint8_t *registers;
 796    target_ulong addr, len;
 797
 798#ifdef DEBUG_GDB
 799    printf("command='%s'\n", line_buf);
 800#endif
 801    p = line_buf;
 802    ch = *p++;
 803    switch(ch) {
 804    case '?':
 805        /* TODO: Make this return the correct value for user-mode.  */
 806        snprintf(buf, sizeof(buf), "T%02xthread:%02x;", GDB_SIGNAL_TRAP,
 807                 cpu_index(s->c_cpu));
 808        put_packet(s, buf);
 809        /* Remove all the breakpoints when this query is issued,
 810         * because gdb is doing and initial connect and the state
 811         * should be cleaned up.
 812         */
 813        gdb_breakpoint_remove_all();
 814        break;
 815    case 'c':
 816        if (*p != '\0') {
 817            addr = strtoull(p, (char **)&p, 16);
 818            gdb_set_cpu_pc(s, addr);
 819        }
 820        s->signal = 0;
 821        gdb_continue(s);
 822        return RS_IDLE;
 823    case 'C':
 824        s->signal = gdb_signal_to_target (strtoul(p, (char **)&p, 16));
 825        if (s->signal == -1)
 826            s->signal = 0;
 827        gdb_continue(s);
 828        return RS_IDLE;
 829    case 'v':
 830        if (strncmp(p, "Cont", 4) == 0) {
 831            int res_signal, res_thread;
 832
 833            p += 4;
 834            if (*p == '?') {
 835                put_packet(s, "vCont;c;C;s;S");
 836                break;
 837            }
 838            res = 0;
 839            res_signal = 0;
 840            res_thread = 0;
 841            while (*p) {
 842                int action, signal;
 843
 844                if (*p++ != ';') {
 845                    res = 0;
 846                    break;
 847                }
 848                action = *p++;
 849                signal = 0;
 850                if (action == 'C' || action == 'S') {
 851                    signal = gdb_signal_to_target(strtoul(p, (char **)&p, 16));
 852                    if (signal == -1) {
 853                        signal = 0;
 854                    }
 855                } else if (action != 'c' && action != 's') {
 856                    res = 0;
 857                    break;
 858                }
 859                thread = 0;
 860                if (*p == ':') {
 861                    thread = strtoull(p+1, (char **)&p, 16);
 862                }
 863                action = tolower(action);
 864                if (res == 0 || (res == 'c' && action == 's')) {
 865                    res = action;
 866                    res_signal = signal;
 867                    res_thread = thread;
 868                }
 869            }
 870            if (res) {
 871                if (res_thread != -1 && res_thread != 0) {
 872                    cpu = find_cpu(res_thread);
 873                    if (cpu == NULL) {
 874                        put_packet(s, "E22");
 875                        break;
 876                    }
 877                    s->c_cpu = cpu;
 878                }
 879                if (res == 's') {
 880                    cpu_single_step(s->c_cpu, sstep_flags);
 881                }
 882                s->signal = res_signal;
 883                gdb_continue(s);
 884                return RS_IDLE;
 885            }
 886            break;
 887        } else {
 888            goto unknown_command;
 889        }
 890    case 'k':
 891        /* Kill the target */
 892        fprintf(stderr, "\nQEMU: Terminated via GDBstub\n");
 893        exit(0);
 894    case 'D':
 895        /* Detach packet */
 896        gdb_breakpoint_remove_all();
 897        gdb_syscall_mode = GDB_SYS_DISABLED;
 898        gdb_continue(s);
 899        put_packet(s, "OK");
 900        break;
 901    case 's':
 902        if (*p != '\0') {
 903            addr = strtoull(p, (char **)&p, 16);
 904            gdb_set_cpu_pc(s, addr);
 905        }
 906        cpu_single_step(s->c_cpu, sstep_flags);
 907        gdb_continue(s);
 908        return RS_IDLE;
 909    case 'F':
 910        {
 911            target_ulong ret;
 912            target_ulong err;
 913
 914            ret = strtoull(p, (char **)&p, 16);
 915            if (*p == ',') {
 916                p++;
 917                err = strtoull(p, (char **)&p, 16);
 918            } else {
 919                err = 0;
 920            }
 921            if (*p == ',')
 922                p++;
 923            type = *p;
 924            if (s->current_syscall_cb) {
 925                s->current_syscall_cb(s->c_cpu, ret, err);
 926                s->current_syscall_cb = NULL;
 927            }
 928            if (type == 'C') {
 929                put_packet(s, "T02");
 930            } else {
 931                gdb_continue(s);
 932            }
 933        }
 934        break;
 935    case 'g':
 936        cpu_synchronize_state(s->g_cpu);
 937        len = 0;
 938        for (addr = 0; addr < s->g_cpu->gdb_num_g_regs; addr++) {
 939            reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);
 940            len += reg_size;
 941        }
 942        memtohex(buf, mem_buf, len);
 943        put_packet(s, buf);
 944        break;
 945    case 'G':
 946        cpu_synchronize_state(s->g_cpu);
 947        registers = mem_buf;
 948        len = strlen(p) / 2;
 949        hextomem((uint8_t *)registers, p, len);
 950        for (addr = 0; addr < s->g_cpu->gdb_num_g_regs && len > 0; addr++) {
 951            reg_size = gdb_write_register(s->g_cpu, registers, addr);
 952            len -= reg_size;
 953            registers += reg_size;
 954        }
 955        put_packet(s, "OK");
 956        break;
 957    case 'm':
 958        addr = strtoull(p, (char **)&p, 16);
 959        if (*p == ',')
 960            p++;
 961        len = strtoull(p, NULL, 16);
 962
 963        /* memtohex() doubles the required space */
 964        if (len > MAX_PACKET_LENGTH / 2) {
 965            put_packet (s, "E22");
 966            break;
 967        }
 968
 969        if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len, false) != 0) {
 970            put_packet (s, "E14");
 971        } else {
 972            memtohex(buf, mem_buf, len);
 973            put_packet(s, buf);
 974        }
 975        break;
 976    case 'M':
 977        addr = strtoull(p, (char **)&p, 16);
 978        if (*p == ',')
 979            p++;
 980        len = strtoull(p, (char **)&p, 16);
 981        if (*p == ':')
 982            p++;
 983
 984        /* hextomem() reads 2*len bytes */
 985        if (len > strlen(p) / 2) {
 986            put_packet (s, "E22");
 987            break;
 988        }
 989        hextomem(mem_buf, p, len);
 990        if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len,
 991                                   true) != 0) {
 992            put_packet(s, "E14");
 993        } else {
 994            put_packet(s, "OK");
 995        }
 996        break;
 997    case 'p':
 998        /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.
 999           This works, but can be very slow.  Anything new enough to
1000           understand XML also knows how to use this properly.  */
1001        if (!gdb_has_xml)
1002            goto unknown_command;
1003        addr = strtoull(p, (char **)&p, 16);
1004        reg_size = gdb_read_register(s->g_cpu, mem_buf, addr);
1005        if (reg_size) {
1006            memtohex(buf, mem_buf, reg_size);
1007            put_packet(s, buf);
1008        } else {
1009            put_packet(s, "E14");
1010        }
1011        break;
1012    case 'P':
1013        if (!gdb_has_xml)
1014            goto unknown_command;
1015        addr = strtoull(p, (char **)&p, 16);
1016        if (*p == '=')
1017            p++;
1018        reg_size = strlen(p) / 2;
1019        hextomem(mem_buf, p, reg_size);
1020        gdb_write_register(s->g_cpu, mem_buf, addr);
1021        put_packet(s, "OK");
1022        break;
1023    case 'Z':
1024    case 'z':
1025        type = strtoul(p, (char **)&p, 16);
1026        if (*p == ',')
1027            p++;
1028        addr = strtoull(p, (char **)&p, 16);
1029        if (*p == ',')
1030            p++;
1031        len = strtoull(p, (char **)&p, 16);
1032        if (ch == 'Z')
1033            res = gdb_breakpoint_insert(addr, len, type);
1034        else
1035            res = gdb_breakpoint_remove(addr, len, type);
1036        if (res >= 0)
1037             put_packet(s, "OK");
1038        else if (res == -ENOSYS)
1039            put_packet(s, "");
1040        else
1041            put_packet(s, "E22");
1042        break;
1043    case 'H':
1044        type = *p++;
1045        thread = strtoull(p, (char **)&p, 16);
1046        if (thread == -1 || thread == 0) {
1047            put_packet(s, "OK");
1048            break;
1049        }
1050        cpu = find_cpu(thread);
1051        if (cpu == NULL) {
1052            put_packet(s, "E22");
1053            break;
1054        }
1055        switch (type) {
1056        case 'c':
1057            s->c_cpu = cpu;
1058            put_packet(s, "OK");
1059            break;
1060        case 'g':
1061            s->g_cpu = cpu;
1062            put_packet(s, "OK");
1063            break;
1064        default:
1065             put_packet(s, "E22");
1066             break;
1067        }
1068        break;
1069    case 'T':
1070        thread = strtoull(p, (char **)&p, 16);
1071        cpu = find_cpu(thread);
1072
1073        if (cpu != NULL) {
1074            put_packet(s, "OK");
1075        } else {
1076            put_packet(s, "E22");
1077        }
1078        break;
1079    case 'q':
1080    case 'Q':
1081        /* parse any 'q' packets here */
1082        if (!strcmp(p,"qemu.sstepbits")) {
1083            /* Query Breakpoint bit definitions */
1084            snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1085                     SSTEP_ENABLE,
1086                     SSTEP_NOIRQ,
1087                     SSTEP_NOTIMER);
1088            put_packet(s, buf);
1089            break;
1090        } else if (is_query_packet(p, "qemu.sstep", '=')) {
1091            /* Display or change the sstep_flags */
1092            p += 10;
1093            if (*p != '=') {
1094                /* Display current setting */
1095                snprintf(buf, sizeof(buf), "0x%x", sstep_flags);
1096                put_packet(s, buf);
1097                break;
1098            }
1099            p++;
1100            type = strtoul(p, (char **)&p, 16);
1101            sstep_flags = type;
1102            put_packet(s, "OK");
1103            break;
1104        } else if (strcmp(p,"C") == 0) {
1105            /* "Current thread" remains vague in the spec, so always return
1106             *  the first CPU (gdb returns the first thread). */
1107            put_packet(s, "QC1");
1108            break;
1109        } else if (strcmp(p,"fThreadInfo") == 0) {
1110            s->query_cpu = first_cpu;
1111            goto report_cpuinfo;
1112        } else if (strcmp(p,"sThreadInfo") == 0) {
1113        report_cpuinfo:
1114            if (s->query_cpu) {
1115                snprintf(buf, sizeof(buf), "m%x", cpu_index(s->query_cpu));
1116                put_packet(s, buf);
1117                s->query_cpu = CPU_NEXT(s->query_cpu);
1118            } else
1119                put_packet(s, "l");
1120            break;
1121        } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {
1122            thread = strtoull(p+16, (char **)&p, 16);
1123            cpu = find_cpu(thread);
1124            if (cpu != NULL) {
1125                cpu_synchronize_state(cpu);
1126                /* memtohex() doubles the required space */
1127                len = snprintf((char *)mem_buf, sizeof(buf) / 2,
1128                               "CPU#%d [%s]", cpu->cpu_index,
1129                               cpu->halted ? "halted " : "running");
1130                memtohex(buf, mem_buf, len);
1131                put_packet(s, buf);
1132            }
1133            break;
1134        }
1135#ifdef CONFIG_USER_ONLY
1136        else if (strcmp(p, "Offsets") == 0) {
1137            TaskState *ts = s->c_cpu->opaque;
1138
1139            snprintf(buf, sizeof(buf),
1140                     "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx
1141                     ";Bss=" TARGET_ABI_FMT_lx,
1142                     ts->info->code_offset,
1143                     ts->info->data_offset,
1144                     ts->info->data_offset);
1145            put_packet(s, buf);
1146            break;
1147        }
1148#else /* !CONFIG_USER_ONLY */
1149        else if (strncmp(p, "Rcmd,", 5) == 0) {
1150            int len = strlen(p + 5);
1151
1152            if ((len % 2) != 0) {
1153                put_packet(s, "E01");
1154                break;
1155            }
1156            len = len / 2;
1157            hextomem(mem_buf, p + 5, len);
1158            mem_buf[len++] = 0;
1159            qemu_chr_be_write(s->mon_chr, mem_buf, len);
1160            put_packet(s, "OK");
1161            break;
1162        }
1163#endif /* !CONFIG_USER_ONLY */
1164        if (is_query_packet(p, "Supported", ':')) {
1165            snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);
1166            cc = CPU_GET_CLASS(first_cpu);
1167            if (cc->gdb_core_xml_file != NULL) {
1168                pstrcat(buf, sizeof(buf), ";qXfer:features:read+");
1169            }
1170            put_packet(s, buf);
1171            break;
1172        }
1173        if (strncmp(p, "Xfer:features:read:", 19) == 0) {
1174            const char *xml;
1175            target_ulong total_len;
1176
1177            cc = CPU_GET_CLASS(first_cpu);
1178            if (cc->gdb_core_xml_file == NULL) {
1179                goto unknown_command;
1180            }
1181
1182            gdb_has_xml = true;
1183            p += 19;
1184            xml = get_feature_xml(p, &p, cc);
1185            if (!xml) {
1186                snprintf(buf, sizeof(buf), "E00");
1187                put_packet(s, buf);
1188                break;
1189            }
1190
1191            if (*p == ':')
1192                p++;
1193            addr = strtoul(p, (char **)&p, 16);
1194            if (*p == ',')
1195                p++;
1196            len = strtoul(p, (char **)&p, 16);
1197
1198            total_len = strlen(xml);
1199            if (addr > total_len) {
1200                snprintf(buf, sizeof(buf), "E00");
1201                put_packet(s, buf);
1202                break;
1203            }
1204            if (len > (MAX_PACKET_LENGTH - 5) / 2)
1205                len = (MAX_PACKET_LENGTH - 5) / 2;
1206            if (len < total_len - addr) {
1207                buf[0] = 'm';
1208                len = memtox(buf + 1, xml + addr, len);
1209            } else {
1210                buf[0] = 'l';
1211                len = memtox(buf + 1, xml + addr, total_len - addr);
1212            }
1213            put_packet_binary(s, buf, len + 1);
1214            break;
1215        }
1216        if (is_query_packet(p, "Attached", ':')) {
1217            put_packet(s, GDB_ATTACHED);
1218            break;
1219        }
1220        /* Unrecognised 'q' command.  */
1221        goto unknown_command;
1222
1223    default:
1224    unknown_command:
1225        /* put empty packet */
1226        buf[0] = '\0';
1227        put_packet(s, buf);
1228        break;
1229    }
1230    return RS_IDLE;
1231}
1232
1233void gdb_set_stop_cpu(CPUState *cpu)
1234{
1235    gdbserver_state->c_cpu = cpu;
1236    gdbserver_state->g_cpu = cpu;
1237}
1238
1239#ifndef CONFIG_USER_ONLY
1240static void gdb_vm_state_change(void *opaque, int running, RunState state)
1241{
1242    GDBState *s = gdbserver_state;
1243    CPUState *cpu = s->c_cpu;
1244    char buf[256];
1245    const char *type;
1246    int ret;
1247
1248    if (running || s->state == RS_INACTIVE) {
1249        return;
1250    }
1251    /* Is there a GDB syscall waiting to be sent?  */
1252    if (s->current_syscall_cb) {
1253        put_packet(s, s->syscall_buf);
1254        return;
1255    }
1256    switch (state) {
1257    case RUN_STATE_DEBUG:
1258        if (cpu->watchpoint_hit) {
1259            switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
1260            case BP_MEM_READ:
1261                type = "r";
1262                break;
1263            case BP_MEM_ACCESS:
1264                type = "a";
1265                break;
1266            default:
1267                type = "";
1268                break;
1269            }
1270            snprintf(buf, sizeof(buf),
1271                     "T%02xthread:%02x;%swatch:" TARGET_FMT_lx ";",
1272                     GDB_SIGNAL_TRAP, cpu_index(cpu), type,
1273                     (target_ulong)cpu->watchpoint_hit->vaddr);
1274            cpu->watchpoint_hit = NULL;
1275            goto send_packet;
1276        }
1277        tb_flush(cpu);
1278        ret = GDB_SIGNAL_TRAP;
1279        break;
1280    case RUN_STATE_PAUSED:
1281        ret = GDB_SIGNAL_INT;
1282        break;
1283    case RUN_STATE_SHUTDOWN:
1284        ret = GDB_SIGNAL_QUIT;
1285        break;
1286    case RUN_STATE_IO_ERROR:
1287        ret = GDB_SIGNAL_IO;
1288        break;
1289    case RUN_STATE_WATCHDOG:
1290        ret = GDB_SIGNAL_ALRM;
1291        break;
1292    case RUN_STATE_INTERNAL_ERROR:
1293        ret = GDB_SIGNAL_ABRT;
1294        break;
1295    case RUN_STATE_SAVE_VM:
1296    case RUN_STATE_RESTORE_VM:
1297        return;
1298    case RUN_STATE_FINISH_MIGRATE:
1299        ret = GDB_SIGNAL_XCPU;
1300        break;
1301    default:
1302        ret = GDB_SIGNAL_UNKNOWN;
1303        break;
1304    }
1305    gdb_set_stop_cpu(cpu);
1306    snprintf(buf, sizeof(buf), "T%02xthread:%02x;", ret, cpu_index(cpu));
1307
1308send_packet:
1309    put_packet(s, buf);
1310
1311    /* disable single step if it was enabled */
1312    cpu_single_step(cpu, 0);
1313}
1314#endif
1315
1316/* Send a gdb syscall request.
1317   This accepts limited printf-style format specifiers, specifically:
1318    %x  - target_ulong argument printed in hex.
1319    %lx - 64-bit argument printed in hex.
1320    %s  - string pointer (target_ulong) and length (int) pair.  */
1321void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
1322{
1323    char *p;
1324    char *p_end;
1325    target_ulong addr;
1326    uint64_t i64;
1327    GDBState *s;
1328
1329    s = gdbserver_state;
1330    if (!s)
1331        return;
1332    s->current_syscall_cb = cb;
1333#ifndef CONFIG_USER_ONLY
1334    vm_stop(RUN_STATE_DEBUG);
1335#endif
1336    p = s->syscall_buf;
1337    p_end = &s->syscall_buf[sizeof(s->syscall_buf)];
1338    *(p++) = 'F';
1339    while (*fmt) {
1340        if (*fmt == '%') {
1341            fmt++;
1342            switch (*fmt++) {
1343            case 'x':
1344                addr = va_arg(va, target_ulong);
1345                p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
1346                break;
1347            case 'l':
1348                if (*(fmt++) != 'x')
1349                    goto bad_format;
1350                i64 = va_arg(va, uint64_t);
1351                p += snprintf(p, p_end - p, "%" PRIx64, i64);
1352                break;
1353            case 's':
1354                addr = va_arg(va, target_ulong);
1355                p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
1356                              addr, va_arg(va, int));
1357                break;
1358            default:
1359            bad_format:
1360                fprintf(stderr, "gdbstub: Bad syscall format string '%s'\n",
1361                        fmt - 1);
1362                break;
1363            }
1364        } else {
1365            *(p++) = *(fmt++);
1366        }
1367    }
1368    *p = 0;
1369#ifdef CONFIG_USER_ONLY
1370    put_packet(s, s->syscall_buf);
1371    gdb_handlesig(s->c_cpu, 0);
1372#else
1373    /* In this case wait to send the syscall packet until notification that
1374       the CPU has stopped.  This must be done because if the packet is sent
1375       now the reply from the syscall request could be received while the CPU
1376       is still in the running state, which can cause packets to be dropped
1377       and state transition 'T' packets to be sent while the syscall is still
1378       being processed.  */
1379    qemu_cpu_kick(s->c_cpu);
1380#endif
1381}
1382
1383void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
1384{
1385    va_list va;
1386
1387    va_start(va, fmt);
1388    gdb_do_syscallv(cb, fmt, va);
1389    va_end(va);
1390}
1391
1392static void gdb_read_byte(GDBState *s, int ch)
1393{
1394    int i, csum;
1395    uint8_t reply;
1396
1397#ifndef CONFIG_USER_ONLY
1398    if (s->last_packet_len) {
1399        /* Waiting for a response to the last packet.  If we see the start
1400           of a new command then abandon the previous response.  */
1401        if (ch == '-') {
1402#ifdef DEBUG_GDB
1403            printf("Got NACK, retransmitting\n");
1404#endif
1405            put_buffer(s, (uint8_t *)s->last_packet, s->last_packet_len);
1406        }
1407#ifdef DEBUG_GDB
1408        else if (ch == '+')
1409            printf("Got ACK\n");
1410        else
1411            printf("Got '%c' when expecting ACK/NACK\n", ch);
1412#endif
1413        if (ch == '+' || ch == '$')
1414            s->last_packet_len = 0;
1415        if (ch != '$')
1416            return;
1417    }
1418    if (runstate_is_running()) {
1419        /* when the CPU is running, we cannot do anything except stop
1420           it when receiving a char */
1421        vm_stop(RUN_STATE_PAUSED);
1422    } else
1423#endif
1424    {
1425        switch(s->state) {
1426        case RS_IDLE:
1427            if (ch == '$') {
1428                s->line_buf_index = 0;
1429                s->state = RS_GETLINE;
1430            }
1431            break;
1432        case RS_GETLINE:
1433            if (ch == '#') {
1434            s->state = RS_CHKSUM1;
1435            } else if (s->line_buf_index >= sizeof(s->line_buf) - 1) {
1436                s->state = RS_IDLE;
1437            } else {
1438            s->line_buf[s->line_buf_index++] = ch;
1439            }
1440            break;
1441        case RS_CHKSUM1:
1442            s->line_buf[s->line_buf_index] = '\0';
1443            s->line_csum = fromhex(ch) << 4;
1444            s->state = RS_CHKSUM2;
1445            break;
1446        case RS_CHKSUM2:
1447            s->line_csum |= fromhex(ch);
1448            csum = 0;
1449            for(i = 0; i < s->line_buf_index; i++) {
1450                csum += s->line_buf[i];
1451            }
1452            if (s->line_csum != (csum & 0xff)) {
1453                reply = '-';
1454                put_buffer(s, &reply, 1);
1455                s->state = RS_IDLE;
1456            } else {
1457                reply = '+';
1458                put_buffer(s, &reply, 1);
1459                s->state = gdb_handle_packet(s, s->line_buf);
1460            }
1461            break;
1462        default:
1463            abort();
1464        }
1465    }
1466}
1467
1468/* Tell the remote gdb that the process has exited.  */
1469void gdb_exit(CPUArchState *env, int code)
1470{
1471  GDBState *s;
1472  char buf[4];
1473#ifndef CONFIG_USER_ONLY
1474  CharDriverState *chr;
1475#endif
1476
1477  s = gdbserver_state;
1478  if (!s) {
1479      return;
1480  }
1481#ifdef CONFIG_USER_ONLY
1482  if (gdbserver_fd < 0 || s->fd < 0) {
1483      return;
1484  }
1485#else
1486  chr = qemu_chr_fe_get_driver(&s->chr);
1487  if (!chr) {
1488      return;
1489  }
1490#endif
1491
1492  snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
1493  put_packet(s, buf);
1494
1495#ifndef CONFIG_USER_ONLY
1496  qemu_chr_fe_deinit(&s->chr);
1497  qemu_chr_delete(chr);
1498#endif
1499}
1500
1501#ifdef CONFIG_USER_ONLY
1502int
1503gdb_handlesig(CPUState *cpu, int sig)
1504{
1505    GDBState *s;
1506    char buf[256];
1507    int n;
1508
1509    s = gdbserver_state;
1510    if (gdbserver_fd < 0 || s->fd < 0) {
1511        return sig;
1512    }
1513
1514    /* disable single step if it was enabled */
1515    cpu_single_step(cpu, 0);
1516    tb_flush(cpu);
1517
1518    if (sig != 0) {
1519        snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
1520        put_packet(s, buf);
1521    }
1522    /* put_packet() might have detected that the peer terminated the
1523       connection.  */
1524    if (s->fd < 0) {
1525        return sig;
1526    }
1527
1528    sig = 0;
1529    s->state = RS_IDLE;
1530    s->running_state = 0;
1531    while (s->running_state == 0) {
1532        n = read(s->fd, buf, 256);
1533        if (n > 0) {
1534            int i;
1535
1536            for (i = 0; i < n; i++) {
1537                gdb_read_byte(s, buf[i]);
1538            }
1539        } else {
1540            /* XXX: Connection closed.  Should probably wait for another
1541               connection before continuing.  */
1542            if (n == 0) {
1543                close(s->fd);
1544            }
1545            s->fd = -1;
1546            return sig;
1547        }
1548    }
1549    sig = s->signal;
1550    s->signal = 0;
1551    return sig;
1552}
1553
1554/* Tell the remote gdb that the process has exited due to SIG.  */
1555void gdb_signalled(CPUArchState *env, int sig)
1556{
1557    GDBState *s;
1558    char buf[4];
1559
1560    s = gdbserver_state;
1561    if (gdbserver_fd < 0 || s->fd < 0) {
1562        return;
1563    }
1564
1565    snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
1566    put_packet(s, buf);
1567}
1568
1569static void gdb_accept(void)
1570{
1571    GDBState *s;
1572    struct sockaddr_in sockaddr;
1573    socklen_t len;
1574    int fd;
1575
1576    for(;;) {
1577        len = sizeof(sockaddr);
1578        fd = accept(gdbserver_fd, (struct sockaddr *)&sockaddr, &len);
1579        if (fd < 0 && errno != EINTR) {
1580            perror("accept");
1581            return;
1582        } else if (fd >= 0) {
1583#ifndef _WIN32
1584            fcntl(fd, F_SETFD, FD_CLOEXEC);
1585#endif
1586            break;
1587        }
1588    }
1589
1590    /* set short latency */
1591    socket_set_nodelay(fd);
1592
1593    s = g_malloc0(sizeof(GDBState));
1594    s->c_cpu = first_cpu;
1595    s->g_cpu = first_cpu;
1596    s->fd = fd;
1597    gdb_has_xml = false;
1598
1599    gdbserver_state = s;
1600}
1601
1602static int gdbserver_open(int port)
1603{
1604    struct sockaddr_in sockaddr;
1605    int fd, ret;
1606
1607    fd = socket(PF_INET, SOCK_STREAM, 0);
1608    if (fd < 0) {
1609        perror("socket");
1610        return -1;
1611    }
1612#ifndef _WIN32
1613    fcntl(fd, F_SETFD, FD_CLOEXEC);
1614#endif
1615
1616    socket_set_fast_reuse(fd);
1617
1618    sockaddr.sin_family = AF_INET;
1619    sockaddr.sin_port = htons(port);
1620    sockaddr.sin_addr.s_addr = 0;
1621    ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
1622    if (ret < 0) {
1623        perror("bind");
1624        close(fd);
1625        return -1;
1626    }
1627    ret = listen(fd, 1);
1628    if (ret < 0) {
1629        perror("listen");
1630        close(fd);
1631        return -1;
1632    }
1633    return fd;
1634}
1635
1636int gdbserver_start(int port)
1637{
1638    gdbserver_fd = gdbserver_open(port);
1639    if (gdbserver_fd < 0)
1640        return -1;
1641    /* accept connections */
1642    gdb_accept();
1643    return 0;
1644}
1645
1646/* Disable gdb stub for child processes.  */
1647void gdbserver_fork(CPUState *cpu)
1648{
1649    GDBState *s = gdbserver_state;
1650
1651    if (gdbserver_fd < 0 || s->fd < 0) {
1652        return;
1653    }
1654    close(s->fd);
1655    s->fd = -1;
1656    cpu_breakpoint_remove_all(cpu, BP_GDB);
1657    cpu_watchpoint_remove_all(cpu, BP_GDB);
1658}
1659#else
1660static int gdb_chr_can_receive(void *opaque)
1661{
1662  /* We can handle an arbitrarily large amount of data.
1663   Pick the maximum packet size, which is as good as anything.  */
1664  return MAX_PACKET_LENGTH;
1665}
1666
1667static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
1668{
1669    int i;
1670
1671    for (i = 0; i < size; i++) {
1672        gdb_read_byte(gdbserver_state, buf[i]);
1673    }
1674}
1675
1676static void gdb_chr_event(void *opaque, int event)
1677{
1678    switch (event) {
1679    case CHR_EVENT_OPENED:
1680        vm_stop(RUN_STATE_PAUSED);
1681        gdb_has_xml = false;
1682        break;
1683    default:
1684        break;
1685    }
1686}
1687
1688static void gdb_monitor_output(GDBState *s, const char *msg, int len)
1689{
1690    char buf[MAX_PACKET_LENGTH];
1691
1692    buf[0] = 'O';
1693    if (len > (MAX_PACKET_LENGTH/2) - 1)
1694        len = (MAX_PACKET_LENGTH/2) - 1;
1695    memtohex(buf + 1, (uint8_t *)msg, len);
1696    put_packet(s, buf);
1697}
1698
1699static int gdb_monitor_write(CharDriverState *chr, const uint8_t *buf, int len)
1700{
1701    const char *p = (const char *)buf;
1702    int max_sz;
1703
1704    max_sz = (sizeof(gdbserver_state->last_packet) - 2) / 2;
1705    for (;;) {
1706        if (len <= max_sz) {
1707            gdb_monitor_output(gdbserver_state, p, len);
1708            break;
1709        }
1710        gdb_monitor_output(gdbserver_state, p, max_sz);
1711        p += max_sz;
1712        len -= max_sz;
1713    }
1714    return len;
1715}
1716
1717#ifndef _WIN32
1718static void gdb_sigterm_handler(int signal)
1719{
1720    if (runstate_is_running()) {
1721        vm_stop(RUN_STATE_PAUSED);
1722    }
1723}
1724#endif
1725
1726int gdbserver_start(const char *device)
1727{
1728    GDBState *s;
1729    char gdbstub_device_name[128];
1730    CharDriverState *chr = NULL;
1731    CharDriverState *mon_chr;
1732    ChardevCommon common = { 0 };
1733
1734    if (!device)
1735        return -1;
1736    if (strcmp(device, "none") != 0) {
1737        if (strstart(device, "tcp:", NULL)) {
1738            /* enforce required TCP attributes */
1739            snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
1740                     "%s,nowait,nodelay,server", device);
1741            device = gdbstub_device_name;
1742        }
1743#ifndef _WIN32
1744        else if (strcmp(device, "stdio") == 0) {
1745            struct sigaction act;
1746
1747            memset(&act, 0, sizeof(act));
1748            act.sa_handler = gdb_sigterm_handler;
1749            sigaction(SIGINT, &act, NULL);
1750        }
1751#endif
1752        chr = qemu_chr_new_noreplay("gdb", device);
1753        if (!chr)
1754            return -1;
1755    }
1756
1757    s = gdbserver_state;
1758    if (!s) {
1759        s = g_malloc0(sizeof(GDBState));
1760        gdbserver_state = s;
1761
1762        qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
1763
1764        /* Initialize a monitor terminal for gdb */
1765        mon_chr = qemu_chr_alloc(&common, &error_abort);
1766        mon_chr->chr_write = gdb_monitor_write;
1767        monitor_init(mon_chr, 0);
1768    } else {
1769        if (qemu_chr_fe_get_driver(&s->chr)) {
1770            qemu_chr_delete(qemu_chr_fe_get_driver(&s->chr));
1771        }
1772        mon_chr = s->mon_chr;
1773        memset(s, 0, sizeof(GDBState));
1774        s->mon_chr = mon_chr;
1775    }
1776    s->c_cpu = first_cpu;
1777    s->g_cpu = first_cpu;
1778    if (chr) {
1779        qemu_chr_fe_init(&s->chr, chr, &error_abort);
1780        qemu_chr_fe_set_handlers(&s->chr, gdb_chr_can_receive, gdb_chr_receive,
1781                                 gdb_chr_event, NULL, NULL, true);
1782    }
1783    s->state = chr ? RS_IDLE : RS_INACTIVE;
1784    s->mon_chr = mon_chr;
1785    s->current_syscall_cb = NULL;
1786
1787    return 0;
1788}
1789#endif
1790