qemu/tests/libqtest.c
<<
>>
Prefs
   1/*
   2 * QTest
   3 *
   4 * Copyright IBM, Corp. 2012
   5 * Copyright Red Hat, Inc. 2012
   6 * Copyright SUSE LINUX Products GmbH 2013
   7 *
   8 * Authors:
   9 *  Anthony Liguori   <aliguori@us.ibm.com>
  10 *  Paolo Bonzini     <pbonzini@redhat.com>
  11 *  Andreas Färber    <afaerber@suse.de>
  12 *
  13 * This work is licensed under the terms of the GNU GPL, version 2 or later.
  14 * See the COPYING file in the top-level directory.
  15 *
  16 */
  17#include "qemu/osdep.h"
  18#include "libqtest.h"
  19
  20#include <sys/socket.h>
  21#include <sys/wait.h>
  22#include <sys/un.h>
  23
  24#include "qapi/error.h"
  25#include "qapi/qmp/json-parser.h"
  26#include "qapi/qmp/json-streamer.h"
  27#include "qapi/qmp/qjson.h"
  28
  29#define MAX_IRQ 256
  30#define SOCKET_TIMEOUT 50
  31
  32QTestState *global_qtest;
  33
  34struct QTestState
  35{
  36    int fd;
  37    int qmp_fd;
  38    bool irq_level[MAX_IRQ];
  39    GString *rx;
  40    pid_t qemu_pid;  /* our child QEMU process */
  41    bool big_endian;
  42};
  43
  44static GHookList abrt_hooks;
  45static GList *qtest_instances;
  46static struct sigaction sigact_old;
  47
  48#define g_assert_no_errno(ret) do { \
  49    g_assert_cmpint(ret, !=, -1); \
  50} while (0)
  51
  52static int qtest_query_target_endianness(QTestState *s);
  53
  54static int init_socket(const char *socket_path)
  55{
  56    struct sockaddr_un addr;
  57    int sock;
  58    int ret;
  59
  60    sock = socket(PF_UNIX, SOCK_STREAM, 0);
  61    g_assert_no_errno(sock);
  62
  63    addr.sun_family = AF_UNIX;
  64    snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
  65    qemu_set_cloexec(sock);
  66
  67    do {
  68        ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
  69    } while (ret == -1 && errno == EINTR);
  70    g_assert_no_errno(ret);
  71    ret = listen(sock, 1);
  72    g_assert_no_errno(ret);
  73
  74    return sock;
  75}
  76
  77static int socket_accept(int sock)
  78{
  79    struct sockaddr_un addr;
  80    socklen_t addrlen;
  81    int ret;
  82    struct timeval timeout = { .tv_sec = SOCKET_TIMEOUT,
  83                               .tv_usec = 0 };
  84
  85    setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *)&timeout,
  86               sizeof(timeout));
  87
  88    do {
  89        addrlen = sizeof(addr);
  90        ret = accept(sock, (struct sockaddr *)&addr, &addrlen);
  91    } while (ret == -1 && errno == EINTR);
  92    if (ret == -1) {
  93        fprintf(stderr, "%s failed: %s\n", __func__, strerror(errno));
  94    }
  95    close(sock);
  96
  97    return ret;
  98}
  99
 100static void kill_qemu(QTestState *s)
 101{
 102    if (s->qemu_pid != -1) {
 103        kill(s->qemu_pid, SIGTERM);
 104        waitpid(s->qemu_pid, NULL, 0);
 105    }
 106}
 107
 108static void kill_qemu_hook_func(void *s)
 109{
 110    kill_qemu(s);
 111}
 112
 113static void sigabrt_handler(int signo)
 114{
 115    g_hook_list_invoke(&abrt_hooks, FALSE);
 116}
 117
 118static void setup_sigabrt_handler(void)
 119{
 120    struct sigaction sigact;
 121
 122    /* Catch SIGABRT to clean up on g_assert() failure */
 123    sigact = (struct sigaction){
 124        .sa_handler = sigabrt_handler,
 125        .sa_flags = SA_RESETHAND,
 126    };
 127    sigemptyset(&sigact.sa_mask);
 128    sigaction(SIGABRT, &sigact, &sigact_old);
 129}
 130
 131static void cleanup_sigabrt_handler(void)
 132{
 133    sigaction(SIGABRT, &sigact_old, NULL);
 134}
 135
 136void qtest_add_abrt_handler(GHookFunc fn, const void *data)
 137{
 138    GHook *hook;
 139
 140    /* Only install SIGABRT handler once */
 141    if (!abrt_hooks.is_setup) {
 142        g_hook_list_init(&abrt_hooks, sizeof(GHook));
 143    }
 144    setup_sigabrt_handler();
 145
 146    hook = g_hook_alloc(&abrt_hooks);
 147    hook->func = fn;
 148    hook->data = (void *)data;
 149
 150    g_hook_prepend(&abrt_hooks, hook);
 151}
 152
 153QTestState *qtest_init_without_qmp_handshake(const char *extra_args)
 154{
 155    QTestState *s;
 156    int sock, qmpsock, i;
 157    gchar *socket_path;
 158    gchar *qmp_socket_path;
 159    gchar *command;
 160    const char *qemu_binary;
 161
 162    qemu_binary = getenv("QTEST_QEMU_BINARY");
 163    if (!qemu_binary) {
 164        fprintf(stderr, "Environment variable QTEST_QEMU_BINARY required\n");
 165        exit(1);
 166    }
 167
 168    s = g_malloc(sizeof(*s));
 169
 170    socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
 171    qmp_socket_path = g_strdup_printf("/tmp/qtest-%d.qmp", getpid());
 172
 173    /* It's possible that if an earlier test run crashed it might
 174     * have left a stale unix socket lying around. Delete any
 175     * stale old socket to avoid spurious test failures with
 176     * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1)
 177     */
 178    unlink(socket_path);
 179    unlink(qmp_socket_path);
 180
 181    sock = init_socket(socket_path);
 182    qmpsock = init_socket(qmp_socket_path);
 183
 184    qtest_add_abrt_handler(kill_qemu_hook_func, s);
 185
 186    s->qemu_pid = fork();
 187    if (s->qemu_pid == 0) {
 188        setenv("QEMU_AUDIO_DRV", "none", true);
 189        command = g_strdup_printf("exec %s "
 190                                  "-qtest unix:%s,nowait "
 191                                  "-qtest-log %s "
 192                                  "-qmp unix:%s,nowait "
 193                                  "-machine accel=qtest "
 194                                  "-display none "
 195                                  "%s", qemu_binary, socket_path,
 196                                  getenv("QTEST_LOG") ? "/dev/fd/2" : "/dev/null",
 197                                  qmp_socket_path,
 198                                  extra_args ?: "");
 199        execlp("/bin/sh", "sh", "-c", command, NULL);
 200        exit(1);
 201    }
 202
 203    s->fd = socket_accept(sock);
 204    if (s->fd >= 0) {
 205        s->qmp_fd = socket_accept(qmpsock);
 206    }
 207    unlink(socket_path);
 208    unlink(qmp_socket_path);
 209    g_free(socket_path);
 210    g_free(qmp_socket_path);
 211
 212    g_assert(s->fd >= 0 && s->qmp_fd >= 0);
 213
 214    s->rx = g_string_new("");
 215    for (i = 0; i < MAX_IRQ; i++) {
 216        s->irq_level[i] = false;
 217    }
 218
 219    if (getenv("QTEST_STOP")) {
 220        kill(s->qemu_pid, SIGSTOP);
 221    }
 222
 223    /* ask endianness of the target */
 224
 225    s->big_endian = qtest_query_target_endianness(s);
 226
 227    return s;
 228}
 229
 230QTestState *qtest_init(const char *extra_args)
 231{
 232    QTestState *s = qtest_init_without_qmp_handshake(extra_args);
 233
 234    /* Read the QMP greeting and then do the handshake */
 235    qtest_qmp_discard_response(s, "");
 236    qtest_qmp_discard_response(s, "{ 'execute': 'qmp_capabilities' }");
 237
 238    return s;
 239}
 240
 241void qtest_quit(QTestState *s)
 242{
 243    qtest_instances = g_list_remove(qtest_instances, s);
 244    g_hook_destroy_link(&abrt_hooks, g_hook_find_data(&abrt_hooks, TRUE, s));
 245
 246    /* Uninstall SIGABRT handler on last instance */
 247    if (!qtest_instances) {
 248        cleanup_sigabrt_handler();
 249    }
 250
 251    kill_qemu(s);
 252    close(s->fd);
 253    close(s->qmp_fd);
 254    g_string_free(s->rx, true);
 255    g_free(s);
 256}
 257
 258static void socket_send(int fd, const char *buf, size_t size)
 259{
 260    size_t offset;
 261
 262    offset = 0;
 263    while (offset < size) {
 264        ssize_t len;
 265
 266        len = write(fd, buf + offset, size - offset);
 267        if (len == -1 && errno == EINTR) {
 268            continue;
 269        }
 270
 271        g_assert_no_errno(len);
 272        g_assert_cmpint(len, >, 0);
 273
 274        offset += len;
 275    }
 276}
 277
 278static void socket_sendf(int fd, const char *fmt, va_list ap)
 279{
 280    gchar *str = g_strdup_vprintf(fmt, ap);
 281    size_t size = strlen(str);
 282
 283    socket_send(fd, str, size);
 284    g_free(str);
 285}
 286
 287static void GCC_FMT_ATTR(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...)
 288{
 289    va_list ap;
 290
 291    va_start(ap, fmt);
 292    socket_sendf(s->fd, fmt, ap);
 293    va_end(ap);
 294}
 295
 296static GString *qtest_recv_line(QTestState *s)
 297{
 298    GString *line;
 299    size_t offset;
 300    char *eol;
 301
 302    while ((eol = strchr(s->rx->str, '\n')) == NULL) {
 303        ssize_t len;
 304        char buffer[1024];
 305
 306        len = read(s->fd, buffer, sizeof(buffer));
 307        if (len == -1 && errno == EINTR) {
 308            continue;
 309        }
 310
 311        if (len == -1 || len == 0) {
 312            fprintf(stderr, "Broken pipe\n");
 313            exit(1);
 314        }
 315
 316        g_string_append_len(s->rx, buffer, len);
 317    }
 318
 319    offset = eol - s->rx->str;
 320    line = g_string_new_len(s->rx->str, offset);
 321    g_string_erase(s->rx, 0, offset + 1);
 322
 323    return line;
 324}
 325
 326static gchar **qtest_rsp(QTestState *s, int expected_args)
 327{
 328    GString *line;
 329    gchar **words;
 330    int i;
 331
 332redo:
 333    line = qtest_recv_line(s);
 334    words = g_strsplit(line->str, " ", 0);
 335    g_string_free(line, TRUE);
 336
 337    if (strcmp(words[0], "IRQ") == 0) {
 338        int irq;
 339
 340        g_assert(words[1] != NULL);
 341        g_assert(words[2] != NULL);
 342
 343        irq = strtoul(words[2], NULL, 0);
 344        g_assert_cmpint(irq, >=, 0);
 345        g_assert_cmpint(irq, <, MAX_IRQ);
 346
 347        if (strcmp(words[1], "raise") == 0) {
 348            s->irq_level[irq] = true;
 349        } else {
 350            s->irq_level[irq] = false;
 351        }
 352
 353        g_strfreev(words);
 354        goto redo;
 355    }
 356
 357    g_assert(words[0] != NULL);
 358    g_assert_cmpstr(words[0], ==, "OK");
 359
 360    if (expected_args) {
 361        for (i = 0; i < expected_args; i++) {
 362            g_assert(words[i] != NULL);
 363        }
 364    } else {
 365        g_strfreev(words);
 366    }
 367
 368    return words;
 369}
 370
 371static int qtest_query_target_endianness(QTestState *s)
 372{
 373    gchar **args;
 374    int big_endian;
 375
 376    qtest_sendf(s, "endianness\n");
 377    args = qtest_rsp(s, 1);
 378    g_assert(strcmp(args[1], "big") == 0 || strcmp(args[1], "little") == 0);
 379    big_endian = strcmp(args[1], "big") == 0;
 380    g_strfreev(args);
 381
 382    return big_endian;
 383}
 384
 385typedef struct {
 386    JSONMessageParser parser;
 387    QDict *response;
 388} QMPResponseParser;
 389
 390static void qmp_response(JSONMessageParser *parser, GQueue *tokens)
 391{
 392    QMPResponseParser *qmp = container_of(parser, QMPResponseParser, parser);
 393    QObject *obj;
 394
 395    obj = json_parser_parse(tokens, NULL);
 396    if (!obj) {
 397        fprintf(stderr, "QMP JSON response parsing failed\n");
 398        exit(1);
 399    }
 400
 401    g_assert(!qmp->response);
 402    qmp->response = qobject_to_qdict(obj);
 403    g_assert(qmp->response);
 404}
 405
 406QDict *qmp_fd_receive(int fd)
 407{
 408    QMPResponseParser qmp;
 409    bool log = getenv("QTEST_LOG") != NULL;
 410
 411    qmp.response = NULL;
 412    json_message_parser_init(&qmp.parser, qmp_response);
 413    while (!qmp.response) {
 414        ssize_t len;
 415        char c;
 416
 417        len = read(fd, &c, 1);
 418        if (len == -1 && errno == EINTR) {
 419            continue;
 420        }
 421
 422        if (len == -1 || len == 0) {
 423            fprintf(stderr, "Broken pipe\n");
 424            exit(1);
 425        }
 426
 427        if (log) {
 428            len = write(2, &c, 1);
 429        }
 430        json_message_parser_feed(&qmp.parser, &c, 1);
 431    }
 432    json_message_parser_destroy(&qmp.parser);
 433
 434    return qmp.response;
 435}
 436
 437QDict *qtest_qmp_receive(QTestState *s)
 438{
 439    return qmp_fd_receive(s->qmp_fd);
 440}
 441
 442/**
 443 * Allow users to send a message without waiting for the reply,
 444 * in the case that they choose to discard all replies up until
 445 * a particular EVENT is received.
 446 */
 447void qmp_fd_sendv(int fd, const char *fmt, va_list ap)
 448{
 449    va_list ap_copy;
 450    QObject *qobj;
 451
 452    /* qobject_from_jsonv() silently eats leading 0xff as invalid
 453     * JSON, but we want to test sending them over the wire to force
 454     * resyncs */
 455    if (*fmt == '\377') {
 456        socket_send(fd, fmt, 1);
 457        fmt++;
 458    }
 459
 460    /* Going through qobject ensures we escape strings properly.
 461     * This seemingly unnecessary copy is required in case va_list
 462     * is an array type.
 463     */
 464    va_copy(ap_copy, ap);
 465    qobj = qobject_from_jsonv(fmt, &ap_copy, &error_abort);
 466    va_end(ap_copy);
 467
 468    /* No need to send anything for an empty QObject.  */
 469    if (qobj) {
 470        int log = getenv("QTEST_LOG") != NULL;
 471        QString *qstr = qobject_to_json(qobj);
 472        const char *str;
 473
 474        /*
 475         * BUG: QMP doesn't react to input until it sees a newline, an
 476         * object, or an array.  Work-around: give it a newline.
 477         */
 478        qstring_append_chr(qstr, '\n');
 479        str = qstring_get_str(qstr);
 480
 481        if (log) {
 482            fprintf(stderr, "%s", str);
 483        }
 484        /* Send QMP request */
 485        socket_send(fd, str, qstring_get_length(qstr));
 486
 487        QDECREF(qstr);
 488        qobject_decref(qobj);
 489    }
 490}
 491
 492void qtest_async_qmpv(QTestState *s, const char *fmt, va_list ap)
 493{
 494    qmp_fd_sendv(s->qmp_fd, fmt, ap);
 495}
 496
 497QDict *qmp_fdv(int fd, const char *fmt, va_list ap)
 498{
 499    qmp_fd_sendv(fd, fmt, ap);
 500
 501    return qmp_fd_receive(fd);
 502}
 503
 504QDict *qtest_qmpv(QTestState *s, const char *fmt, va_list ap)
 505{
 506    qtest_async_qmpv(s, fmt, ap);
 507
 508    /* Receive reply */
 509    return qtest_qmp_receive(s);
 510}
 511
 512QDict *qmp_fd(int fd, const char *fmt, ...)
 513{
 514    va_list ap;
 515    QDict *response;
 516
 517    va_start(ap, fmt);
 518    response = qmp_fdv(fd, fmt, ap);
 519    va_end(ap);
 520    return response;
 521}
 522
 523void qmp_fd_send(int fd, const char *fmt, ...)
 524{
 525    va_list ap;
 526
 527    va_start(ap, fmt);
 528    qmp_fd_sendv(fd, fmt, ap);
 529    va_end(ap);
 530}
 531
 532QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
 533{
 534    va_list ap;
 535    QDict *response;
 536
 537    va_start(ap, fmt);
 538    response = qtest_qmpv(s, fmt, ap);
 539    va_end(ap);
 540    return response;
 541}
 542
 543void qtest_async_qmp(QTestState *s, const char *fmt, ...)
 544{
 545    va_list ap;
 546
 547    va_start(ap, fmt);
 548    qtest_async_qmpv(s, fmt, ap);
 549    va_end(ap);
 550}
 551
 552void qtest_qmpv_discard_response(QTestState *s, const char *fmt, va_list ap)
 553{
 554    QDict *response = qtest_qmpv(s, fmt, ap);
 555    QDECREF(response);
 556}
 557
 558void qtest_qmp_discard_response(QTestState *s, const char *fmt, ...)
 559{
 560    va_list ap;
 561    QDict *response;
 562
 563    va_start(ap, fmt);
 564    response = qtest_qmpv(s, fmt, ap);
 565    va_end(ap);
 566    QDECREF(response);
 567}
 568
 569QDict *qtest_qmp_eventwait_ref(QTestState *s, const char *event)
 570{
 571    QDict *response;
 572
 573    for (;;) {
 574        response = qtest_qmp_receive(s);
 575        if ((qdict_haskey(response, "event")) &&
 576            (strcmp(qdict_get_str(response, "event"), event) == 0)) {
 577            return response;
 578        }
 579        QDECREF(response);
 580    }
 581}
 582
 583void qtest_qmp_eventwait(QTestState *s, const char *event)
 584{
 585    QDict *response;
 586
 587    response = qtest_qmp_eventwait_ref(s, event);
 588    QDECREF(response);
 589}
 590
 591char *qtest_hmpv(QTestState *s, const char *fmt, va_list ap)
 592{
 593    char *cmd;
 594    QDict *resp;
 595    char *ret;
 596
 597    cmd = g_strdup_vprintf(fmt, ap);
 598    resp = qtest_qmp(s, "{'execute': 'human-monitor-command',"
 599                     " 'arguments': {'command-line': %s}}",
 600                     cmd);
 601    ret = g_strdup(qdict_get_try_str(resp, "return"));
 602    while (ret == NULL && qdict_get_try_str(resp, "event")) {
 603        /* Ignore asynchronous QMP events */
 604        QDECREF(resp);
 605        resp = qtest_qmp_receive(s);
 606        ret = g_strdup(qdict_get_try_str(resp, "return"));
 607    }
 608    g_assert(ret);
 609    QDECREF(resp);
 610    g_free(cmd);
 611    return ret;
 612}
 613
 614char *qtest_hmp(QTestState *s, const char *fmt, ...)
 615{
 616    va_list ap;
 617    char *ret;
 618
 619    va_start(ap, fmt);
 620    ret = qtest_hmpv(s, fmt, ap);
 621    va_end(ap);
 622    return ret;
 623}
 624
 625const char *qtest_get_arch(void)
 626{
 627    const char *qemu = getenv("QTEST_QEMU_BINARY");
 628    g_assert(qemu != NULL);
 629    const char *end = strrchr(qemu, '/');
 630
 631    return end + strlen("/qemu-system-");
 632}
 633
 634bool qtest_get_irq(QTestState *s, int num)
 635{
 636    /* dummy operation in order to make sure irq is up to date */
 637    qtest_inb(s, 0);
 638
 639    return s->irq_level[num];
 640}
 641
 642static int64_t qtest_clock_rsp(QTestState *s)
 643{
 644    gchar **words;
 645    int64_t clock;
 646    words = qtest_rsp(s, 2);
 647    clock = g_ascii_strtoll(words[1], NULL, 0);
 648    g_strfreev(words);
 649    return clock;
 650}
 651
 652int64_t qtest_clock_step_next(QTestState *s)
 653{
 654    qtest_sendf(s, "clock_step\n");
 655    return qtest_clock_rsp(s);
 656}
 657
 658int64_t qtest_clock_step(QTestState *s, int64_t step)
 659{
 660    qtest_sendf(s, "clock_step %"PRIi64"\n", step);
 661    return qtest_clock_rsp(s);
 662}
 663
 664int64_t qtest_clock_set(QTestState *s, int64_t val)
 665{
 666    qtest_sendf(s, "clock_set %"PRIi64"\n", val);
 667    return qtest_clock_rsp(s);
 668}
 669
 670void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
 671{
 672    qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
 673    qtest_rsp(s, 0);
 674}
 675
 676void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
 677{
 678    qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
 679    qtest_rsp(s, 0);
 680}
 681
 682static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
 683{
 684    qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
 685    qtest_rsp(s, 0);
 686}
 687
 688void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
 689{
 690    qtest_out(s, "outb", addr, value);
 691}
 692
 693void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
 694{
 695    qtest_out(s, "outw", addr, value);
 696}
 697
 698void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
 699{
 700    qtest_out(s, "outl", addr, value);
 701}
 702
 703static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
 704{
 705    gchar **args;
 706    uint32_t value;
 707
 708    qtest_sendf(s, "%s 0x%x\n", cmd, addr);
 709    args = qtest_rsp(s, 2);
 710    value = strtoul(args[1], NULL, 0);
 711    g_strfreev(args);
 712
 713    return value;
 714}
 715
 716uint8_t qtest_inb(QTestState *s, uint16_t addr)
 717{
 718    return qtest_in(s, "inb", addr);
 719}
 720
 721uint16_t qtest_inw(QTestState *s, uint16_t addr)
 722{
 723    return qtest_in(s, "inw", addr);
 724}
 725
 726uint32_t qtest_inl(QTestState *s, uint16_t addr)
 727{
 728    return qtest_in(s, "inl", addr);
 729}
 730
 731static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
 732                        uint64_t value)
 733{
 734    qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
 735    qtest_rsp(s, 0);
 736}
 737
 738void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
 739{
 740    qtest_write(s, "writeb", addr, value);
 741}
 742
 743void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
 744{
 745    qtest_write(s, "writew", addr, value);
 746}
 747
 748void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
 749{
 750    qtest_write(s, "writel", addr, value);
 751}
 752
 753void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
 754{
 755    qtest_write(s, "writeq", addr, value);
 756}
 757
 758static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
 759{
 760    gchar **args;
 761    uint64_t value;
 762
 763    qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
 764    args = qtest_rsp(s, 2);
 765    value = strtoull(args[1], NULL, 0);
 766    g_strfreev(args);
 767
 768    return value;
 769}
 770
 771uint8_t qtest_readb(QTestState *s, uint64_t addr)
 772{
 773    return qtest_read(s, "readb", addr);
 774}
 775
 776uint16_t qtest_readw(QTestState *s, uint64_t addr)
 777{
 778    return qtest_read(s, "readw", addr);
 779}
 780
 781uint32_t qtest_readl(QTestState *s, uint64_t addr)
 782{
 783    return qtest_read(s, "readl", addr);
 784}
 785
 786uint64_t qtest_readq(QTestState *s, uint64_t addr)
 787{
 788    return qtest_read(s, "readq", addr);
 789}
 790
 791static int hex2nib(char ch)
 792{
 793    if (ch >= '0' && ch <= '9') {
 794        return ch - '0';
 795    } else if (ch >= 'a' && ch <= 'f') {
 796        return 10 + (ch - 'a');
 797    } else if (ch >= 'A' && ch <= 'F') {
 798        return 10 + (ch - 'a');
 799    } else {
 800        return -1;
 801    }
 802}
 803
 804void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
 805{
 806    uint8_t *ptr = data;
 807    gchar **args;
 808    size_t i;
 809
 810    if (!size) {
 811        return;
 812    }
 813
 814    qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
 815    args = qtest_rsp(s, 2);
 816
 817    for (i = 0; i < size; i++) {
 818        ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
 819        ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
 820    }
 821
 822    g_strfreev(args);
 823}
 824
 825uint64_t qtest_rtas_call(QTestState *s, const char *name,
 826                         uint32_t nargs, uint64_t args,
 827                         uint32_t nret, uint64_t ret)
 828{
 829    qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n",
 830                name, nargs, args, nret, ret);
 831    qtest_rsp(s, 0);
 832    return 0;
 833}
 834
 835void qtest_add_func(const char *str, void (*fn)(void))
 836{
 837    gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
 838    g_test_add_func(path, fn);
 839    g_free(path);
 840}
 841
 842void qtest_add_data_func_full(const char *str, void *data,
 843                              void (*fn)(const void *),
 844                              GDestroyNotify data_free_func)
 845{
 846    gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
 847    g_test_add_data_func_full(path, data, fn, data_free_func);
 848    g_free(path);
 849}
 850
 851void qtest_add_data_func(const char *str, const void *data,
 852                         void (*fn)(const void *))
 853{
 854    gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
 855    g_test_add_data_func(path, data, fn);
 856    g_free(path);
 857}
 858
 859void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
 860{
 861    gchar *bdata;
 862
 863    bdata = g_base64_encode(data, size);
 864    qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
 865    socket_send(s->fd, bdata, strlen(bdata));
 866    socket_send(s->fd, "\n", 1);
 867    qtest_rsp(s, 0);
 868    g_free(bdata);
 869}
 870
 871void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
 872{
 873    gchar **args;
 874    size_t len;
 875
 876    qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
 877    args = qtest_rsp(s, 2);
 878
 879    g_base64_decode_inplace(args[1], &len);
 880    if (size != len) {
 881        fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
 882                size, len);
 883        len = MIN(len, size);
 884    }
 885
 886    memcpy(data, args[1], len);
 887    g_strfreev(args);
 888}
 889
 890void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
 891{
 892    const uint8_t *ptr = data;
 893    size_t i;
 894    char *enc;
 895
 896    if (!size) {
 897        return;
 898    }
 899
 900    enc = g_malloc(2 * size + 1);
 901
 902    for (i = 0; i < size; i++) {
 903        sprintf(&enc[i * 2], "%02x", ptr[i]);
 904    }
 905
 906    qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
 907    qtest_rsp(s, 0);
 908    g_free(enc);
 909}
 910
 911void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
 912{
 913    qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
 914    qtest_rsp(s, 0);
 915}
 916
 917QDict *qmp(const char *fmt, ...)
 918{
 919    va_list ap;
 920    QDict *response;
 921
 922    va_start(ap, fmt);
 923    response = qtest_qmpv(global_qtest, fmt, ap);
 924    va_end(ap);
 925    return response;
 926}
 927
 928void qmp_async(const char *fmt, ...)
 929{
 930    va_list ap;
 931
 932    va_start(ap, fmt);
 933    qtest_async_qmpv(global_qtest, fmt, ap);
 934    va_end(ap);
 935}
 936
 937void qmp_discard_response(const char *fmt, ...)
 938{
 939    va_list ap;
 940
 941    va_start(ap, fmt);
 942    qtest_qmpv_discard_response(global_qtest, fmt, ap);
 943    va_end(ap);
 944}
 945char *hmp(const char *fmt, ...)
 946{
 947    va_list ap;
 948    char *ret;
 949
 950    va_start(ap, fmt);
 951    ret = qtest_hmpv(global_qtest, fmt, ap);
 952    va_end(ap);
 953    return ret;
 954}
 955
 956bool qtest_big_endian(QTestState *s)
 957{
 958    return s->big_endian;
 959}
 960
 961void qtest_cb_for_every_machine(void (*cb)(const char *machine))
 962{
 963    QDict *response, *minfo;
 964    QList *list;
 965    const QListEntry *p;
 966    QObject *qobj;
 967    QString *qstr;
 968    const char *mname;
 969
 970    qtest_start("-machine none");
 971    response = qmp("{ 'execute': 'query-machines' }");
 972    g_assert(response);
 973    list = qdict_get_qlist(response, "return");
 974    g_assert(list);
 975
 976    for (p = qlist_first(list); p; p = qlist_next(p)) {
 977        minfo = qobject_to_qdict(qlist_entry_obj(p));
 978        g_assert(minfo);
 979        qobj = qdict_get(minfo, "name");
 980        g_assert(qobj);
 981        qstr = qobject_to_qstring(qobj);
 982        g_assert(qstr);
 983        mname = qstring_get_str(qstr);
 984        cb(mname);
 985    }
 986
 987    qtest_end();
 988    QDECREF(response);
 989}
 990