qemu/gdbstub.c
<<
>>
Prefs
   1/*
   2 * gdb server stub
   3 *
   4 * This implements a subset of the remote protocol as described in:
   5 *
   6 *   https://sourceware.org/gdb/onlinedocs/gdb/Remote-Protocol.html
   7 *
   8 * Copyright (c) 2003-2005 Fabrice Bellard
   9 *
  10 * This library is free software; you can redistribute it and/or
  11 * modify it under the terms of the GNU Lesser General Public
  12 * License as published by the Free Software Foundation; either
  13 * version 2 of the License, or (at your option) any later version.
  14 *
  15 * This library is distributed in the hope that it will be useful,
  16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  18 * Lesser General Public License for more details.
  19 *
  20 * You should have received a copy of the GNU Lesser General Public
  21 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  22 *
  23 * SPDX-License-Identifier: LGPL-2.0+
  24 */
  25
  26#include "qemu/osdep.h"
  27#include "qemu-common.h"
  28#include "qapi/error.h"
  29#include "qemu/error-report.h"
  30#include "qemu/ctype.h"
  31#include "qemu/cutils.h"
  32#include "qemu/module.h"
  33#include "trace-root.h"
  34#ifdef CONFIG_USER_ONLY
  35#include "qemu.h"
  36#else
  37#include "monitor/monitor.h"
  38#include "chardev/char.h"
  39#include "chardev/char-fe.h"
  40#include "sysemu/sysemu.h"
  41#include "exec/gdbstub.h"
  42#include "hw/cpu/cluster.h"
  43#include "hw/boards.h"
  44#endif
  45
  46#define MAX_PACKET_LENGTH 4096
  47
  48#include "qemu/sockets.h"
  49#include "sysemu/hw_accel.h"
  50#include "sysemu/kvm.h"
  51#include "sysemu/runstate.h"
  52#include "hw/semihosting/semihost.h"
  53#include "exec/exec-all.h"
  54
  55#ifdef CONFIG_USER_ONLY
  56#define GDB_ATTACHED "0"
  57#else
  58#define GDB_ATTACHED "1"
  59#endif
  60
  61#ifndef CONFIG_USER_ONLY
  62static int phy_memory_mode;
  63#endif
  64
  65static inline int target_memory_rw_debug(CPUState *cpu, target_ulong addr,
  66                                         uint8_t *buf, int len, bool is_write)
  67{
  68    CPUClass *cc;
  69
  70#ifndef CONFIG_USER_ONLY
  71    if (phy_memory_mode) {
  72        if (is_write) {
  73            cpu_physical_memory_write(addr, buf, len);
  74        } else {
  75            cpu_physical_memory_read(addr, buf, len);
  76        }
  77        return 0;
  78    }
  79#endif
  80
  81    cc = CPU_GET_CLASS(cpu);
  82    if (cc->memory_rw_debug) {
  83        return cc->memory_rw_debug(cpu, addr, buf, len, is_write);
  84    }
  85    return cpu_memory_rw_debug(cpu, addr, buf, len, is_write);
  86}
  87
  88/* Return the GDB index for a given vCPU state.
  89 *
  90 * For user mode this is simply the thread id. In system mode GDB
  91 * numbers CPUs from 1 as 0 is reserved as an "any cpu" index.
  92 */
  93static inline int cpu_gdb_index(CPUState *cpu)
  94{
  95#if defined(CONFIG_USER_ONLY)
  96    TaskState *ts = (TaskState *) cpu->opaque;
  97    return ts->ts_tid;
  98#else
  99    return cpu->cpu_index + 1;
 100#endif
 101}
 102
 103enum {
 104    GDB_SIGNAL_0 = 0,
 105    GDB_SIGNAL_INT = 2,
 106    GDB_SIGNAL_QUIT = 3,
 107    GDB_SIGNAL_TRAP = 5,
 108    GDB_SIGNAL_ABRT = 6,
 109    GDB_SIGNAL_ALRM = 14,
 110    GDB_SIGNAL_IO = 23,
 111    GDB_SIGNAL_XCPU = 24,
 112    GDB_SIGNAL_UNKNOWN = 143
 113};
 114
 115#ifdef CONFIG_USER_ONLY
 116
 117/* Map target signal numbers to GDB protocol signal numbers and vice
 118 * versa.  For user emulation's currently supported systems, we can
 119 * assume most signals are defined.
 120 */
 121
 122static int gdb_signal_table[] = {
 123    0,
 124    TARGET_SIGHUP,
 125    TARGET_SIGINT,
 126    TARGET_SIGQUIT,
 127    TARGET_SIGILL,
 128    TARGET_SIGTRAP,
 129    TARGET_SIGABRT,
 130    -1, /* SIGEMT */
 131    TARGET_SIGFPE,
 132    TARGET_SIGKILL,
 133    TARGET_SIGBUS,
 134    TARGET_SIGSEGV,
 135    TARGET_SIGSYS,
 136    TARGET_SIGPIPE,
 137    TARGET_SIGALRM,
 138    TARGET_SIGTERM,
 139    TARGET_SIGURG,
 140    TARGET_SIGSTOP,
 141    TARGET_SIGTSTP,
 142    TARGET_SIGCONT,
 143    TARGET_SIGCHLD,
 144    TARGET_SIGTTIN,
 145    TARGET_SIGTTOU,
 146    TARGET_SIGIO,
 147    TARGET_SIGXCPU,
 148    TARGET_SIGXFSZ,
 149    TARGET_SIGVTALRM,
 150    TARGET_SIGPROF,
 151    TARGET_SIGWINCH,
 152    -1, /* SIGLOST */
 153    TARGET_SIGUSR1,
 154    TARGET_SIGUSR2,
 155#ifdef TARGET_SIGPWR
 156    TARGET_SIGPWR,
 157#else
 158    -1,
 159#endif
 160    -1, /* SIGPOLL */
 161    -1,
 162    -1,
 163    -1,
 164    -1,
 165    -1,
 166    -1,
 167    -1,
 168    -1,
 169    -1,
 170    -1,
 171    -1,
 172#ifdef __SIGRTMIN
 173    __SIGRTMIN + 1,
 174    __SIGRTMIN + 2,
 175    __SIGRTMIN + 3,
 176    __SIGRTMIN + 4,
 177    __SIGRTMIN + 5,
 178    __SIGRTMIN + 6,
 179    __SIGRTMIN + 7,
 180    __SIGRTMIN + 8,
 181    __SIGRTMIN + 9,
 182    __SIGRTMIN + 10,
 183    __SIGRTMIN + 11,
 184    __SIGRTMIN + 12,
 185    __SIGRTMIN + 13,
 186    __SIGRTMIN + 14,
 187    __SIGRTMIN + 15,
 188    __SIGRTMIN + 16,
 189    __SIGRTMIN + 17,
 190    __SIGRTMIN + 18,
 191    __SIGRTMIN + 19,
 192    __SIGRTMIN + 20,
 193    __SIGRTMIN + 21,
 194    __SIGRTMIN + 22,
 195    __SIGRTMIN + 23,
 196    __SIGRTMIN + 24,
 197    __SIGRTMIN + 25,
 198    __SIGRTMIN + 26,
 199    __SIGRTMIN + 27,
 200    __SIGRTMIN + 28,
 201    __SIGRTMIN + 29,
 202    __SIGRTMIN + 30,
 203    __SIGRTMIN + 31,
 204    -1, /* SIGCANCEL */
 205    __SIGRTMIN,
 206    __SIGRTMIN + 32,
 207    __SIGRTMIN + 33,
 208    __SIGRTMIN + 34,
 209    __SIGRTMIN + 35,
 210    __SIGRTMIN + 36,
 211    __SIGRTMIN + 37,
 212    __SIGRTMIN + 38,
 213    __SIGRTMIN + 39,
 214    __SIGRTMIN + 40,
 215    __SIGRTMIN + 41,
 216    __SIGRTMIN + 42,
 217    __SIGRTMIN + 43,
 218    __SIGRTMIN + 44,
 219    __SIGRTMIN + 45,
 220    __SIGRTMIN + 46,
 221    __SIGRTMIN + 47,
 222    __SIGRTMIN + 48,
 223    __SIGRTMIN + 49,
 224    __SIGRTMIN + 50,
 225    __SIGRTMIN + 51,
 226    __SIGRTMIN + 52,
 227    __SIGRTMIN + 53,
 228    __SIGRTMIN + 54,
 229    __SIGRTMIN + 55,
 230    __SIGRTMIN + 56,
 231    __SIGRTMIN + 57,
 232    __SIGRTMIN + 58,
 233    __SIGRTMIN + 59,
 234    __SIGRTMIN + 60,
 235    __SIGRTMIN + 61,
 236    __SIGRTMIN + 62,
 237    __SIGRTMIN + 63,
 238    __SIGRTMIN + 64,
 239    __SIGRTMIN + 65,
 240    __SIGRTMIN + 66,
 241    __SIGRTMIN + 67,
 242    __SIGRTMIN + 68,
 243    __SIGRTMIN + 69,
 244    __SIGRTMIN + 70,
 245    __SIGRTMIN + 71,
 246    __SIGRTMIN + 72,
 247    __SIGRTMIN + 73,
 248    __SIGRTMIN + 74,
 249    __SIGRTMIN + 75,
 250    __SIGRTMIN + 76,
 251    __SIGRTMIN + 77,
 252    __SIGRTMIN + 78,
 253    __SIGRTMIN + 79,
 254    __SIGRTMIN + 80,
 255    __SIGRTMIN + 81,
 256    __SIGRTMIN + 82,
 257    __SIGRTMIN + 83,
 258    __SIGRTMIN + 84,
 259    __SIGRTMIN + 85,
 260    __SIGRTMIN + 86,
 261    __SIGRTMIN + 87,
 262    __SIGRTMIN + 88,
 263    __SIGRTMIN + 89,
 264    __SIGRTMIN + 90,
 265    __SIGRTMIN + 91,
 266    __SIGRTMIN + 92,
 267    __SIGRTMIN + 93,
 268    __SIGRTMIN + 94,
 269    __SIGRTMIN + 95,
 270    -1, /* SIGINFO */
 271    -1, /* UNKNOWN */
 272    -1, /* DEFAULT */
 273    -1,
 274    -1,
 275    -1,
 276    -1,
 277    -1,
 278    -1
 279#endif
 280};
 281#else
 282/* In system mode we only need SIGINT and SIGTRAP; other signals
 283   are not yet supported.  */
 284
 285enum {
 286    TARGET_SIGINT = 2,
 287    TARGET_SIGTRAP = 5
 288};
 289
 290static int gdb_signal_table[] = {
 291    -1,
 292    -1,
 293    TARGET_SIGINT,
 294    -1,
 295    -1,
 296    TARGET_SIGTRAP
 297};
 298#endif
 299
 300#ifdef CONFIG_USER_ONLY
 301static int target_signal_to_gdb (int sig)
 302{
 303    int i;
 304    for (i = 0; i < ARRAY_SIZE (gdb_signal_table); i++)
 305        if (gdb_signal_table[i] == sig)
 306            return i;
 307    return GDB_SIGNAL_UNKNOWN;
 308}
 309#endif
 310
 311static int gdb_signal_to_target (int sig)
 312{
 313    if (sig < ARRAY_SIZE (gdb_signal_table))
 314        return gdb_signal_table[sig];
 315    else
 316        return -1;
 317}
 318
 319typedef struct GDBRegisterState {
 320    int base_reg;
 321    int num_regs;
 322    gdb_get_reg_cb get_reg;
 323    gdb_set_reg_cb set_reg;
 324    const char *xml;
 325    struct GDBRegisterState *next;
 326} GDBRegisterState;
 327
 328typedef struct GDBProcess {
 329    uint32_t pid;
 330    bool attached;
 331
 332    char target_xml[1024];
 333} GDBProcess;
 334
 335enum RSState {
 336    RS_INACTIVE,
 337    RS_IDLE,
 338    RS_GETLINE,
 339    RS_GETLINE_ESC,
 340    RS_GETLINE_RLE,
 341    RS_CHKSUM1,
 342    RS_CHKSUM2,
 343};
 344typedef struct GDBState {
 345    bool init;       /* have we been initialised? */
 346    CPUState *c_cpu; /* current CPU for step/continue ops */
 347    CPUState *g_cpu; /* current CPU for other ops */
 348    CPUState *query_cpu; /* for q{f|s}ThreadInfo */
 349    enum RSState state; /* parsing state */
 350    char line_buf[MAX_PACKET_LENGTH];
 351    int line_buf_index;
 352    int line_sum; /* running checksum */
 353    int line_csum; /* checksum at the end of the packet */
 354    GByteArray *last_packet;
 355    int signal;
 356#ifdef CONFIG_USER_ONLY
 357    int fd;
 358    char *socket_path;
 359    int running_state;
 360#else
 361    CharBackend chr;
 362    Chardev *mon_chr;
 363#endif
 364    bool multiprocess;
 365    GDBProcess *processes;
 366    int process_num;
 367    char syscall_buf[256];
 368    gdb_syscall_complete_cb current_syscall_cb;
 369    GString *str_buf;
 370    GByteArray *mem_buf;
 371} GDBState;
 372
 373/* By default use no IRQs and no timers while single stepping so as to
 374 * make single stepping like an ICE HW step.
 375 */
 376static int sstep_flags = SSTEP_ENABLE|SSTEP_NOIRQ|SSTEP_NOTIMER;
 377
 378static GDBState gdbserver_state;
 379
 380static void init_gdbserver_state(void)
 381{
 382    g_assert(!gdbserver_state.init);
 383    memset(&gdbserver_state, 0, sizeof(GDBState));
 384    gdbserver_state.init = true;
 385    gdbserver_state.str_buf = g_string_new(NULL);
 386    gdbserver_state.mem_buf = g_byte_array_sized_new(MAX_PACKET_LENGTH);
 387    gdbserver_state.last_packet = g_byte_array_sized_new(MAX_PACKET_LENGTH + 4);
 388}
 389
 390#ifndef CONFIG_USER_ONLY
 391static void reset_gdbserver_state(void)
 392{
 393    g_free(gdbserver_state.processes);
 394    gdbserver_state.processes = NULL;
 395    gdbserver_state.process_num = 0;
 396}
 397#endif
 398
 399bool gdb_has_xml;
 400
 401#ifdef CONFIG_USER_ONLY
 402
 403static int get_char(void)
 404{
 405    uint8_t ch;
 406    int ret;
 407
 408    for(;;) {
 409        ret = qemu_recv(gdbserver_state.fd, &ch, 1, 0);
 410        if (ret < 0) {
 411            if (errno == ECONNRESET)
 412                gdbserver_state.fd = -1;
 413            if (errno != EINTR)
 414                return -1;
 415        } else if (ret == 0) {
 416            close(gdbserver_state.fd);
 417            gdbserver_state.fd = -1;
 418            return -1;
 419        } else {
 420            break;
 421        }
 422    }
 423    return ch;
 424}
 425#endif
 426
 427static enum {
 428    GDB_SYS_UNKNOWN,
 429    GDB_SYS_ENABLED,
 430    GDB_SYS_DISABLED,
 431} gdb_syscall_mode;
 432
 433/* Decide if either remote gdb syscalls or native file IO should be used. */
 434int use_gdb_syscalls(void)
 435{
 436    SemihostingTarget target = semihosting_get_target();
 437    if (target == SEMIHOSTING_TARGET_NATIVE) {
 438        /* -semihosting-config target=native */
 439        return false;
 440    } else if (target == SEMIHOSTING_TARGET_GDB) {
 441        /* -semihosting-config target=gdb */
 442        return true;
 443    }
 444
 445    /* -semihosting-config target=auto */
 446    /* On the first call check if gdb is connected and remember. */
 447    if (gdb_syscall_mode == GDB_SYS_UNKNOWN) {
 448        gdb_syscall_mode = gdbserver_state.init ?
 449            GDB_SYS_ENABLED : GDB_SYS_DISABLED;
 450    }
 451    return gdb_syscall_mode == GDB_SYS_ENABLED;
 452}
 453
 454/* Resume execution.  */
 455static inline void gdb_continue(void)
 456{
 457
 458#ifdef CONFIG_USER_ONLY
 459    gdbserver_state.running_state = 1;
 460    trace_gdbstub_op_continue();
 461#else
 462    if (!runstate_needs_reset()) {
 463        trace_gdbstub_op_continue();
 464        vm_start();
 465    }
 466#endif
 467}
 468
 469/*
 470 * Resume execution, per CPU actions. For user-mode emulation it's
 471 * equivalent to gdb_continue.
 472 */
 473static int gdb_continue_partial(char *newstates)
 474{
 475    CPUState *cpu;
 476    int res = 0;
 477#ifdef CONFIG_USER_ONLY
 478    /*
 479     * This is not exactly accurate, but it's an improvement compared to the
 480     * previous situation, where only one CPU would be single-stepped.
 481     */
 482    CPU_FOREACH(cpu) {
 483        if (newstates[cpu->cpu_index] == 's') {
 484            trace_gdbstub_op_stepping(cpu->cpu_index);
 485            cpu_single_step(cpu, sstep_flags);
 486        }
 487    }
 488    gdbserver_state.running_state = 1;
 489#else
 490    int flag = 0;
 491
 492    if (!runstate_needs_reset()) {
 493        if (vm_prepare_start()) {
 494            return 0;
 495        }
 496
 497        CPU_FOREACH(cpu) {
 498            switch (newstates[cpu->cpu_index]) {
 499            case 0:
 500            case 1:
 501                break; /* nothing to do here */
 502            case 's':
 503                trace_gdbstub_op_stepping(cpu->cpu_index);
 504                cpu_single_step(cpu, sstep_flags);
 505                cpu_resume(cpu);
 506                flag = 1;
 507                break;
 508            case 'c':
 509                trace_gdbstub_op_continue_cpu(cpu->cpu_index);
 510                cpu_resume(cpu);
 511                flag = 1;
 512                break;
 513            default:
 514                res = -1;
 515                break;
 516            }
 517        }
 518    }
 519    if (flag) {
 520        qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
 521    }
 522#endif
 523    return res;
 524}
 525
 526static void put_buffer(const uint8_t *buf, int len)
 527{
 528#ifdef CONFIG_USER_ONLY
 529    int ret;
 530
 531    while (len > 0) {
 532        ret = send(gdbserver_state.fd, buf, len, 0);
 533        if (ret < 0) {
 534            if (errno != EINTR)
 535                return;
 536        } else {
 537            buf += ret;
 538            len -= ret;
 539        }
 540    }
 541#else
 542    /* XXX this blocks entire thread. Rewrite to use
 543     * qemu_chr_fe_write and background I/O callbacks */
 544    qemu_chr_fe_write_all(&gdbserver_state.chr, buf, len);
 545#endif
 546}
 547
 548static inline int fromhex(int v)
 549{
 550    if (v >= '0' && v <= '9')
 551        return v - '0';
 552    else if (v >= 'A' && v <= 'F')
 553        return v - 'A' + 10;
 554    else if (v >= 'a' && v <= 'f')
 555        return v - 'a' + 10;
 556    else
 557        return 0;
 558}
 559
 560static inline int tohex(int v)
 561{
 562    if (v < 10)
 563        return v + '0';
 564    else
 565        return v - 10 + 'a';
 566}
 567
 568/* writes 2*len+1 bytes in buf */
 569static void memtohex(GString *buf, const uint8_t *mem, int len)
 570{
 571    int i, c;
 572    for(i = 0; i < len; i++) {
 573        c = mem[i];
 574        g_string_append_c(buf, tohex(c >> 4));
 575        g_string_append_c(buf, tohex(c & 0xf));
 576    }
 577    g_string_append_c(buf, '\0');
 578}
 579
 580static void hextomem(GByteArray *mem, const char *buf, int len)
 581{
 582    int i;
 583
 584    for(i = 0; i < len; i++) {
 585        guint8 byte = fromhex(buf[0]) << 4 | fromhex(buf[1]);
 586        g_byte_array_append(mem, &byte, 1);
 587        buf += 2;
 588    }
 589}
 590
 591static void hexdump(const char *buf, int len,
 592                    void (*trace_fn)(size_t ofs, char const *text))
 593{
 594    char line_buffer[3 * 16 + 4 + 16 + 1];
 595
 596    size_t i;
 597    for (i = 0; i < len || (i & 0xF); ++i) {
 598        size_t byte_ofs = i & 15;
 599
 600        if (byte_ofs == 0) {
 601            memset(line_buffer, ' ', 3 * 16 + 4 + 16);
 602            line_buffer[3 * 16 + 4 + 16] = 0;
 603        }
 604
 605        size_t col_group = (i >> 2) & 3;
 606        size_t hex_col = byte_ofs * 3 + col_group;
 607        size_t txt_col = 3 * 16 + 4 + byte_ofs;
 608
 609        if (i < len) {
 610            char value = buf[i];
 611
 612            line_buffer[hex_col + 0] = tohex((value >> 4) & 0xF);
 613            line_buffer[hex_col + 1] = tohex((value >> 0) & 0xF);
 614            line_buffer[txt_col + 0] = (value >= ' ' && value < 127)
 615                    ? value
 616                    : '.';
 617        }
 618
 619        if (byte_ofs == 0xF)
 620            trace_fn(i & -16, line_buffer);
 621    }
 622}
 623
 624/* return -1 if error, 0 if OK */
 625static int put_packet_binary(const char *buf, int len, bool dump)
 626{
 627    int csum, i;
 628    uint8_t footer[3];
 629
 630    if (dump && trace_event_get_state_backends(TRACE_GDBSTUB_IO_BINARYREPLY)) {
 631        hexdump(buf, len, trace_gdbstub_io_binaryreply);
 632    }
 633
 634    for(;;) {
 635        g_byte_array_set_size(gdbserver_state.last_packet, 0);
 636        g_byte_array_append(gdbserver_state.last_packet,
 637                            (const uint8_t *) "$", 1);
 638        g_byte_array_append(gdbserver_state.last_packet,
 639                            (const uint8_t *) buf, len);
 640        csum = 0;
 641        for(i = 0; i < len; i++) {
 642            csum += buf[i];
 643        }
 644        footer[0] = '#';
 645        footer[1] = tohex((csum >> 4) & 0xf);
 646        footer[2] = tohex((csum) & 0xf);
 647        g_byte_array_append(gdbserver_state.last_packet, footer, 3);
 648
 649        put_buffer(gdbserver_state.last_packet->data,
 650                   gdbserver_state.last_packet->len);
 651
 652#ifdef CONFIG_USER_ONLY
 653        i = get_char();
 654        if (i < 0)
 655            return -1;
 656        if (i == '+')
 657            break;
 658#else
 659        break;
 660#endif
 661    }
 662    return 0;
 663}
 664
 665/* return -1 if error, 0 if OK */
 666static int put_packet(const char *buf)
 667{
 668    trace_gdbstub_io_reply(buf);
 669
 670    return put_packet_binary(buf, strlen(buf), false);
 671}
 672
 673static void put_strbuf(void)
 674{
 675    put_packet(gdbserver_state.str_buf->str);
 676}
 677
 678/* Encode data using the encoding for 'x' packets.  */
 679static void memtox(GString *buf, const char *mem, int len)
 680{
 681    char c;
 682
 683    while (len--) {
 684        c = *(mem++);
 685        switch (c) {
 686        case '#': case '$': case '*': case '}':
 687            g_string_append_c(buf, '}');
 688            g_string_append_c(buf, c ^ 0x20);
 689            break;
 690        default:
 691            g_string_append_c(buf, c);
 692            break;
 693        }
 694    }
 695}
 696
 697static uint32_t gdb_get_cpu_pid(CPUState *cpu)
 698{
 699    /* TODO: In user mode, we should use the task state PID */
 700    if (cpu->cluster_index == UNASSIGNED_CLUSTER_INDEX) {
 701        /* Return the default process' PID */
 702        int index = gdbserver_state.process_num - 1;
 703        return gdbserver_state.processes[index].pid;
 704    }
 705    return cpu->cluster_index + 1;
 706}
 707
 708static GDBProcess *gdb_get_process(uint32_t pid)
 709{
 710    int i;
 711
 712    if (!pid) {
 713        /* 0 means any process, we take the first one */
 714        return &gdbserver_state.processes[0];
 715    }
 716
 717    for (i = 0; i < gdbserver_state.process_num; i++) {
 718        if (gdbserver_state.processes[i].pid == pid) {
 719            return &gdbserver_state.processes[i];
 720        }
 721    }
 722
 723    return NULL;
 724}
 725
 726static GDBProcess *gdb_get_cpu_process(CPUState *cpu)
 727{
 728    return gdb_get_process(gdb_get_cpu_pid(cpu));
 729}
 730
 731static CPUState *find_cpu(uint32_t thread_id)
 732{
 733    CPUState *cpu;
 734
 735    CPU_FOREACH(cpu) {
 736        if (cpu_gdb_index(cpu) == thread_id) {
 737            return cpu;
 738        }
 739    }
 740
 741    return NULL;
 742}
 743
 744static CPUState *get_first_cpu_in_process(GDBProcess *process)
 745{
 746    CPUState *cpu;
 747
 748    CPU_FOREACH(cpu) {
 749        if (gdb_get_cpu_pid(cpu) == process->pid) {
 750            return cpu;
 751        }
 752    }
 753
 754    return NULL;
 755}
 756
 757static CPUState *gdb_next_cpu_in_process(CPUState *cpu)
 758{
 759    uint32_t pid = gdb_get_cpu_pid(cpu);
 760    cpu = CPU_NEXT(cpu);
 761
 762    while (cpu) {
 763        if (gdb_get_cpu_pid(cpu) == pid) {
 764            break;
 765        }
 766
 767        cpu = CPU_NEXT(cpu);
 768    }
 769
 770    return cpu;
 771}
 772
 773/* Return the cpu following @cpu, while ignoring unattached processes. */
 774static CPUState *gdb_next_attached_cpu(CPUState *cpu)
 775{
 776    cpu = CPU_NEXT(cpu);
 777
 778    while (cpu) {
 779        if (gdb_get_cpu_process(cpu)->attached) {
 780            break;
 781        }
 782
 783        cpu = CPU_NEXT(cpu);
 784    }
 785
 786    return cpu;
 787}
 788
 789/* Return the first attached cpu */
 790static CPUState *gdb_first_attached_cpu(void)
 791{
 792    CPUState *cpu = first_cpu;
 793    GDBProcess *process = gdb_get_cpu_process(cpu);
 794
 795    if (!process->attached) {
 796        return gdb_next_attached_cpu(cpu);
 797    }
 798
 799    return cpu;
 800}
 801
 802static CPUState *gdb_get_cpu(uint32_t pid, uint32_t tid)
 803{
 804    GDBProcess *process;
 805    CPUState *cpu;
 806
 807    if (!pid && !tid) {
 808        /* 0 means any process/thread, we take the first attached one */
 809        return gdb_first_attached_cpu();
 810    } else if (pid && !tid) {
 811        /* any thread in a specific process */
 812        process = gdb_get_process(pid);
 813
 814        if (process == NULL) {
 815            return NULL;
 816        }
 817
 818        return get_first_cpu_in_process(process);
 819    } else {
 820        /* a specific thread */
 821        cpu = find_cpu(tid);
 822
 823        if (cpu == NULL) {
 824            return NULL;
 825        }
 826
 827        process = gdb_get_cpu_process(cpu);
 828
 829        if (pid && process->pid != pid) {
 830            return NULL;
 831        }
 832
 833        return cpu;
 834    }
 835}
 836
 837static const char *get_feature_xml(const char *p, const char **newp,
 838                                   GDBProcess *process)
 839{
 840    size_t len;
 841    int i;
 842    const char *name;
 843    CPUState *cpu = get_first_cpu_in_process(process);
 844    CPUClass *cc = CPU_GET_CLASS(cpu);
 845
 846    len = 0;
 847    while (p[len] && p[len] != ':')
 848        len++;
 849    *newp = p + len;
 850
 851    name = NULL;
 852    if (strncmp(p, "target.xml", len) == 0) {
 853        char *buf = process->target_xml;
 854        const size_t buf_sz = sizeof(process->target_xml);
 855
 856        /* Generate the XML description for this CPU.  */
 857        if (!buf[0]) {
 858            GDBRegisterState *r;
 859
 860            pstrcat(buf, buf_sz,
 861                    "<?xml version=\"1.0\"?>"
 862                    "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"
 863                    "<target>");
 864            if (cc->gdb_arch_name) {
 865                gchar *arch = cc->gdb_arch_name(cpu);
 866                pstrcat(buf, buf_sz, "<architecture>");
 867                pstrcat(buf, buf_sz, arch);
 868                pstrcat(buf, buf_sz, "</architecture>");
 869                g_free(arch);
 870            }
 871            pstrcat(buf, buf_sz, "<xi:include href=\"");
 872            pstrcat(buf, buf_sz, cc->gdb_core_xml_file);
 873            pstrcat(buf, buf_sz, "\"/>");
 874            for (r = cpu->gdb_regs; r; r = r->next) {
 875                pstrcat(buf, buf_sz, "<xi:include href=\"");
 876                pstrcat(buf, buf_sz, r->xml);
 877                pstrcat(buf, buf_sz, "\"/>");
 878            }
 879            pstrcat(buf, buf_sz, "</target>");
 880        }
 881        return buf;
 882    }
 883    if (cc->gdb_get_dynamic_xml) {
 884        char *xmlname = g_strndup(p, len);
 885        const char *xml = cc->gdb_get_dynamic_xml(cpu, xmlname);
 886
 887        g_free(xmlname);
 888        if (xml) {
 889            return xml;
 890        }
 891    }
 892    for (i = 0; ; i++) {
 893        name = xml_builtin[i][0];
 894        if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))
 895            break;
 896    }
 897    return name ? xml_builtin[i][1] : NULL;
 898}
 899
 900static int gdb_read_register(CPUState *cpu, GByteArray *buf, int reg)
 901{
 902    CPUClass *cc = CPU_GET_CLASS(cpu);
 903    CPUArchState *env = cpu->env_ptr;
 904    GDBRegisterState *r;
 905
 906    if (reg < cc->gdb_num_core_regs) {
 907        return cc->gdb_read_register(cpu, buf, reg);
 908    }
 909
 910    for (r = cpu->gdb_regs; r; r = r->next) {
 911        if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
 912            return r->get_reg(env, buf, reg - r->base_reg);
 913        }
 914    }
 915    return 0;
 916}
 917
 918static int gdb_write_register(CPUState *cpu, uint8_t *mem_buf, int reg)
 919{
 920    CPUClass *cc = CPU_GET_CLASS(cpu);
 921    CPUArchState *env = cpu->env_ptr;
 922    GDBRegisterState *r;
 923
 924    if (reg < cc->gdb_num_core_regs) {
 925        return cc->gdb_write_register(cpu, mem_buf, reg);
 926    }
 927
 928    for (r = cpu->gdb_regs; r; r = r->next) {
 929        if (r->base_reg <= reg && reg < r->base_reg + r->num_regs) {
 930            return r->set_reg(env, mem_buf, reg - r->base_reg);
 931        }
 932    }
 933    return 0;
 934}
 935
 936/* Register a supplemental set of CPU registers.  If g_pos is nonzero it
 937   specifies the first register number and these registers are included in
 938   a standard "g" packet.  Direction is relative to gdb, i.e. get_reg is
 939   gdb reading a CPU register, and set_reg is gdb modifying a CPU register.
 940 */
 941
 942void gdb_register_coprocessor(CPUState *cpu,
 943                              gdb_get_reg_cb get_reg, gdb_set_reg_cb set_reg,
 944                              int num_regs, const char *xml, int g_pos)
 945{
 946    GDBRegisterState *s;
 947    GDBRegisterState **p;
 948
 949    p = &cpu->gdb_regs;
 950    while (*p) {
 951        /* Check for duplicates.  */
 952        if (strcmp((*p)->xml, xml) == 0)
 953            return;
 954        p = &(*p)->next;
 955    }
 956
 957    s = g_new0(GDBRegisterState, 1);
 958    s->base_reg = cpu->gdb_num_regs;
 959    s->num_regs = num_regs;
 960    s->get_reg = get_reg;
 961    s->set_reg = set_reg;
 962    s->xml = xml;
 963
 964    /* Add to end of list.  */
 965    cpu->gdb_num_regs += num_regs;
 966    *p = s;
 967    if (g_pos) {
 968        if (g_pos != s->base_reg) {
 969            error_report("Error: Bad gdb register numbering for '%s', "
 970                         "expected %d got %d", xml, g_pos, s->base_reg);
 971        } else {
 972            cpu->gdb_num_g_regs = cpu->gdb_num_regs;
 973        }
 974    }
 975}
 976
 977#ifndef CONFIG_USER_ONLY
 978/* Translate GDB watchpoint type to a flags value for cpu_watchpoint_* */
 979static inline int xlat_gdb_type(CPUState *cpu, int gdbtype)
 980{
 981    static const int xlat[] = {
 982        [GDB_WATCHPOINT_WRITE]  = BP_GDB | BP_MEM_WRITE,
 983        [GDB_WATCHPOINT_READ]   = BP_GDB | BP_MEM_READ,
 984        [GDB_WATCHPOINT_ACCESS] = BP_GDB | BP_MEM_ACCESS,
 985    };
 986
 987    CPUClass *cc = CPU_GET_CLASS(cpu);
 988    int cputype = xlat[gdbtype];
 989
 990    if (cc->gdb_stop_before_watchpoint) {
 991        cputype |= BP_STOP_BEFORE_ACCESS;
 992    }
 993    return cputype;
 994}
 995#endif
 996
 997static int gdb_breakpoint_insert(int type, target_ulong addr, target_ulong len)
 998{
 999    CPUState *cpu;
1000    int err = 0;
1001
1002    if (kvm_enabled()) {
1003        return kvm_insert_breakpoint(gdbserver_state.c_cpu, addr, len, type);
1004    }
1005
1006    switch (type) {
1007    case GDB_BREAKPOINT_SW:
1008    case GDB_BREAKPOINT_HW:
1009        CPU_FOREACH(cpu) {
1010            err = cpu_breakpoint_insert(cpu, addr, BP_GDB, NULL);
1011            if (err) {
1012                break;
1013            }
1014        }
1015        return err;
1016#ifndef CONFIG_USER_ONLY
1017    case GDB_WATCHPOINT_WRITE:
1018    case GDB_WATCHPOINT_READ:
1019    case GDB_WATCHPOINT_ACCESS:
1020        CPU_FOREACH(cpu) {
1021            err = cpu_watchpoint_insert(cpu, addr, len,
1022                                        xlat_gdb_type(cpu, type), NULL);
1023            if (err) {
1024                break;
1025            }
1026        }
1027        return err;
1028#endif
1029    default:
1030        return -ENOSYS;
1031    }
1032}
1033
1034static int gdb_breakpoint_remove(int type, target_ulong addr, target_ulong len)
1035{
1036    CPUState *cpu;
1037    int err = 0;
1038
1039    if (kvm_enabled()) {
1040        return kvm_remove_breakpoint(gdbserver_state.c_cpu, addr, len, type);
1041    }
1042
1043    switch (type) {
1044    case GDB_BREAKPOINT_SW:
1045    case GDB_BREAKPOINT_HW:
1046        CPU_FOREACH(cpu) {
1047            err = cpu_breakpoint_remove(cpu, addr, BP_GDB);
1048            if (err) {
1049                break;
1050            }
1051        }
1052        return err;
1053#ifndef CONFIG_USER_ONLY
1054    case GDB_WATCHPOINT_WRITE:
1055    case GDB_WATCHPOINT_READ:
1056    case GDB_WATCHPOINT_ACCESS:
1057        CPU_FOREACH(cpu) {
1058            err = cpu_watchpoint_remove(cpu, addr, len,
1059                                        xlat_gdb_type(cpu, type));
1060            if (err)
1061                break;
1062        }
1063        return err;
1064#endif
1065    default:
1066        return -ENOSYS;
1067    }
1068}
1069
1070static inline void gdb_cpu_breakpoint_remove_all(CPUState *cpu)
1071{
1072    cpu_breakpoint_remove_all(cpu, BP_GDB);
1073#ifndef CONFIG_USER_ONLY
1074    cpu_watchpoint_remove_all(cpu, BP_GDB);
1075#endif
1076}
1077
1078static void gdb_process_breakpoint_remove_all(GDBProcess *p)
1079{
1080    CPUState *cpu = get_first_cpu_in_process(p);
1081
1082    while (cpu) {
1083        gdb_cpu_breakpoint_remove_all(cpu);
1084        cpu = gdb_next_cpu_in_process(cpu);
1085    }
1086}
1087
1088static void gdb_breakpoint_remove_all(void)
1089{
1090    CPUState *cpu;
1091
1092    if (kvm_enabled()) {
1093        kvm_remove_all_breakpoints(gdbserver_state.c_cpu);
1094        return;
1095    }
1096
1097    CPU_FOREACH(cpu) {
1098        gdb_cpu_breakpoint_remove_all(cpu);
1099    }
1100}
1101
1102static void gdb_set_cpu_pc(target_ulong pc)
1103{
1104    CPUState *cpu = gdbserver_state.c_cpu;
1105
1106    cpu_synchronize_state(cpu);
1107    cpu_set_pc(cpu, pc);
1108}
1109
1110static void gdb_append_thread_id(CPUState *cpu, GString *buf)
1111{
1112    if (gdbserver_state.multiprocess) {
1113        g_string_append_printf(buf, "p%02x.%02x",
1114                               gdb_get_cpu_pid(cpu), cpu_gdb_index(cpu));
1115    } else {
1116        g_string_append_printf(buf, "%02x", cpu_gdb_index(cpu));
1117    }
1118}
1119
1120typedef enum GDBThreadIdKind {
1121    GDB_ONE_THREAD = 0,
1122    GDB_ALL_THREADS,     /* One process, all threads */
1123    GDB_ALL_PROCESSES,
1124    GDB_READ_THREAD_ERR
1125} GDBThreadIdKind;
1126
1127static GDBThreadIdKind read_thread_id(const char *buf, const char **end_buf,
1128                                      uint32_t *pid, uint32_t *tid)
1129{
1130    unsigned long p, t;
1131    int ret;
1132
1133    if (*buf == 'p') {
1134        buf++;
1135        ret = qemu_strtoul(buf, &buf, 16, &p);
1136
1137        if (ret) {
1138            return GDB_READ_THREAD_ERR;
1139        }
1140
1141        /* Skip '.' */
1142        buf++;
1143    } else {
1144        p = 1;
1145    }
1146
1147    ret = qemu_strtoul(buf, &buf, 16, &t);
1148
1149    if (ret) {
1150        return GDB_READ_THREAD_ERR;
1151    }
1152
1153    *end_buf = buf;
1154
1155    if (p == -1) {
1156        return GDB_ALL_PROCESSES;
1157    }
1158
1159    if (pid) {
1160        *pid = p;
1161    }
1162
1163    if (t == -1) {
1164        return GDB_ALL_THREADS;
1165    }
1166
1167    if (tid) {
1168        *tid = t;
1169    }
1170
1171    return GDB_ONE_THREAD;
1172}
1173
1174/**
1175 * gdb_handle_vcont - Parses and handles a vCont packet.
1176 * returns -ENOTSUP if a command is unsupported, -EINVAL or -ERANGE if there is
1177 *         a format error, 0 on success.
1178 */
1179static int gdb_handle_vcont(const char *p)
1180{
1181    int res, signal = 0;
1182    char cur_action;
1183    char *newstates;
1184    unsigned long tmp;
1185    uint32_t pid, tid;
1186    GDBProcess *process;
1187    CPUState *cpu;
1188    GDBThreadIdKind kind;
1189#ifdef CONFIG_USER_ONLY
1190    int max_cpus = 1; /* global variable max_cpus exists only in system mode */
1191
1192    CPU_FOREACH(cpu) {
1193        max_cpus = max_cpus <= cpu->cpu_index ? cpu->cpu_index + 1 : max_cpus;
1194    }
1195#else
1196    MachineState *ms = MACHINE(qdev_get_machine());
1197    unsigned int max_cpus = ms->smp.max_cpus;
1198#endif
1199    /* uninitialised CPUs stay 0 */
1200    newstates = g_new0(char, max_cpus);
1201
1202    /* mark valid CPUs with 1 */
1203    CPU_FOREACH(cpu) {
1204        newstates[cpu->cpu_index] = 1;
1205    }
1206
1207    /*
1208     * res keeps track of what error we are returning, with -ENOTSUP meaning
1209     * that the command is unknown or unsupported, thus returning an empty
1210     * packet, while -EINVAL and -ERANGE cause an E22 packet, due to invalid,
1211     *  or incorrect parameters passed.
1212     */
1213    res = 0;
1214    while (*p) {
1215        if (*p++ != ';') {
1216            res = -ENOTSUP;
1217            goto out;
1218        }
1219
1220        cur_action = *p++;
1221        if (cur_action == 'C' || cur_action == 'S') {
1222            cur_action = qemu_tolower(cur_action);
1223            res = qemu_strtoul(p + 1, &p, 16, &tmp);
1224            if (res) {
1225                goto out;
1226            }
1227            signal = gdb_signal_to_target(tmp);
1228        } else if (cur_action != 'c' && cur_action != 's') {
1229            /* unknown/invalid/unsupported command */
1230            res = -ENOTSUP;
1231            goto out;
1232        }
1233
1234        if (*p == '\0' || *p == ';') {
1235            /*
1236             * No thread specifier, action is on "all threads". The
1237             * specification is unclear regarding the process to act on. We
1238             * choose all processes.
1239             */
1240            kind = GDB_ALL_PROCESSES;
1241        } else if (*p++ == ':') {
1242            kind = read_thread_id(p, &p, &pid, &tid);
1243        } else {
1244            res = -ENOTSUP;
1245            goto out;
1246        }
1247
1248        switch (kind) {
1249        case GDB_READ_THREAD_ERR:
1250            res = -EINVAL;
1251            goto out;
1252
1253        case GDB_ALL_PROCESSES:
1254            cpu = gdb_first_attached_cpu();
1255            while (cpu) {
1256                if (newstates[cpu->cpu_index] == 1) {
1257                    newstates[cpu->cpu_index] = cur_action;
1258                }
1259
1260                cpu = gdb_next_attached_cpu(cpu);
1261            }
1262            break;
1263
1264        case GDB_ALL_THREADS:
1265            process = gdb_get_process(pid);
1266
1267            if (!process->attached) {
1268                res = -EINVAL;
1269                goto out;
1270            }
1271
1272            cpu = get_first_cpu_in_process(process);
1273            while (cpu) {
1274                if (newstates[cpu->cpu_index] == 1) {
1275                    newstates[cpu->cpu_index] = cur_action;
1276                }
1277
1278                cpu = gdb_next_cpu_in_process(cpu);
1279            }
1280            break;
1281
1282        case GDB_ONE_THREAD:
1283            cpu = gdb_get_cpu(pid, tid);
1284
1285            /* invalid CPU/thread specified */
1286            if (!cpu) {
1287                res = -EINVAL;
1288                goto out;
1289            }
1290
1291            /* only use if no previous match occourred */
1292            if (newstates[cpu->cpu_index] == 1) {
1293                newstates[cpu->cpu_index] = cur_action;
1294            }
1295            break;
1296        }
1297    }
1298    gdbserver_state.signal = signal;
1299    gdb_continue_partial(newstates);
1300
1301out:
1302    g_free(newstates);
1303
1304    return res;
1305}
1306
1307typedef union GdbCmdVariant {
1308    const char *data;
1309    uint8_t opcode;
1310    unsigned long val_ul;
1311    unsigned long long val_ull;
1312    struct {
1313        GDBThreadIdKind kind;
1314        uint32_t pid;
1315        uint32_t tid;
1316    } thread_id;
1317} GdbCmdVariant;
1318
1319static const char *cmd_next_param(const char *param, const char delimiter)
1320{
1321    static const char all_delimiters[] = ",;:=";
1322    char curr_delimiters[2] = {0};
1323    const char *delimiters;
1324
1325    if (delimiter == '?') {
1326        delimiters = all_delimiters;
1327    } else if (delimiter == '0') {
1328        return strchr(param, '\0');
1329    } else if (delimiter == '.' && *param) {
1330        return param + 1;
1331    } else {
1332        curr_delimiters[0] = delimiter;
1333        delimiters = curr_delimiters;
1334    }
1335
1336    param += strcspn(param, delimiters);
1337    if (*param) {
1338        param++;
1339    }
1340    return param;
1341}
1342
1343static int cmd_parse_params(const char *data, const char *schema,
1344                            GdbCmdVariant *params, int *num_params)
1345{
1346    int curr_param;
1347    const char *curr_schema, *curr_data;
1348
1349    *num_params = 0;
1350
1351    if (!schema) {
1352        return 0;
1353    }
1354
1355    curr_schema = schema;
1356    curr_param = 0;
1357    curr_data = data;
1358    while (curr_schema[0] && curr_schema[1] && *curr_data) {
1359        switch (curr_schema[0]) {
1360        case 'l':
1361            if (qemu_strtoul(curr_data, &curr_data, 16,
1362                             &params[curr_param].val_ul)) {
1363                return -EINVAL;
1364            }
1365            curr_param++;
1366            curr_data = cmd_next_param(curr_data, curr_schema[1]);
1367            break;
1368        case 'L':
1369            if (qemu_strtou64(curr_data, &curr_data, 16,
1370                              (uint64_t *)&params[curr_param].val_ull)) {
1371                return -EINVAL;
1372            }
1373            curr_param++;
1374            curr_data = cmd_next_param(curr_data, curr_schema[1]);
1375            break;
1376        case 's':
1377            params[curr_param].data = curr_data;
1378            curr_param++;
1379            curr_data = cmd_next_param(curr_data, curr_schema[1]);
1380            break;
1381        case 'o':
1382            params[curr_param].opcode = *(uint8_t *)curr_data;
1383            curr_param++;
1384            curr_data = cmd_next_param(curr_data, curr_schema[1]);
1385            break;
1386        case 't':
1387            params[curr_param].thread_id.kind =
1388                read_thread_id(curr_data, &curr_data,
1389                               &params[curr_param].thread_id.pid,
1390                               &params[curr_param].thread_id.tid);
1391            curr_param++;
1392            curr_data = cmd_next_param(curr_data, curr_schema[1]);
1393            break;
1394        case '?':
1395            curr_data = cmd_next_param(curr_data, curr_schema[1]);
1396            break;
1397        default:
1398            return -EINVAL;
1399        }
1400        curr_schema += 2;
1401    }
1402
1403    *num_params = curr_param;
1404    return 0;
1405}
1406
1407typedef struct GdbCmdContext {
1408    GdbCmdVariant *params;
1409    int num_params;
1410} GdbCmdContext;
1411
1412typedef void (*GdbCmdHandler)(GdbCmdContext *gdb_ctx, void *user_ctx);
1413
1414/*
1415 * cmd_startswith -> cmd is compared using startswith
1416 *
1417 *
1418 * schema definitions:
1419 * Each schema parameter entry consists of 2 chars,
1420 * the first char represents the parameter type handling
1421 * the second char represents the delimiter for the next parameter
1422 *
1423 * Currently supported schema types:
1424 * 'l' -> unsigned long (stored in .val_ul)
1425 * 'L' -> unsigned long long (stored in .val_ull)
1426 * 's' -> string (stored in .data)
1427 * 'o' -> single char (stored in .opcode)
1428 * 't' -> thread id (stored in .thread_id)
1429 * '?' -> skip according to delimiter
1430 *
1431 * Currently supported delimiters:
1432 * '?' -> Stop at any delimiter (",;:=\0")
1433 * '0' -> Stop at "\0"
1434 * '.' -> Skip 1 char unless reached "\0"
1435 * Any other value is treated as the delimiter value itself
1436 */
1437typedef struct GdbCmdParseEntry {
1438    GdbCmdHandler handler;
1439    const char *cmd;
1440    bool cmd_startswith;
1441    const char *schema;
1442} GdbCmdParseEntry;
1443
1444static inline int startswith(const char *string, const char *pattern)
1445{
1446  return !strncmp(string, pattern, strlen(pattern));
1447}
1448
1449static int process_string_cmd(void *user_ctx, const char *data,
1450                              const GdbCmdParseEntry *cmds, int num_cmds)
1451{
1452    int i, schema_len, max_num_params = 0;
1453    GdbCmdContext gdb_ctx;
1454
1455    if (!cmds) {
1456        return -1;
1457    }
1458
1459    for (i = 0; i < num_cmds; i++) {
1460        const GdbCmdParseEntry *cmd = &cmds[i];
1461        g_assert(cmd->handler && cmd->cmd);
1462
1463        if ((cmd->cmd_startswith && !startswith(data, cmd->cmd)) ||
1464            (!cmd->cmd_startswith && strcmp(cmd->cmd, data))) {
1465            continue;
1466        }
1467
1468        if (cmd->schema) {
1469            schema_len = strlen(cmd->schema);
1470            if (schema_len % 2) {
1471                return -2;
1472            }
1473
1474            max_num_params = schema_len / 2;
1475        }
1476
1477        gdb_ctx.params =
1478            (GdbCmdVariant *)alloca(sizeof(*gdb_ctx.params) * max_num_params);
1479        memset(gdb_ctx.params, 0, sizeof(*gdb_ctx.params) * max_num_params);
1480
1481        if (cmd_parse_params(&data[strlen(cmd->cmd)], cmd->schema,
1482                             gdb_ctx.params, &gdb_ctx.num_params)) {
1483            return -1;
1484        }
1485
1486        cmd->handler(&gdb_ctx, user_ctx);
1487        return 0;
1488    }
1489
1490    return -1;
1491}
1492
1493static void run_cmd_parser(const char *data, const GdbCmdParseEntry *cmd)
1494{
1495    if (!data) {
1496        return;
1497    }
1498
1499    g_string_set_size(gdbserver_state.str_buf, 0);
1500    g_byte_array_set_size(gdbserver_state.mem_buf, 0);
1501
1502    /* In case there was an error during the command parsing we must
1503    * send a NULL packet to indicate the command is not supported */
1504    if (process_string_cmd(NULL, data, cmd, 1)) {
1505        put_packet("");
1506    }
1507}
1508
1509static void handle_detach(GdbCmdContext *gdb_ctx, void *user_ctx)
1510{
1511    GDBProcess *process;
1512    uint32_t pid = 1;
1513
1514    if (gdbserver_state.multiprocess) {
1515        if (!gdb_ctx->num_params) {
1516            put_packet("E22");
1517            return;
1518        }
1519
1520        pid = gdb_ctx->params[0].val_ul;
1521    }
1522
1523    process = gdb_get_process(pid);
1524    gdb_process_breakpoint_remove_all(process);
1525    process->attached = false;
1526
1527    if (pid == gdb_get_cpu_pid(gdbserver_state.c_cpu)) {
1528        gdbserver_state.c_cpu = gdb_first_attached_cpu();
1529    }
1530
1531    if (pid == gdb_get_cpu_pid(gdbserver_state.g_cpu)) {
1532        gdbserver_state.g_cpu = gdb_first_attached_cpu();
1533    }
1534
1535    if (!gdbserver_state.c_cpu) {
1536        /* No more process attached */
1537        gdb_syscall_mode = GDB_SYS_DISABLED;
1538        gdb_continue();
1539    }
1540    put_packet("OK");
1541}
1542
1543static void handle_thread_alive(GdbCmdContext *gdb_ctx, void *user_ctx)
1544{
1545    CPUState *cpu;
1546
1547    if (!gdb_ctx->num_params) {
1548        put_packet("E22");
1549        return;
1550    }
1551
1552    if (gdb_ctx->params[0].thread_id.kind == GDB_READ_THREAD_ERR) {
1553        put_packet("E22");
1554        return;
1555    }
1556
1557    cpu = gdb_get_cpu(gdb_ctx->params[0].thread_id.pid,
1558                      gdb_ctx->params[0].thread_id.tid);
1559    if (!cpu) {
1560        put_packet("E22");
1561        return;
1562    }
1563
1564    put_packet("OK");
1565}
1566
1567static void handle_continue(GdbCmdContext *gdb_ctx, void *user_ctx)
1568{
1569    if (gdb_ctx->num_params) {
1570        gdb_set_cpu_pc(gdb_ctx->params[0].val_ull);
1571    }
1572
1573    gdbserver_state.signal = 0;
1574    gdb_continue();
1575}
1576
1577static void handle_cont_with_sig(GdbCmdContext *gdb_ctx, void *user_ctx)
1578{
1579    unsigned long signal = 0;
1580
1581    /*
1582     * Note: C sig;[addr] is currently unsupported and we simply
1583     *       omit the addr parameter
1584     */
1585    if (gdb_ctx->num_params) {
1586        signal = gdb_ctx->params[0].val_ul;
1587    }
1588
1589    gdbserver_state.signal = gdb_signal_to_target(signal);
1590    if (gdbserver_state.signal == -1) {
1591        gdbserver_state.signal = 0;
1592    }
1593    gdb_continue();
1594}
1595
1596static void handle_set_thread(GdbCmdContext *gdb_ctx, void *user_ctx)
1597{
1598    CPUState *cpu;
1599
1600    if (gdb_ctx->num_params != 2) {
1601        put_packet("E22");
1602        return;
1603    }
1604
1605    if (gdb_ctx->params[1].thread_id.kind == GDB_READ_THREAD_ERR) {
1606        put_packet("E22");
1607        return;
1608    }
1609
1610    if (gdb_ctx->params[1].thread_id.kind != GDB_ONE_THREAD) {
1611        put_packet("OK");
1612        return;
1613    }
1614
1615    cpu = gdb_get_cpu(gdb_ctx->params[1].thread_id.pid,
1616                      gdb_ctx->params[1].thread_id.tid);
1617    if (!cpu) {
1618        put_packet("E22");
1619        return;
1620    }
1621
1622    /*
1623     * Note: This command is deprecated and modern gdb's will be using the
1624     *       vCont command instead.
1625     */
1626    switch (gdb_ctx->params[0].opcode) {
1627    case 'c':
1628        gdbserver_state.c_cpu = cpu;
1629        put_packet("OK");
1630        break;
1631    case 'g':
1632        gdbserver_state.g_cpu = cpu;
1633        put_packet("OK");
1634        break;
1635    default:
1636        put_packet("E22");
1637        break;
1638    }
1639}
1640
1641static void handle_insert_bp(GdbCmdContext *gdb_ctx, void *user_ctx)
1642{
1643    int res;
1644
1645    if (gdb_ctx->num_params != 3) {
1646        put_packet("E22");
1647        return;
1648    }
1649
1650    res = gdb_breakpoint_insert(gdb_ctx->params[0].val_ul,
1651                                gdb_ctx->params[1].val_ull,
1652                                gdb_ctx->params[2].val_ull);
1653    if (res >= 0) {
1654        put_packet("OK");
1655        return;
1656    } else if (res == -ENOSYS) {
1657        put_packet("");
1658        return;
1659    }
1660
1661    put_packet("E22");
1662}
1663
1664static void handle_remove_bp(GdbCmdContext *gdb_ctx, void *user_ctx)
1665{
1666    int res;
1667
1668    if (gdb_ctx->num_params != 3) {
1669        put_packet("E22");
1670        return;
1671    }
1672
1673    res = gdb_breakpoint_remove(gdb_ctx->params[0].val_ul,
1674                                gdb_ctx->params[1].val_ull,
1675                                gdb_ctx->params[2].val_ull);
1676    if (res >= 0) {
1677        put_packet("OK");
1678        return;
1679    } else if (res == -ENOSYS) {
1680        put_packet("");
1681        return;
1682    }
1683
1684    put_packet("E22");
1685}
1686
1687/*
1688 * handle_set/get_reg
1689 *
1690 * Older gdb are really dumb, and don't use 'G/g' if 'P/p' is available.
1691 * This works, but can be very slow. Anything new enough to understand
1692 * XML also knows how to use this properly. However to use this we
1693 * need to define a local XML file as well as be talking to a
1694 * reasonably modern gdb. Responding with an empty packet will cause
1695 * the remote gdb to fallback to older methods.
1696 */
1697
1698static void handle_set_reg(GdbCmdContext *gdb_ctx, void *user_ctx)
1699{
1700    int reg_size;
1701
1702    if (!gdb_has_xml) {
1703        put_packet("");
1704        return;
1705    }
1706
1707    if (gdb_ctx->num_params != 2) {
1708        put_packet("E22");
1709        return;
1710    }
1711
1712    reg_size = strlen(gdb_ctx->params[1].data) / 2;
1713    hextomem(gdbserver_state.mem_buf, gdb_ctx->params[1].data, reg_size);
1714    gdb_write_register(gdbserver_state.g_cpu, gdbserver_state.mem_buf->data,
1715                       gdb_ctx->params[0].val_ull);
1716    put_packet("OK");
1717}
1718
1719static void handle_get_reg(GdbCmdContext *gdb_ctx, void *user_ctx)
1720{
1721    int reg_size;
1722
1723    if (!gdb_has_xml) {
1724        put_packet("");
1725        return;
1726    }
1727
1728    if (!gdb_ctx->num_params) {
1729        put_packet("E14");
1730        return;
1731    }
1732
1733    reg_size = gdb_read_register(gdbserver_state.g_cpu,
1734                                 gdbserver_state.mem_buf,
1735                                 gdb_ctx->params[0].val_ull);
1736    if (!reg_size) {
1737        put_packet("E14");
1738        return;
1739    } else {
1740        g_byte_array_set_size(gdbserver_state.mem_buf, reg_size);
1741    }
1742
1743    memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data, reg_size);
1744    put_strbuf();
1745}
1746
1747static void handle_write_mem(GdbCmdContext *gdb_ctx, void *user_ctx)
1748{
1749    if (gdb_ctx->num_params != 3) {
1750        put_packet("E22");
1751        return;
1752    }
1753
1754    /* hextomem() reads 2*len bytes */
1755    if (gdb_ctx->params[1].val_ull > strlen(gdb_ctx->params[2].data) / 2) {
1756        put_packet("E22");
1757        return;
1758    }
1759
1760    hextomem(gdbserver_state.mem_buf, gdb_ctx->params[2].data,
1761             gdb_ctx->params[1].val_ull);
1762    if (target_memory_rw_debug(gdbserver_state.g_cpu, gdb_ctx->params[0].val_ull,
1763                               gdbserver_state.mem_buf->data,
1764                               gdbserver_state.mem_buf->len, true)) {
1765        put_packet("E14");
1766        return;
1767    }
1768
1769    put_packet("OK");
1770}
1771
1772static void handle_read_mem(GdbCmdContext *gdb_ctx, void *user_ctx)
1773{
1774    if (gdb_ctx->num_params != 2) {
1775        put_packet("E22");
1776        return;
1777    }
1778
1779    /* memtohex() doubles the required space */
1780    if (gdb_ctx->params[1].val_ull > MAX_PACKET_LENGTH / 2) {
1781        put_packet("E22");
1782        return;
1783    }
1784
1785    g_byte_array_set_size(gdbserver_state.mem_buf, gdb_ctx->params[1].val_ull);
1786
1787    if (target_memory_rw_debug(gdbserver_state.g_cpu, gdb_ctx->params[0].val_ull,
1788                               gdbserver_state.mem_buf->data,
1789                               gdbserver_state.mem_buf->len, false)) {
1790        put_packet("E14");
1791        return;
1792    }
1793
1794    memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data,
1795             gdbserver_state.mem_buf->len);
1796    put_strbuf();
1797}
1798
1799static void handle_write_all_regs(GdbCmdContext *gdb_ctx, void *user_ctx)
1800{
1801    target_ulong addr, len;
1802    uint8_t *registers;
1803    int reg_size;
1804
1805    if (!gdb_ctx->num_params) {
1806        return;
1807    }
1808
1809    cpu_synchronize_state(gdbserver_state.g_cpu);
1810    len = strlen(gdb_ctx->params[0].data) / 2;
1811    hextomem(gdbserver_state.mem_buf, gdb_ctx->params[0].data, len);
1812    registers = gdbserver_state.mem_buf->data;
1813    for (addr = 0; addr < gdbserver_state.g_cpu->gdb_num_g_regs && len > 0;
1814         addr++) {
1815        reg_size = gdb_write_register(gdbserver_state.g_cpu, registers, addr);
1816        len -= reg_size;
1817        registers += reg_size;
1818    }
1819    put_packet("OK");
1820}
1821
1822static void handle_read_all_regs(GdbCmdContext *gdb_ctx, void *user_ctx)
1823{
1824    target_ulong addr, len;
1825
1826    cpu_synchronize_state(gdbserver_state.g_cpu);
1827    g_byte_array_set_size(gdbserver_state.mem_buf, 0);
1828    len = 0;
1829    for (addr = 0; addr < gdbserver_state.g_cpu->gdb_num_g_regs; addr++) {
1830        len += gdb_read_register(gdbserver_state.g_cpu,
1831                                 gdbserver_state.mem_buf,
1832                                 addr);
1833    }
1834    g_assert(len == gdbserver_state.mem_buf->len);
1835
1836    memtohex(gdbserver_state.str_buf, gdbserver_state.mem_buf->data, len);
1837    put_strbuf();
1838}
1839
1840static void handle_file_io(GdbCmdContext *gdb_ctx, void *user_ctx)
1841{
1842    if (gdb_ctx->num_params >= 1 && gdbserver_state.current_syscall_cb) {
1843        target_ulong ret, err;
1844
1845        ret = (target_ulong)gdb_ctx->params[0].val_ull;
1846        if (gdb_ctx->num_params >= 2) {
1847            err = (target_ulong)gdb_ctx->params[1].val_ull;
1848        } else {
1849            err = 0;
1850        }
1851        gdbserver_state.current_syscall_cb(gdbserver_state.c_cpu, ret, err);
1852        gdbserver_state.current_syscall_cb = NULL;
1853    }
1854
1855    if (gdb_ctx->num_params >= 3 && gdb_ctx->params[2].opcode == (uint8_t)'C') {
1856        put_packet("T02");
1857        return;
1858    }
1859
1860    gdb_continue();
1861}
1862
1863static void handle_step(GdbCmdContext *gdb_ctx, void *user_ctx)
1864{
1865    if (gdb_ctx->num_params) {
1866        gdb_set_cpu_pc((target_ulong)gdb_ctx->params[0].val_ull);
1867    }
1868
1869    cpu_single_step(gdbserver_state.c_cpu, sstep_flags);
1870    gdb_continue();
1871}
1872
1873static void handle_v_cont_query(GdbCmdContext *gdb_ctx, void *user_ctx)
1874{
1875    put_packet("vCont;c;C;s;S");
1876}
1877
1878static void handle_v_cont(GdbCmdContext *gdb_ctx, void *user_ctx)
1879{
1880    int res;
1881
1882    if (!gdb_ctx->num_params) {
1883        return;
1884    }
1885
1886    res = gdb_handle_vcont(gdb_ctx->params[0].data);
1887    if ((res == -EINVAL) || (res == -ERANGE)) {
1888        put_packet("E22");
1889    } else if (res) {
1890        put_packet("");
1891    }
1892}
1893
1894static void handle_v_attach(GdbCmdContext *gdb_ctx, void *user_ctx)
1895{
1896    GDBProcess *process;
1897    CPUState *cpu;
1898
1899    g_string_assign(gdbserver_state.str_buf, "E22");
1900    if (!gdb_ctx->num_params) {
1901        goto cleanup;
1902    }
1903
1904    process = gdb_get_process(gdb_ctx->params[0].val_ul);
1905    if (!process) {
1906        goto cleanup;
1907    }
1908
1909    cpu = get_first_cpu_in_process(process);
1910    if (!cpu) {
1911        goto cleanup;
1912    }
1913
1914    process->attached = true;
1915    gdbserver_state.g_cpu = cpu;
1916    gdbserver_state.c_cpu = cpu;
1917
1918    g_string_printf(gdbserver_state.str_buf, "T%02xthread:", GDB_SIGNAL_TRAP);
1919    gdb_append_thread_id(cpu, gdbserver_state.str_buf);
1920    g_string_append_c(gdbserver_state.str_buf, ';');
1921cleanup:
1922    put_strbuf();
1923}
1924
1925static void handle_v_kill(GdbCmdContext *gdb_ctx, void *user_ctx)
1926{
1927    /* Kill the target */
1928    put_packet("OK");
1929    error_report("QEMU: Terminated via GDBstub");
1930    exit(0);
1931}
1932
1933static GdbCmdParseEntry gdb_v_commands_table[] = {
1934    /* Order is important if has same prefix */
1935    {
1936        .handler = handle_v_cont_query,
1937        .cmd = "Cont?",
1938        .cmd_startswith = 1
1939    },
1940    {
1941        .handler = handle_v_cont,
1942        .cmd = "Cont",
1943        .cmd_startswith = 1,
1944        .schema = "s0"
1945    },
1946    {
1947        .handler = handle_v_attach,
1948        .cmd = "Attach;",
1949        .cmd_startswith = 1,
1950        .schema = "l0"
1951    },
1952    {
1953        .handler = handle_v_kill,
1954        .cmd = "Kill;",
1955        .cmd_startswith = 1
1956    },
1957};
1958
1959static void handle_v_commands(GdbCmdContext *gdb_ctx, void *user_ctx)
1960{
1961    if (!gdb_ctx->num_params) {
1962        return;
1963    }
1964
1965    if (process_string_cmd(NULL, gdb_ctx->params[0].data,
1966                           gdb_v_commands_table,
1967                           ARRAY_SIZE(gdb_v_commands_table))) {
1968        put_packet("");
1969    }
1970}
1971
1972static void handle_query_qemu_sstepbits(GdbCmdContext *gdb_ctx, void *user_ctx)
1973{
1974    g_string_printf(gdbserver_state.str_buf, "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",
1975                    SSTEP_ENABLE, SSTEP_NOIRQ, SSTEP_NOTIMER);
1976    put_strbuf();
1977}
1978
1979static void handle_set_qemu_sstep(GdbCmdContext *gdb_ctx, void *user_ctx)
1980{
1981    if (!gdb_ctx->num_params) {
1982        return;
1983    }
1984
1985    sstep_flags = gdb_ctx->params[0].val_ul;
1986    put_packet("OK");
1987}
1988
1989static void handle_query_qemu_sstep(GdbCmdContext *gdb_ctx, void *user_ctx)
1990{
1991    g_string_printf(gdbserver_state.str_buf, "0x%x", sstep_flags);
1992    put_strbuf();
1993}
1994
1995static void handle_query_curr_tid(GdbCmdContext *gdb_ctx, void *user_ctx)
1996{
1997    CPUState *cpu;
1998    GDBProcess *process;
1999
2000    /*
2001     * "Current thread" remains vague in the spec, so always return
2002     * the first thread of the current process (gdb returns the
2003     * first thread).
2004     */
2005    process = gdb_get_cpu_process(gdbserver_state.g_cpu);
2006    cpu = get_first_cpu_in_process(process);
2007    g_string_assign(gdbserver_state.str_buf, "QC");
2008    gdb_append_thread_id(cpu, gdbserver_state.str_buf);
2009    put_strbuf();
2010}
2011
2012static void handle_query_threads(GdbCmdContext *gdb_ctx, void *user_ctx)
2013{
2014    if (!gdbserver_state.query_cpu) {
2015        put_packet("l");
2016        return;
2017    }
2018
2019    g_string_assign(gdbserver_state.str_buf, "m");
2020    gdb_append_thread_id(gdbserver_state.query_cpu, gdbserver_state.str_buf);
2021    put_strbuf();
2022    gdbserver_state.query_cpu = gdb_next_attached_cpu(gdbserver_state.query_cpu);
2023}
2024
2025static void handle_query_first_threads(GdbCmdContext *gdb_ctx, void *user_ctx)
2026{
2027    gdbserver_state.query_cpu = gdb_first_attached_cpu();
2028    handle_query_threads(gdb_ctx, user_ctx);
2029}
2030
2031static void handle_query_thread_extra(GdbCmdContext *gdb_ctx, void *user_ctx)
2032{
2033    g_autoptr(GString) rs = g_string_new(NULL);
2034    CPUState *cpu;
2035
2036    if (!gdb_ctx->num_params ||
2037        gdb_ctx->params[0].thread_id.kind == GDB_READ_THREAD_ERR) {
2038        put_packet("E22");
2039        return;
2040    }
2041
2042    cpu = gdb_get_cpu(gdb_ctx->params[0].thread_id.pid,
2043                      gdb_ctx->params[0].thread_id.tid);
2044    if (!cpu) {
2045        return;
2046    }
2047
2048    cpu_synchronize_state(cpu);
2049
2050    if (gdbserver_state.multiprocess && (gdbserver_state.process_num > 1)) {
2051        /* Print the CPU model and name in multiprocess mode */
2052        ObjectClass *oc = object_get_class(OBJECT(cpu));
2053        const char *cpu_model = object_class_get_name(oc);
2054        if (cpu->gdb_id) {
2055            g_string_printf(rs, "%s [%s]", cpu->gdb_id,
2056                            cpu->halted ? "halted " : "running");
2057        } else {
2058        const char *cpu_name =
2059            object_get_canonical_path_component(OBJECT(cpu));
2060        g_string_printf(rs, "%s %s [%s]", cpu_model, cpu_name,
2061                        cpu->halted ? "halted " : "running");
2062        }
2063    } else {
2064        g_string_printf(rs, "CPU#%d [%s]", cpu->cpu_index,
2065                        cpu->halted ? "halted " : "running");
2066    }
2067    trace_gdbstub_op_extra_info(rs->str);
2068    memtohex(gdbserver_state.str_buf, (uint8_t *)rs->str, rs->len);
2069    put_strbuf();
2070}
2071
2072#ifdef CONFIG_USER_ONLY
2073static void handle_query_offsets(GdbCmdContext *gdb_ctx, void *user_ctx)
2074{
2075    TaskState *ts;
2076
2077    ts = gdbserver_state.c_cpu->opaque;
2078    g_string_printf(gdbserver_state.str_buf,
2079                    "Text=" TARGET_ABI_FMT_lx
2080                    ";Data=" TARGET_ABI_FMT_lx
2081                    ";Bss=" TARGET_ABI_FMT_lx,
2082                    ts->info->code_offset,
2083                    ts->info->data_offset,
2084                    ts->info->data_offset);
2085    put_strbuf();
2086}
2087#else
2088static void handle_query_rcmd(GdbCmdContext *gdb_ctx, void *user_ctx)
2089{
2090    const guint8 zero = 0;
2091    int len;
2092
2093    if (!gdb_ctx->num_params) {
2094        put_packet("E22");
2095        return;
2096    }
2097
2098    len = strlen(gdb_ctx->params[0].data);
2099    if (len % 2) {
2100        put_packet("E01");
2101        return;
2102    }
2103
2104    g_assert(gdbserver_state.mem_buf->len == 0);
2105    len = len / 2;
2106    hextomem(gdbserver_state.mem_buf, gdb_ctx->params[0].data, len);
2107    g_byte_array_append(gdbserver_state.mem_buf, &zero, 1);
2108    qemu_chr_be_write(gdbserver_state.mon_chr, gdbserver_state.mem_buf->data,
2109                      gdbserver_state.mem_buf->len);
2110    put_packet("OK");
2111}
2112#endif
2113
2114static void handle_query_supported(GdbCmdContext *gdb_ctx, void *user_ctx)
2115{
2116    CPUClass *cc;
2117
2118    g_string_printf(gdbserver_state.str_buf, "PacketSize=%x", MAX_PACKET_LENGTH);
2119    cc = CPU_GET_CLASS(first_cpu);
2120    if (cc->gdb_core_xml_file) {
2121        g_string_append(gdbserver_state.str_buf, ";qXfer:features:read+");
2122    }
2123
2124    if (gdb_ctx->num_params &&
2125        strstr(gdb_ctx->params[0].data, "multiprocess+")) {
2126        gdbserver_state.multiprocess = true;
2127    }
2128
2129    g_string_append(gdbserver_state.str_buf, ";vContSupported+;multiprocess+");
2130    g_string_append(gdbserver_state.str_buf, ";qXfer:osdata:read+");
2131    put_strbuf();
2132}
2133
2134static char *gdb_get_process_list(void)
2135{
2136#define MAX_PLIST (8 * 1024)
2137
2138    static const char *header = "<?xml version=\"1.0\"?>\n" \
2139    "<!DOCTYPE target SYSTEM \"osdata.dtd\">\n<osdata type=\"processes\">\n";
2140    unsigned int i;
2141    CPUState *cpu;
2142    char *buf = g_malloc0(MAX_PLIST);
2143
2144    pstrcat(buf, MAX_PLIST, header);
2145    for (i = 0; i < gdbserver_state.process_num - 1; i++) {
2146        char lbuf[128];
2147        unsigned int num_cores = 0;
2148
2149        /* PIDs should start at 1, 0 is reserved by GDB */
2150        snprintf(lbuf, sizeof(lbuf),
2151                       "<item>\n<column name=\"pid\">%u</column>\n"
2152                       "<column name=\"cores\">", i + 1);
2153        pstrcat(buf, MAX_PLIST, lbuf);
2154
2155        cpu = get_first_cpu_in_process(&gdbserver_state.processes[i]);
2156        while (cpu) {
2157            /* cpu_index starts at 0, which is reserved by GDB */
2158            snprintf(lbuf, sizeof(lbuf), "%s%u",
2159                           num_cores ? "," : "", cpu->cpu_index + 1);
2160            pstrcat(buf, MAX_PLIST, lbuf);
2161            cpu = gdb_next_cpu_in_process(cpu);
2162            num_cores++;
2163        }
2164        pstrcat(buf, MAX_PLIST, "</column>\n</item>\n");
2165    }
2166    pstrcat(buf, MAX_PLIST, "</osdata>");
2167
2168    return buf;
2169}
2170
2171static void handle_query_xfer_osdata_read_proc(GdbCmdContext *gdb_ctx,
2172                                               void *user_ctx)
2173{
2174    target_ulong total_len;
2175    size_t addr = gdb_ctx->params[0].val_ul;
2176    size_t len = gdb_ctx->params[1].val_ul;
2177    const char *plist = gdb_get_process_list();
2178
2179    total_len = strlen(plist);
2180
2181    if (addr > total_len) {
2182        put_packet("E00");
2183
2184        g_free((void *) plist);
2185        return;
2186    }
2187
2188    if (len > (MAX_PACKET_LENGTH - 5) / 2) {
2189        len = (MAX_PACKET_LENGTH - 5) / 2;
2190    }
2191    if (len < total_len - addr) {
2192        g_string_assign(gdbserver_state.str_buf, "m");
2193        memtox(gdbserver_state.str_buf, plist + addr, len);
2194    } else {
2195        g_string_assign(gdbserver_state.str_buf, "l");
2196        memtox(gdbserver_state.str_buf, plist + addr, total_len - addr);
2197    }
2198
2199    put_packet_binary(gdbserver_state.str_buf->str,
2200                      gdbserver_state.str_buf->len, true);
2201    g_free((void *) plist);
2202}
2203
2204static void handle_query_xfer_features(GdbCmdContext *gdb_ctx, void *user_ctx)
2205{
2206    GDBProcess *process;
2207    CPUClass *cc;
2208    unsigned long len, total_len, addr;
2209    const char *xml;
2210    const char *p;
2211
2212    if (gdb_ctx->num_params < 3) {
2213        put_packet("E22");
2214        return;
2215    }
2216
2217    process = gdb_get_cpu_process(gdbserver_state.g_cpu);
2218    cc = CPU_GET_CLASS(gdbserver_state.g_cpu);
2219    if (!cc->gdb_core_xml_file) {
2220        put_packet("");
2221        return;
2222    }
2223
2224    gdb_has_xml = true;
2225    p = gdb_ctx->params[0].data;
2226    xml = get_feature_xml(p, &p, process);
2227    if (!xml) {
2228        put_packet("E00");
2229        return;
2230    }
2231
2232    addr = gdb_ctx->params[1].val_ul;
2233    len = gdb_ctx->params[2].val_ul;
2234    total_len = strlen(xml);
2235    if (addr > total_len) {
2236        put_packet("E00");
2237        return;
2238    }
2239
2240    if (len > (MAX_PACKET_LENGTH - 5) / 2) {
2241        len = (MAX_PACKET_LENGTH - 5) / 2;
2242    }
2243
2244    if (len < total_len - addr) {
2245        g_string_assign(gdbserver_state.str_buf, "m");
2246        memtox(gdbserver_state.str_buf, xml + addr, len);
2247    } else {
2248        g_string_assign(gdbserver_state.str_buf, "l");
2249        memtox(gdbserver_state.str_buf, xml + addr, total_len - addr);
2250    }
2251
2252    put_packet_binary(gdbserver_state.str_buf->str,
2253                      gdbserver_state.str_buf->len, true);
2254}
2255
2256static void handle_query_attached(GdbCmdContext *gdb_ctx, void *user_ctx)
2257{
2258    put_packet(GDB_ATTACHED);
2259}
2260
2261static void handle_query_qemu_supported(GdbCmdContext *gdb_ctx, void *user_ctx)
2262{
2263    g_string_printf(gdbserver_state.str_buf, "sstepbits;sstep");
2264#ifndef CONFIG_USER_ONLY
2265    g_string_append(gdbserver_state.str_buf, ";PhyMemMode");
2266#endif
2267    put_strbuf();
2268}
2269
2270#ifndef CONFIG_USER_ONLY
2271static void handle_query_qemu_phy_mem_mode(GdbCmdContext *gdb_ctx,
2272                                           void *user_ctx)
2273{
2274    g_string_printf(gdbserver_state.str_buf, "%d", phy_memory_mode);
2275    put_strbuf();
2276}
2277
2278static void handle_set_qemu_phy_mem_mode(GdbCmdContext *gdb_ctx, void *user_ctx)
2279{
2280    if (!gdb_ctx->num_params) {
2281        put_packet("E22");
2282        return;
2283    }
2284
2285    if (!gdb_ctx->params[0].val_ul) {
2286        phy_memory_mode = 0;
2287    } else {
2288        phy_memory_mode = 1;
2289    }
2290    put_packet("OK");
2291}
2292#endif
2293
2294static GdbCmdParseEntry gdb_gen_query_set_common_table[] = {
2295    /* Order is important if has same prefix */
2296    {
2297        .handler = handle_query_qemu_sstepbits,
2298        .cmd = "qemu.sstepbits",
2299    },
2300    {
2301        .handler = handle_query_qemu_sstep,
2302        .cmd = "qemu.sstep",
2303    },
2304    {
2305        .handler = handle_set_qemu_sstep,
2306        .cmd = "qemu.sstep=",
2307        .cmd_startswith = 1,
2308        .schema = "l0"
2309    },
2310};
2311
2312static GdbCmdParseEntry gdb_gen_query_table[] = {
2313    {
2314        .handler = handle_query_curr_tid,
2315        .cmd = "C",
2316    },
2317    {
2318        .handler = handle_query_threads,
2319        .cmd = "sThreadInfo",
2320    },
2321    {
2322        .handler = handle_query_first_threads,
2323        .cmd = "fThreadInfo",
2324    },
2325    {
2326        .handler = handle_query_thread_extra,
2327        .cmd = "ThreadExtraInfo,",
2328        .cmd_startswith = 1,
2329        .schema = "t0"
2330    },
2331#ifdef CONFIG_USER_ONLY
2332    {
2333        .handler = handle_query_offsets,
2334        .cmd = "Offsets",
2335    },
2336#else
2337    {
2338        .handler = handle_query_rcmd,
2339        .cmd = "Rcmd,",
2340        .cmd_startswith = 1,
2341        .schema = "s0"
2342    },
2343#endif
2344    {
2345        .handler = handle_query_supported,
2346        .cmd = "Supported:",
2347        .cmd_startswith = 1,
2348        .schema = "s0"
2349    },
2350    {
2351        .handler = handle_query_supported,
2352        .cmd = "Supported",
2353        .schema = "s0"
2354    },
2355    {
2356        .handler = handle_query_xfer_features,
2357        .cmd = "Xfer:features:read:",
2358        .cmd_startswith = 1,
2359        .schema = "s:l,l0"
2360    },
2361    {
2362        .handler = handle_query_xfer_osdata_read_proc,
2363        .cmd = "Xfer:osdata:read:processes:",
2364        .cmd_startswith = 1,
2365        .schema = "l,l0"
2366    },
2367    {
2368        .handler = handle_query_attached,
2369        .cmd = "Attached:",
2370        .cmd_startswith = 1
2371    },
2372    {
2373        .handler = handle_query_attached,
2374        .cmd = "Attached",
2375    },
2376    {
2377        .handler = handle_query_qemu_supported,
2378        .cmd = "qemu.Supported",
2379    },
2380#ifndef CONFIG_USER_ONLY
2381    {
2382        .handler = handle_query_qemu_phy_mem_mode,
2383        .cmd = "qemu.PhyMemMode",
2384    },
2385#endif
2386};
2387
2388static GdbCmdParseEntry gdb_gen_set_table[] = {
2389    /* Order is important if has same prefix */
2390    {
2391        .handler = handle_set_qemu_sstep,
2392        .cmd = "qemu.sstep:",
2393        .cmd_startswith = 1,
2394        .schema = "l0"
2395    },
2396#ifndef CONFIG_USER_ONLY
2397    {
2398        .handler = handle_set_qemu_phy_mem_mode,
2399        .cmd = "qemu.PhyMemMode:",
2400        .cmd_startswith = 1,
2401        .schema = "l0"
2402    },
2403#endif
2404};
2405
2406static void handle_gen_query(GdbCmdContext *gdb_ctx, void *user_ctx)
2407{
2408    if (!gdb_ctx->num_params) {
2409        return;
2410    }
2411
2412    if (!process_string_cmd(NULL, gdb_ctx->params[0].data,
2413                            gdb_gen_query_set_common_table,
2414                            ARRAY_SIZE(gdb_gen_query_set_common_table))) {
2415        return;
2416    }
2417
2418    if (process_string_cmd(NULL, gdb_ctx->params[0].data,
2419                           gdb_gen_query_table,
2420                           ARRAY_SIZE(gdb_gen_query_table))) {
2421        put_packet("");
2422    }
2423}
2424
2425static void handle_gen_set(GdbCmdContext *gdb_ctx, void *user_ctx)
2426{
2427    if (!gdb_ctx->num_params) {
2428        return;
2429    }
2430
2431    if (!process_string_cmd(NULL, gdb_ctx->params[0].data,
2432                            gdb_gen_query_set_common_table,
2433                            ARRAY_SIZE(gdb_gen_query_set_common_table))) {
2434        return;
2435    }
2436
2437    if (process_string_cmd(NULL, gdb_ctx->params[0].data,
2438                           gdb_gen_set_table,
2439                           ARRAY_SIZE(gdb_gen_set_table))) {
2440        put_packet("");
2441    }
2442}
2443
2444static void handle_target_halt(GdbCmdContext *gdb_ctx, void *user_ctx)
2445{
2446    g_string_printf(gdbserver_state.str_buf, "T%02xthread:", GDB_SIGNAL_TRAP);
2447    gdb_append_thread_id(gdbserver_state.c_cpu, gdbserver_state.str_buf);
2448    g_string_append_c(gdbserver_state.str_buf, ';');
2449    put_strbuf();
2450    /*
2451     * Remove all the breakpoints when this query is issued,
2452     * because gdb is doing an initial connect and the state
2453     * should be cleaned up.
2454     */
2455    gdb_breakpoint_remove_all();
2456}
2457
2458static int gdb_handle_packet(const char *line_buf)
2459{
2460    const GdbCmdParseEntry *cmd_parser = NULL;
2461
2462    trace_gdbstub_io_command(line_buf);
2463
2464    switch (line_buf[0]) {
2465    case '!':
2466        put_packet("OK");
2467        break;
2468    case '?':
2469        {
2470            static const GdbCmdParseEntry target_halted_cmd_desc = {
2471                .handler = handle_target_halt,
2472                .cmd = "?",
2473                .cmd_startswith = 1
2474            };
2475            cmd_parser = &target_halted_cmd_desc;
2476        }
2477        break;
2478    case 'c':
2479        {
2480            static const GdbCmdParseEntry continue_cmd_desc = {
2481                .handler = handle_continue,
2482                .cmd = "c",
2483                .cmd_startswith = 1,
2484                .schema = "L0"
2485            };
2486            cmd_parser = &continue_cmd_desc;
2487        }
2488        break;
2489    case 'C':
2490        {
2491            static const GdbCmdParseEntry cont_with_sig_cmd_desc = {
2492                .handler = handle_cont_with_sig,
2493                .cmd = "C",
2494                .cmd_startswith = 1,
2495                .schema = "l0"
2496            };
2497            cmd_parser = &cont_with_sig_cmd_desc;
2498        }
2499        break;
2500    case 'v':
2501        {
2502            static const GdbCmdParseEntry v_cmd_desc = {
2503                .handler = handle_v_commands,
2504                .cmd = "v",
2505                .cmd_startswith = 1,
2506                .schema = "s0"
2507            };
2508            cmd_parser = &v_cmd_desc;
2509        }
2510        break;
2511    case 'k':
2512        /* Kill the target */
2513        error_report("QEMU: Terminated via GDBstub");
2514        exit(0);
2515    case 'D':
2516        {
2517            static const GdbCmdParseEntry detach_cmd_desc = {
2518                .handler = handle_detach,
2519                .cmd = "D",
2520                .cmd_startswith = 1,
2521                .schema = "?.l0"
2522            };
2523            cmd_parser = &detach_cmd_desc;
2524        }
2525        break;
2526    case 's':
2527        {
2528            static const GdbCmdParseEntry step_cmd_desc = {
2529                .handler = handle_step,
2530                .cmd = "s",
2531                .cmd_startswith = 1,
2532                .schema = "L0"
2533            };
2534            cmd_parser = &step_cmd_desc;
2535        }
2536        break;
2537    case 'F':
2538        {
2539            static const GdbCmdParseEntry file_io_cmd_desc = {
2540                .handler = handle_file_io,
2541                .cmd = "F",
2542                .cmd_startswith = 1,
2543                .schema = "L,L,o0"
2544            };
2545            cmd_parser = &file_io_cmd_desc;
2546        }
2547        break;
2548    case 'g':
2549        {
2550            static const GdbCmdParseEntry read_all_regs_cmd_desc = {
2551                .handler = handle_read_all_regs,
2552                .cmd = "g",
2553                .cmd_startswith = 1
2554            };
2555            cmd_parser = &read_all_regs_cmd_desc;
2556        }
2557        break;
2558    case 'G':
2559        {
2560            static const GdbCmdParseEntry write_all_regs_cmd_desc = {
2561                .handler = handle_write_all_regs,
2562                .cmd = "G",
2563                .cmd_startswith = 1,
2564                .schema = "s0"
2565            };
2566            cmd_parser = &write_all_regs_cmd_desc;
2567        }
2568        break;
2569    case 'm':
2570        {
2571            static const GdbCmdParseEntry read_mem_cmd_desc = {
2572                .handler = handle_read_mem,
2573                .cmd = "m",
2574                .cmd_startswith = 1,
2575                .schema = "L,L0"
2576            };
2577            cmd_parser = &read_mem_cmd_desc;
2578        }
2579        break;
2580    case 'M':
2581        {
2582            static const GdbCmdParseEntry write_mem_cmd_desc = {
2583                .handler = handle_write_mem,
2584                .cmd = "M",
2585                .cmd_startswith = 1,
2586                .schema = "L,L:s0"
2587            };
2588            cmd_parser = &write_mem_cmd_desc;
2589        }
2590        break;
2591    case 'p':
2592        {
2593            static const GdbCmdParseEntry get_reg_cmd_desc = {
2594                .handler = handle_get_reg,
2595                .cmd = "p",
2596                .cmd_startswith = 1,
2597                .schema = "L0"
2598            };
2599            cmd_parser = &get_reg_cmd_desc;
2600        }
2601        break;
2602    case 'P':
2603        {
2604            static const GdbCmdParseEntry set_reg_cmd_desc = {
2605                .handler = handle_set_reg,
2606                .cmd = "P",
2607                .cmd_startswith = 1,
2608                .schema = "L?s0"
2609            };
2610            cmd_parser = &set_reg_cmd_desc;
2611        }
2612        break;
2613    case 'Z':
2614        {
2615            static const GdbCmdParseEntry insert_bp_cmd_desc = {
2616                .handler = handle_insert_bp,
2617                .cmd = "Z",
2618                .cmd_startswith = 1,
2619                .schema = "l?L?L0"
2620            };
2621            cmd_parser = &insert_bp_cmd_desc;
2622        }
2623        break;
2624    case 'z':
2625        {
2626            static const GdbCmdParseEntry remove_bp_cmd_desc = {
2627                .handler = handle_remove_bp,
2628                .cmd = "z",
2629                .cmd_startswith = 1,
2630                .schema = "l?L?L0"
2631            };
2632            cmd_parser = &remove_bp_cmd_desc;
2633        }
2634        break;
2635    case 'H':
2636        {
2637            static const GdbCmdParseEntry set_thread_cmd_desc = {
2638                .handler = handle_set_thread,
2639                .cmd = "H",
2640                .cmd_startswith = 1,
2641                .schema = "o.t0"
2642            };
2643            cmd_parser = &set_thread_cmd_desc;
2644        }
2645        break;
2646    case 'T':
2647        {
2648            static const GdbCmdParseEntry thread_alive_cmd_desc = {
2649                .handler = handle_thread_alive,
2650                .cmd = "T",
2651                .cmd_startswith = 1,
2652                .schema = "t0"
2653            };
2654            cmd_parser = &thread_alive_cmd_desc;
2655        }
2656        break;
2657    case 'q':
2658        {
2659            static const GdbCmdParseEntry gen_query_cmd_desc = {
2660                .handler = handle_gen_query,
2661                .cmd = "q",
2662                .cmd_startswith = 1,
2663                .schema = "s0"
2664            };
2665            cmd_parser = &gen_query_cmd_desc;
2666        }
2667        break;
2668    case 'Q':
2669        {
2670            static const GdbCmdParseEntry gen_set_cmd_desc = {
2671                .handler = handle_gen_set,
2672                .cmd = "Q",
2673                .cmd_startswith = 1,
2674                .schema = "s0"
2675            };
2676            cmd_parser = &gen_set_cmd_desc;
2677        }
2678        break;
2679    default:
2680        /* put empty packet */
2681        put_packet("");
2682        break;
2683    }
2684
2685    if (cmd_parser) {
2686        run_cmd_parser(line_buf, cmd_parser);
2687    }
2688
2689    return RS_IDLE;
2690}
2691
2692void gdb_set_stop_cpu(CPUState *cpu)
2693{
2694    GDBProcess *p = gdb_get_cpu_process(cpu);
2695
2696    if (!p->attached) {
2697        /*
2698         * Having a stop CPU corresponding to a process that is not attached
2699         * confuses GDB. So we ignore the request.
2700         */
2701        return;
2702    }
2703
2704    gdbserver_state.c_cpu = cpu;
2705    gdbserver_state.g_cpu = cpu;
2706}
2707
2708#ifndef CONFIG_USER_ONLY
2709static void gdb_vm_state_change(void *opaque, int running, RunState state)
2710{
2711    CPUState *cpu = gdbserver_state.c_cpu;
2712    g_autoptr(GString) buf = g_string_new(NULL);
2713    g_autoptr(GString) tid = g_string_new(NULL);
2714    const char *type;
2715    int ret;
2716
2717    if (running || gdbserver_state.state == RS_INACTIVE) {
2718        return;
2719    }
2720    /* Is there a GDB syscall waiting to be sent?  */
2721    if (gdbserver_state.current_syscall_cb) {
2722        put_packet(gdbserver_state.syscall_buf);
2723        return;
2724    }
2725
2726    if (cpu == NULL) {
2727        /* No process attached */
2728        return;
2729    }
2730
2731    gdb_append_thread_id(cpu, tid);
2732
2733    switch (state) {
2734    case RUN_STATE_DEBUG:
2735        if (cpu->watchpoint_hit) {
2736            switch (cpu->watchpoint_hit->flags & BP_MEM_ACCESS) {
2737            case BP_MEM_READ:
2738                type = "r";
2739                break;
2740            case BP_MEM_ACCESS:
2741                type = "a";
2742                break;
2743            default:
2744                type = "";
2745                break;
2746            }
2747            trace_gdbstub_hit_watchpoint(type, cpu_gdb_index(cpu),
2748                    (target_ulong)cpu->watchpoint_hit->vaddr);
2749            g_string_printf(buf, "T%02xthread:%s;%swatch:" TARGET_FMT_lx ";",
2750                            GDB_SIGNAL_TRAP, tid->str, type,
2751                            (target_ulong)cpu->watchpoint_hit->vaddr);
2752            cpu->watchpoint_hit = NULL;
2753            goto send_packet;
2754        } else {
2755            trace_gdbstub_hit_break();
2756        }
2757        tb_flush(cpu);
2758        ret = GDB_SIGNAL_TRAP;
2759        break;
2760    case RUN_STATE_PAUSED:
2761        trace_gdbstub_hit_paused();
2762        ret = GDB_SIGNAL_INT;
2763        break;
2764    case RUN_STATE_SHUTDOWN:
2765        trace_gdbstub_hit_shutdown();
2766        ret = GDB_SIGNAL_QUIT;
2767        break;
2768    case RUN_STATE_IO_ERROR:
2769        trace_gdbstub_hit_io_error();
2770        ret = GDB_SIGNAL_IO;
2771        break;
2772    case RUN_STATE_WATCHDOG:
2773        trace_gdbstub_hit_watchdog();
2774        ret = GDB_SIGNAL_ALRM;
2775        break;
2776    case RUN_STATE_INTERNAL_ERROR:
2777        trace_gdbstub_hit_internal_error();
2778        ret = GDB_SIGNAL_ABRT;
2779        break;
2780    case RUN_STATE_SAVE_VM:
2781    case RUN_STATE_RESTORE_VM:
2782        return;
2783    case RUN_STATE_FINISH_MIGRATE:
2784        ret = GDB_SIGNAL_XCPU;
2785        break;
2786    default:
2787        trace_gdbstub_hit_unknown(state);
2788        ret = GDB_SIGNAL_UNKNOWN;
2789        break;
2790    }
2791    gdb_set_stop_cpu(cpu);
2792    g_string_printf(buf, "T%02xthread:%s;", ret, tid->str);
2793
2794send_packet:
2795    put_packet(buf->str);
2796
2797    /* disable single step if it was enabled */
2798    cpu_single_step(cpu, 0);
2799}
2800#endif
2801
2802/* Send a gdb syscall request.
2803   This accepts limited printf-style format specifiers, specifically:
2804    %x  - target_ulong argument printed in hex.
2805    %lx - 64-bit argument printed in hex.
2806    %s  - string pointer (target_ulong) and length (int) pair.  */
2807void gdb_do_syscallv(gdb_syscall_complete_cb cb, const char *fmt, va_list va)
2808{
2809    char *p;
2810    char *p_end;
2811    target_ulong addr;
2812    uint64_t i64;
2813
2814    if (!gdbserver_state.init) {
2815        return;
2816    }
2817
2818    gdbserver_state.current_syscall_cb = cb;
2819#ifndef CONFIG_USER_ONLY
2820    vm_stop(RUN_STATE_DEBUG);
2821#endif
2822    p = &gdbserver_state.syscall_buf[0];
2823    p_end = &gdbserver_state.syscall_buf[sizeof(gdbserver_state.syscall_buf)];
2824    *(p++) = 'F';
2825    while (*fmt) {
2826        if (*fmt == '%') {
2827            fmt++;
2828            switch (*fmt++) {
2829            case 'x':
2830                addr = va_arg(va, target_ulong);
2831                p += snprintf(p, p_end - p, TARGET_FMT_lx, addr);
2832                break;
2833            case 'l':
2834                if (*(fmt++) != 'x')
2835                    goto bad_format;
2836                i64 = va_arg(va, uint64_t);
2837                p += snprintf(p, p_end - p, "%" PRIx64, i64);
2838                break;
2839            case 's':
2840                addr = va_arg(va, target_ulong);
2841                p += snprintf(p, p_end - p, TARGET_FMT_lx "/%x",
2842                              addr, va_arg(va, int));
2843                break;
2844            default:
2845            bad_format:
2846                error_report("gdbstub: Bad syscall format string '%s'",
2847                             fmt - 1);
2848                break;
2849            }
2850        } else {
2851            *(p++) = *(fmt++);
2852        }
2853    }
2854    *p = 0;
2855#ifdef CONFIG_USER_ONLY
2856    put_packet(gdbserver_state.syscall_buf);
2857    /* Return control to gdb for it to process the syscall request.
2858     * Since the protocol requires that gdb hands control back to us
2859     * using a "here are the results" F packet, we don't need to check
2860     * gdb_handlesig's return value (which is the signal to deliver if
2861     * execution was resumed via a continue packet).
2862     */
2863    gdb_handlesig(gdbserver_state.c_cpu, 0);
2864#else
2865    /* In this case wait to send the syscall packet until notification that
2866       the CPU has stopped.  This must be done because if the packet is sent
2867       now the reply from the syscall request could be received while the CPU
2868       is still in the running state, which can cause packets to be dropped
2869       and state transition 'T' packets to be sent while the syscall is still
2870       being processed.  */
2871    qemu_cpu_kick(gdbserver_state.c_cpu);
2872#endif
2873}
2874
2875void gdb_do_syscall(gdb_syscall_complete_cb cb, const char *fmt, ...)
2876{
2877    va_list va;
2878
2879    va_start(va, fmt);
2880    gdb_do_syscallv(cb, fmt, va);
2881    va_end(va);
2882}
2883
2884static void gdb_read_byte(uint8_t ch)
2885{
2886    uint8_t reply;
2887
2888#ifndef CONFIG_USER_ONLY
2889    if (gdbserver_state.last_packet->len) {
2890        /* Waiting for a response to the last packet.  If we see the start
2891           of a new command then abandon the previous response.  */
2892        if (ch == '-') {
2893            trace_gdbstub_err_got_nack();
2894            put_buffer(gdbserver_state.last_packet->data,
2895                       gdbserver_state.last_packet->len);
2896        } else if (ch == '+') {
2897            trace_gdbstub_io_got_ack();
2898        } else {
2899            trace_gdbstub_io_got_unexpected(ch);
2900        }
2901
2902        if (ch == '+' || ch == '$') {
2903            g_byte_array_set_size(gdbserver_state.last_packet, 0);
2904        }
2905        if (ch != '$')
2906            return;
2907    }
2908    if (runstate_is_running()) {
2909        /* when the CPU is running, we cannot do anything except stop
2910           it when receiving a char */
2911        vm_stop(RUN_STATE_PAUSED);
2912    } else
2913#endif
2914    {
2915        switch(gdbserver_state.state) {
2916        case RS_IDLE:
2917            if (ch == '$') {
2918                /* start of command packet */
2919                gdbserver_state.line_buf_index = 0;
2920                gdbserver_state.line_sum = 0;
2921                gdbserver_state.state = RS_GETLINE;
2922            } else {
2923                trace_gdbstub_err_garbage(ch);
2924            }
2925            break;
2926        case RS_GETLINE:
2927            if (ch == '}') {
2928                /* start escape sequence */
2929                gdbserver_state.state = RS_GETLINE_ESC;
2930                gdbserver_state.line_sum += ch;
2931            } else if (ch == '*') {
2932                /* start run length encoding sequence */
2933                gdbserver_state.state = RS_GETLINE_RLE;
2934                gdbserver_state.line_sum += ch;
2935            } else if (ch == '#') {
2936                /* end of command, start of checksum*/
2937                gdbserver_state.state = RS_CHKSUM1;
2938            } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
2939                trace_gdbstub_err_overrun();
2940                gdbserver_state.state = RS_IDLE;
2941            } else {
2942                /* unescaped command character */
2943                gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch;
2944                gdbserver_state.line_sum += ch;
2945            }
2946            break;
2947        case RS_GETLINE_ESC:
2948            if (ch == '#') {
2949                /* unexpected end of command in escape sequence */
2950                gdbserver_state.state = RS_CHKSUM1;
2951            } else if (gdbserver_state.line_buf_index >= sizeof(gdbserver_state.line_buf) - 1) {
2952                /* command buffer overrun */
2953                trace_gdbstub_err_overrun();
2954                gdbserver_state.state = RS_IDLE;
2955            } else {
2956                /* parse escaped character and leave escape state */
2957                gdbserver_state.line_buf[gdbserver_state.line_buf_index++] = ch ^ 0x20;
2958                gdbserver_state.line_sum += ch;
2959                gdbserver_state.state = RS_GETLINE;
2960            }
2961            break;
2962        case RS_GETLINE_RLE:
2963            /*
2964             * Run-length encoding is explained in "Debugging with GDB /
2965             * Appendix E GDB Remote Serial Protocol / Overview".
2966             */
2967            if (ch < ' ' || ch == '#' || ch == '$' || ch > 126) {
2968                /* invalid RLE count encoding */
2969                trace_gdbstub_err_invalid_repeat(ch);
2970                gdbserver_state.state = RS_GETLINE;
2971            } else {
2972                /* decode repeat length */
2973                int repeat = ch - ' ' + 3;
2974                if (gdbserver_state.line_buf_index + repeat >= sizeof(gdbserver_state.line_buf) - 1) {
2975                    /* that many repeats would overrun the command buffer */
2976                    trace_gdbstub_err_overrun();
2977                    gdbserver_state.state = RS_IDLE;
2978                } else if (gdbserver_state.line_buf_index < 1) {
2979                    /* got a repeat but we have nothing to repeat */
2980                    trace_gdbstub_err_invalid_rle();
2981                    gdbserver_state.state = RS_GETLINE;
2982                } else {
2983                    /* repeat the last character */
2984                    memset(gdbserver_state.line_buf + gdbserver_state.line_buf_index,
2985                           gdbserver_state.line_buf[gdbserver_state.line_buf_index - 1], repeat);
2986                    gdbserver_state.line_buf_index += repeat;
2987                    gdbserver_state.line_sum += ch;
2988                    gdbserver_state.state = RS_GETLINE;
2989                }
2990            }
2991            break;
2992        case RS_CHKSUM1:
2993            /* get high hex digit of checksum */
2994            if (!isxdigit(ch)) {
2995                trace_gdbstub_err_checksum_invalid(ch);
2996                gdbserver_state.state = RS_GETLINE;
2997                break;
2998            }
2999            gdbserver_state.line_buf[gdbserver_state.line_buf_index] = '\0';
3000            gdbserver_state.line_csum = fromhex(ch) << 4;
3001            gdbserver_state.state = RS_CHKSUM2;
3002            break;
3003        case RS_CHKSUM2:
3004            /* get low hex digit of checksum */
3005            if (!isxdigit(ch)) {
3006                trace_gdbstub_err_checksum_invalid(ch);
3007                gdbserver_state.state = RS_GETLINE;
3008                break;
3009            }
3010            gdbserver_state.line_csum |= fromhex(ch);
3011
3012            if (gdbserver_state.line_csum != (gdbserver_state.line_sum & 0xff)) {
3013                trace_gdbstub_err_checksum_incorrect(gdbserver_state.line_sum, gdbserver_state.line_csum);
3014                /* send NAK reply */
3015                reply = '-';
3016                put_buffer(&reply, 1);
3017                gdbserver_state.state = RS_IDLE;
3018            } else {
3019                /* send ACK reply */
3020                reply = '+';
3021                put_buffer(&reply, 1);
3022                gdbserver_state.state = gdb_handle_packet(gdbserver_state.line_buf);
3023            }
3024            break;
3025        default:
3026            abort();
3027        }
3028    }
3029}
3030
3031/* Tell the remote gdb that the process has exited.  */
3032void gdb_exit(CPUArchState *env, int code)
3033{
3034  char buf[4];
3035
3036  if (!gdbserver_state.init) {
3037      return;
3038  }
3039#ifdef CONFIG_USER_ONLY
3040  if (gdbserver_state.socket_path) {
3041      unlink(gdbserver_state.socket_path);
3042  }
3043  if (gdbserver_state.fd < 0) {
3044      return;
3045  }
3046#endif
3047
3048  trace_gdbstub_op_exiting((uint8_t)code);
3049
3050  snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);
3051  put_packet(buf);
3052
3053#ifndef CONFIG_USER_ONLY
3054  qemu_chr_fe_deinit(&gdbserver_state.chr, true);
3055#endif
3056}
3057
3058/*
3059 * Create the process that will contain all the "orphan" CPUs (that are not
3060 * part of a CPU cluster). Note that if this process contains no CPUs, it won't
3061 * be attachable and thus will be invisible to the user.
3062 */
3063static void create_default_process(GDBState *s)
3064{
3065    GDBProcess *process;
3066    int max_pid = 0;
3067
3068    if (gdbserver_state.process_num) {
3069        max_pid = s->processes[s->process_num - 1].pid;
3070    }
3071
3072    s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
3073    process = &s->processes[s->process_num - 1];
3074
3075    /* We need an available PID slot for this process */
3076    assert(max_pid < UINT32_MAX);
3077
3078    process->pid = max_pid + 1;
3079    process->attached = false;
3080    process->target_xml[0] = '\0';
3081}
3082
3083#ifdef CONFIG_USER_ONLY
3084int
3085gdb_handlesig(CPUState *cpu, int sig)
3086{
3087    char buf[256];
3088    int n;
3089
3090    if (!gdbserver_state.init || gdbserver_state.fd < 0) {
3091        return sig;
3092    }
3093
3094    /* disable single step if it was enabled */
3095    cpu_single_step(cpu, 0);
3096    tb_flush(cpu);
3097
3098    if (sig != 0) {
3099        snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb(sig));
3100        put_packet(buf);
3101    }
3102    /* put_packet() might have detected that the peer terminated the
3103       connection.  */
3104    if (gdbserver_state.fd < 0) {
3105        return sig;
3106    }
3107
3108    sig = 0;
3109    gdbserver_state.state = RS_IDLE;
3110    gdbserver_state.running_state = 0;
3111    while (gdbserver_state.running_state == 0) {
3112        n = read(gdbserver_state.fd, buf, 256);
3113        if (n > 0) {
3114            int i;
3115
3116            for (i = 0; i < n; i++) {
3117                gdb_read_byte(buf[i]);
3118            }
3119        } else {
3120            /* XXX: Connection closed.  Should probably wait for another
3121               connection before continuing.  */
3122            if (n == 0) {
3123                close(gdbserver_state.fd);
3124            }
3125            gdbserver_state.fd = -1;
3126            return sig;
3127        }
3128    }
3129    sig = gdbserver_state.signal;
3130    gdbserver_state.signal = 0;
3131    return sig;
3132}
3133
3134/* Tell the remote gdb that the process has exited due to SIG.  */
3135void gdb_signalled(CPUArchState *env, int sig)
3136{
3137    char buf[4];
3138
3139    if (!gdbserver_state.init || gdbserver_state.fd < 0) {
3140        return;
3141    }
3142
3143    snprintf(buf, sizeof(buf), "X%02x", target_signal_to_gdb(sig));
3144    put_packet(buf);
3145}
3146
3147static void gdb_accept_init(int fd)
3148{
3149    init_gdbserver_state();
3150    create_default_process(&gdbserver_state);
3151    gdbserver_state.processes[0].attached = true;
3152    gdbserver_state.c_cpu = gdb_first_attached_cpu();
3153    gdbserver_state.g_cpu = gdbserver_state.c_cpu;
3154    gdbserver_state.fd = fd;
3155    gdb_has_xml = false;
3156}
3157
3158static bool gdb_accept_socket(int gdb_fd)
3159{
3160    int fd;
3161
3162    for(;;) {
3163        fd = accept(gdb_fd, NULL, NULL);
3164        if (fd < 0 && errno != EINTR) {
3165            perror("accept socket");
3166            return false;
3167        } else if (fd >= 0) {
3168            qemu_set_cloexec(fd);
3169            break;
3170        }
3171    }
3172
3173    gdb_accept_init(fd);
3174    return true;
3175}
3176
3177static int gdbserver_open_socket(const char *path)
3178{
3179    struct sockaddr_un sockaddr;
3180    int fd, ret;
3181
3182    fd = socket(AF_UNIX, SOCK_STREAM, 0);
3183    if (fd < 0) {
3184        perror("create socket");
3185        return -1;
3186    }
3187
3188    sockaddr.sun_family = AF_UNIX;
3189    pstrcpy(sockaddr.sun_path, sizeof(sockaddr.sun_path) - 1, path);
3190    ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
3191    if (ret < 0) {
3192        perror("bind socket");
3193        close(fd);
3194        return -1;
3195    }
3196    ret = listen(fd, 1);
3197    if (ret < 0) {
3198        perror("listen socket");
3199        close(fd);
3200        return -1;
3201    }
3202
3203    return fd;
3204}
3205
3206static bool gdb_accept_tcp(int gdb_fd)
3207{
3208    struct sockaddr_in sockaddr;
3209    socklen_t len;
3210    int fd;
3211
3212    for(;;) {
3213        len = sizeof(sockaddr);
3214        fd = accept(gdb_fd, (struct sockaddr *)&sockaddr, &len);
3215        if (fd < 0 && errno != EINTR) {
3216            perror("accept");
3217            return false;
3218        } else if (fd >= 0) {
3219            qemu_set_cloexec(fd);
3220            break;
3221        }
3222    }
3223
3224    /* set short latency */
3225    if (socket_set_nodelay(fd)) {
3226        perror("setsockopt");
3227        close(fd);
3228        return false;
3229    }
3230
3231    gdb_accept_init(fd);
3232    return true;
3233}
3234
3235static int gdbserver_open_port(int port)
3236{
3237    struct sockaddr_in sockaddr;
3238    int fd, ret;
3239
3240    fd = socket(PF_INET, SOCK_STREAM, 0);
3241    if (fd < 0) {
3242        perror("socket");
3243        return -1;
3244    }
3245    qemu_set_cloexec(fd);
3246
3247    socket_set_fast_reuse(fd);
3248
3249    sockaddr.sin_family = AF_INET;
3250    sockaddr.sin_port = htons(port);
3251    sockaddr.sin_addr.s_addr = 0;
3252    ret = bind(fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
3253    if (ret < 0) {
3254        perror("bind");
3255        close(fd);
3256        return -1;
3257    }
3258    ret = listen(fd, 1);
3259    if (ret < 0) {
3260        perror("listen");
3261        close(fd);
3262        return -1;
3263    }
3264
3265    return fd;
3266}
3267
3268int gdbserver_start(const char *port_or_path)
3269{
3270    int port = g_ascii_strtoull(port_or_path, NULL, 10);
3271    int gdb_fd;
3272
3273    if (port > 0) {
3274        gdb_fd = gdbserver_open_port(port);
3275    } else {
3276        gdb_fd = gdbserver_open_socket(port_or_path);
3277    }
3278
3279    if (gdb_fd < 0) {
3280        return -1;
3281    }
3282
3283    if (port > 0 && gdb_accept_tcp(gdb_fd)) {
3284        return 0;
3285    } else if (gdb_accept_socket(gdb_fd)) {
3286        gdbserver_state.socket_path = g_strdup(port_or_path);
3287        return 0;
3288    }
3289
3290    /* gone wrong */
3291    close(gdb_fd);
3292    return -1;
3293}
3294
3295/* Disable gdb stub for child processes.  */
3296void gdbserver_fork(CPUState *cpu)
3297{
3298    if (!gdbserver_state.init || gdbserver_state.fd < 0) {
3299        return;
3300    }
3301    close(gdbserver_state.fd);
3302    gdbserver_state.fd = -1;
3303    cpu_breakpoint_remove_all(cpu, BP_GDB);
3304    cpu_watchpoint_remove_all(cpu, BP_GDB);
3305}
3306#else
3307static int gdb_chr_can_receive(void *opaque)
3308{
3309  /* We can handle an arbitrarily large amount of data.
3310   Pick the maximum packet size, which is as good as anything.  */
3311  return MAX_PACKET_LENGTH;
3312}
3313
3314static void gdb_chr_receive(void *opaque, const uint8_t *buf, int size)
3315{
3316    int i;
3317
3318    for (i = 0; i < size; i++) {
3319        gdb_read_byte(buf[i]);
3320    }
3321}
3322
3323static void gdb_chr_event(void *opaque, QEMUChrEvent event)
3324{
3325    int i;
3326    GDBState *s = (GDBState *) opaque;
3327
3328    switch (event) {
3329    case CHR_EVENT_OPENED:
3330        /* Start with first process attached, others detached */
3331        for (i = 0; i < s->process_num; i++) {
3332            s->processes[i].attached = !i;
3333        }
3334
3335        s->c_cpu = gdb_first_attached_cpu();
3336        s->g_cpu = s->c_cpu;
3337
3338        vm_stop(RUN_STATE_PAUSED);
3339        gdb_has_xml = false;
3340        break;
3341    default:
3342        break;
3343    }
3344}
3345
3346static int gdb_monitor_write(Chardev *chr, const uint8_t *buf, int len)
3347{
3348    g_autoptr(GString) hex_buf = g_string_new("O");
3349    memtohex(hex_buf, buf, len);
3350    put_packet(hex_buf->str);
3351    return len;
3352}
3353
3354#ifndef _WIN32
3355static void gdb_sigterm_handler(int signal)
3356{
3357    if (runstate_is_running()) {
3358        vm_stop(RUN_STATE_PAUSED);
3359    }
3360}
3361#endif
3362
3363static void gdb_monitor_open(Chardev *chr, ChardevBackend *backend,
3364                             bool *be_opened, Error **errp)
3365{
3366    *be_opened = false;
3367}
3368
3369static void char_gdb_class_init(ObjectClass *oc, void *data)
3370{
3371    ChardevClass *cc = CHARDEV_CLASS(oc);
3372
3373    cc->internal = true;
3374    cc->open = gdb_monitor_open;
3375    cc->chr_write = gdb_monitor_write;
3376}
3377
3378#define TYPE_CHARDEV_GDB "chardev-gdb"
3379
3380static const TypeInfo char_gdb_type_info = {
3381    .name = TYPE_CHARDEV_GDB,
3382    .parent = TYPE_CHARDEV,
3383    .class_init = char_gdb_class_init,
3384};
3385
3386static int find_cpu_clusters(Object *child, void *opaque)
3387{
3388    if (object_dynamic_cast(child, TYPE_CPU_CLUSTER)) {
3389        GDBState *s = (GDBState *) opaque;
3390        CPUClusterState *cluster = CPU_CLUSTER(child);
3391        GDBProcess *process;
3392
3393        s->processes = g_renew(GDBProcess, s->processes, ++s->process_num);
3394
3395        process = &s->processes[s->process_num - 1];
3396
3397        /*
3398         * GDB process IDs -1 and 0 are reserved. To avoid subtle errors at
3399         * runtime, we enforce here that the machine does not use a cluster ID
3400         * that would lead to PID 0.
3401         */
3402        assert(cluster->cluster_id != UINT32_MAX);
3403        process->pid = cluster->cluster_id + 1;
3404        process->attached = false;
3405        process->target_xml[0] = '\0';
3406
3407        return 0;
3408    }
3409
3410    return object_child_foreach(child, find_cpu_clusters, opaque);
3411}
3412
3413static int pid_order(const void *a, const void *b)
3414{
3415    GDBProcess *pa = (GDBProcess *) a;
3416    GDBProcess *pb = (GDBProcess *) b;
3417
3418    if (pa->pid < pb->pid) {
3419        return -1;
3420    } else if (pa->pid > pb->pid) {
3421        return 1;
3422    } else {
3423        return 0;
3424    }
3425}
3426
3427static void create_processes(GDBState *s)
3428{
3429    object_child_foreach(object_get_root(), find_cpu_clusters, s);
3430
3431    if (gdbserver_state.processes) {
3432        /* Sort by PID */
3433        qsort(gdbserver_state.processes, gdbserver_state.process_num, sizeof(gdbserver_state.processes[0]), pid_order);
3434    }
3435
3436    create_default_process(s);
3437}
3438
3439int gdbserver_start(const char *device)
3440{
3441    trace_gdbstub_op_start(device);
3442
3443    char gdbstub_device_name[128];
3444    Chardev *chr = NULL;
3445    Chardev *mon_chr;
3446
3447    if (!first_cpu) {
3448        error_report("gdbstub: meaningless to attach gdb to a "
3449                     "machine without any CPU.");
3450        return -1;
3451    }
3452
3453    if (!device)
3454        return -1;
3455    if (strcmp(device, "none") != 0) {
3456        if (strstart(device, "tcp:", NULL)) {
3457            /* enforce required TCP attributes */
3458            snprintf(gdbstub_device_name, sizeof(gdbstub_device_name),
3459                     "%s,nowait,nodelay,server", device);
3460            device = gdbstub_device_name;
3461        }
3462#ifndef _WIN32
3463        else if (strcmp(device, "stdio") == 0) {
3464            struct sigaction act;
3465
3466            memset(&act, 0, sizeof(act));
3467            act.sa_handler = gdb_sigterm_handler;
3468            sigaction(SIGINT, &act, NULL);
3469        }
3470#endif
3471        /*
3472         * FIXME: it's a bit weird to allow using a mux chardev here
3473         * and implicitly setup a monitor. We may want to break this.
3474         */
3475        chr = qemu_chr_new_noreplay("gdb", device, true, NULL);
3476        if (!chr)
3477            return -1;
3478    }
3479
3480    if (!gdbserver_state.init) {
3481        init_gdbserver_state();
3482
3483        qemu_add_vm_change_state_handler(gdb_vm_state_change, NULL);
3484
3485        /* Initialize a monitor terminal for gdb */
3486        mon_chr = qemu_chardev_new(NULL, TYPE_CHARDEV_GDB,
3487                                   NULL, NULL, &error_abort);
3488        monitor_init_hmp(mon_chr, false, &error_abort);
3489    } else {
3490        qemu_chr_fe_deinit(&gdbserver_state.chr, true);
3491        mon_chr = gdbserver_state.mon_chr;
3492        reset_gdbserver_state();
3493    }
3494
3495    create_processes(&gdbserver_state);
3496
3497    if (chr) {
3498        qemu_chr_fe_init(&gdbserver_state.chr, chr, &error_abort);
3499        qemu_chr_fe_set_handlers(&gdbserver_state.chr, gdb_chr_can_receive,
3500                                 gdb_chr_receive, gdb_chr_event,
3501                                 NULL, &gdbserver_state, NULL, true);
3502    }
3503    gdbserver_state.state = chr ? RS_IDLE : RS_INACTIVE;
3504    gdbserver_state.mon_chr = mon_chr;
3505    gdbserver_state.current_syscall_cb = NULL;
3506
3507    return 0;
3508}
3509
3510void gdbserver_cleanup(void)
3511{
3512    if (gdbserver_state.init) {
3513        put_packet("W00");
3514    }
3515}
3516
3517static void register_types(void)
3518{
3519    type_register_static(&char_gdb_type_info);
3520}
3521
3522type_init(register_types);
3523#endif
3524