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 19 #ifndef _WIN32 20 #include <sys/socket.h> 21 #include <sys/wait.h> 22 #include <sys/un.h> 23 #endif /* _WIN32 */ 24 #ifdef __linux__ 25 #include <sys/prctl.h> 26 #endif /* __linux__ */ 27 #ifdef __FreeBSD__ 28 #include <sys/procctl.h> 29 #endif /* __FreeBSD__ */ 30 31 #include "libqtest.h" 32 #include "libqmp.h" 33 #include "qemu/ctype.h" 34 #include "qemu/cutils.h" 35 #include "qemu/sockets.h" 36 #include "qapi/qmp/qdict.h" 37 #include "qapi/qmp/qjson.h" 38 #include "qapi/qmp/qlist.h" 39 #include "qapi/qmp/qstring.h" 40 41 #define MAX_IRQ 256 42 43 #ifndef _WIN32 44 # define SOCKET_TIMEOUT 50 45 # define CMD_EXEC "exec " 46 # define DEV_STDERR "/dev/fd/2" 47 # define DEV_NULL "/dev/null" 48 #else 49 # define SOCKET_TIMEOUT 50000 50 # define CMD_EXEC "" 51 # define DEV_STDERR "2" 52 # define DEV_NULL "nul" 53 #endif 54 55 #define WAITPID_TIMEOUT 30 56 57 typedef void (*QTestSendFn)(QTestState *s, const char *buf); 58 typedef void (*ExternalSendFn)(void *s, const char *buf); 59 typedef GString* (*QTestRecvFn)(QTestState *); 60 61 typedef struct QTestClientTransportOps { 62 QTestSendFn send; /* for sending qtest commands */ 63 64 /* 65 * use external_send to send qtest command strings through functions which 66 * do not accept a QTestState as the first parameter. 67 */ 68 ExternalSendFn external_send; 69 70 QTestRecvFn recv_line; /* for receiving qtest command responses */ 71 } QTestTransportOps; 72 73 struct QTestState 74 { 75 int fd; 76 int qmp_fd; 77 pid_t qemu_pid; /* our child QEMU process */ 78 int wstatus; 79 #ifdef _WIN32 80 DWORD exit_code; 81 #endif 82 int expected_status; 83 bool big_endian; 84 bool irq_level[MAX_IRQ]; 85 GString *rx; 86 QTestTransportOps ops; 87 GList *pending_events; 88 QTestQMPEventCallback eventCB; 89 void *eventData; 90 }; 91 92 static GHookList abrt_hooks; 93 static void (*sighandler_old)(int); 94 95 static int qtest_query_target_endianness(QTestState *s); 96 97 static void qtest_client_socket_send(QTestState*, const char *buf); 98 static void socket_send(int fd, const char *buf, size_t size); 99 100 static GString *qtest_client_socket_recv_line(QTestState *); 101 102 static void qtest_client_set_tx_handler(QTestState *s, QTestSendFn send); 103 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv); 104 105 static int init_socket(const char *socket_path) 106 { 107 int sock = qtest_socket_server(socket_path); 108 qemu_set_cloexec(sock); 109 return sock; 110 } 111 112 static int socket_accept(int sock) 113 { 114 struct sockaddr_un addr; 115 socklen_t addrlen; 116 int ret; 117 /* 118 * timeout unit of blocking receive calls is different among platforms. 119 * It's in seconds on non-Windows platforms but milliseconds on Windows. 120 */ 121 #ifndef _WIN32 122 struct timeval timeout = { .tv_sec = SOCKET_TIMEOUT, 123 .tv_usec = 0 }; 124 #else 125 DWORD timeout = SOCKET_TIMEOUT; 126 #endif 127 128 if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, 129 (void *)&timeout, sizeof(timeout))) { 130 fprintf(stderr, "%s failed to set SO_RCVTIMEO: %s\n", 131 __func__, strerror(errno)); 132 close(sock); 133 return -1; 134 } 135 136 do { 137 addrlen = sizeof(addr); 138 ret = accept(sock, (struct sockaddr *)&addr, &addrlen); 139 } while (ret == -1 && errno == EINTR); 140 if (ret == -1) { 141 fprintf(stderr, "%s failed: %s\n", __func__, strerror(errno)); 142 } 143 close(sock); 144 145 return ret; 146 } 147 148 pid_t qtest_pid(QTestState *s) 149 { 150 return s->qemu_pid; 151 } 152 153 bool qtest_probe_child(QTestState *s) 154 { 155 pid_t pid = s->qemu_pid; 156 157 if (pid != -1) { 158 #ifndef _WIN32 159 pid = waitpid(pid, &s->wstatus, WNOHANG); 160 if (pid == 0) { 161 return true; 162 } 163 #else 164 GetExitCodeProcess((HANDLE)pid, &s->exit_code); 165 if (s->exit_code == STILL_ACTIVE) { 166 return true; 167 } 168 CloseHandle((HANDLE)pid); 169 #endif 170 s->qemu_pid = -1; 171 qtest_remove_abrt_handler(s); 172 } 173 return false; 174 } 175 176 void qtest_set_expected_status(QTestState *s, int status) 177 { 178 s->expected_status = status; 179 } 180 181 static void qtest_check_status(QTestState *s) 182 { 183 assert(s->qemu_pid == -1); 184 185 /* 186 * Check whether qemu exited with expected exit status; anything else is 187 * fishy and should be logged with as much detail as possible. 188 */ 189 #ifndef _WIN32 190 int wstatus = s->wstatus; 191 if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != s->expected_status) { 192 fprintf(stderr, "%s:%d: kill_qemu() tried to terminate QEMU " 193 "process but encountered exit status %d (expected %d)\n", 194 __FILE__, __LINE__, WEXITSTATUS(wstatus), s->expected_status); 195 abort(); 196 } else if (WIFSIGNALED(wstatus)) { 197 int sig = WTERMSIG(wstatus); 198 const char *signame = strsignal(sig) ?: "unknown ???"; 199 const char *dump = WCOREDUMP(wstatus) ? " (core dumped)" : ""; 200 201 fprintf(stderr, "%s:%d: kill_qemu() detected QEMU death " 202 "from signal %d (%s)%s\n", 203 __FILE__, __LINE__, sig, signame, dump); 204 abort(); 205 } 206 #else 207 if (s->exit_code != s->expected_status) { 208 fprintf(stderr, "%s:%d: kill_qemu() tried to terminate QEMU " 209 "process but encountered exit status %ld (expected %d)\n", 210 __FILE__, __LINE__, s->exit_code, s->expected_status); 211 abort(); 212 } 213 #endif 214 } 215 216 void qtest_wait_qemu(QTestState *s) 217 { 218 if (s->qemu_pid != -1) { 219 #ifndef _WIN32 220 pid_t pid; 221 uint64_t end; 222 223 /* poll for a while until sending SIGKILL */ 224 end = g_get_monotonic_time() + WAITPID_TIMEOUT * G_TIME_SPAN_SECOND; 225 226 do { 227 pid = waitpid(s->qemu_pid, &s->wstatus, WNOHANG); 228 if (pid != 0) { 229 break; 230 } 231 g_usleep(100 * 1000); 232 } while (g_get_monotonic_time() < end); 233 234 if (pid == 0) { 235 kill(s->qemu_pid, SIGKILL); 236 pid = RETRY_ON_EINTR(waitpid(s->qemu_pid, &s->wstatus, 0)); 237 } 238 239 assert(pid == s->qemu_pid); 240 #else 241 DWORD ret; 242 243 ret = WaitForSingleObject((HANDLE)s->qemu_pid, INFINITE); 244 assert(ret == WAIT_OBJECT_0); 245 GetExitCodeProcess((HANDLE)s->qemu_pid, &s->exit_code); 246 CloseHandle((HANDLE)s->qemu_pid); 247 #endif 248 249 s->qemu_pid = -1; 250 qtest_remove_abrt_handler(s); 251 } 252 qtest_check_status(s); 253 } 254 255 void qtest_kill_qemu(QTestState *s) 256 { 257 /* Skip wait if qtest_probe_child() already reaped */ 258 if (s->qemu_pid != -1) { 259 #ifndef _WIN32 260 kill(s->qemu_pid, SIGTERM); 261 #else 262 TerminateProcess((HANDLE)s->qemu_pid, s->expected_status); 263 #endif 264 qtest_wait_qemu(s); 265 return; 266 } 267 268 qtest_check_status(s); 269 } 270 271 static void kill_qemu_hook_func(void *s) 272 { 273 qtest_kill_qemu(s); 274 } 275 276 static void sigabrt_handler(int signo) 277 { 278 g_hook_list_invoke(&abrt_hooks, FALSE); 279 } 280 281 static void setup_sigabrt_handler(void) 282 { 283 sighandler_old = signal(SIGABRT, sigabrt_handler); 284 } 285 286 static void cleanup_sigabrt_handler(void) 287 { 288 signal(SIGABRT, sighandler_old); 289 } 290 291 static bool hook_list_is_empty(GHookList *hook_list) 292 { 293 GHook *hook = g_hook_first_valid(hook_list, TRUE); 294 295 if (!hook) { 296 return true; 297 } 298 299 g_hook_unref(hook_list, hook); 300 return false; 301 } 302 303 void qtest_add_abrt_handler(GHookFunc fn, const void *data) 304 { 305 GHook *hook; 306 307 if (!abrt_hooks.is_setup) { 308 g_hook_list_init(&abrt_hooks, sizeof(GHook)); 309 } 310 311 /* Only install SIGABRT handler once */ 312 if (hook_list_is_empty(&abrt_hooks)) { 313 setup_sigabrt_handler(); 314 } 315 316 hook = g_hook_alloc(&abrt_hooks); 317 hook->func = fn; 318 hook->data = (void *)data; 319 320 g_hook_prepend(&abrt_hooks, hook); 321 } 322 323 void qtest_remove_abrt_handler(void *data) 324 { 325 GHook *hook = g_hook_find_data(&abrt_hooks, TRUE, data); 326 327 if (!hook) { 328 return; 329 } 330 331 g_hook_destroy_link(&abrt_hooks, hook); 332 333 /* Uninstall SIGABRT handler on last instance */ 334 if (hook_list_is_empty(&abrt_hooks)) { 335 cleanup_sigabrt_handler(); 336 } 337 } 338 339 static const char *qtest_qemu_binary(void) 340 { 341 const char *qemu_bin; 342 343 qemu_bin = getenv("QTEST_QEMU_BINARY"); 344 if (!qemu_bin) { 345 fprintf(stderr, "Environment variable QTEST_QEMU_BINARY required\n"); 346 exit(1); 347 } 348 349 return qemu_bin; 350 } 351 352 #ifdef _WIN32 353 static pid_t qtest_create_process(char *cmd) 354 { 355 STARTUPINFO si; 356 PROCESS_INFORMATION pi; 357 BOOL ret; 358 359 ZeroMemory(&si, sizeof(si)); 360 si.cb = sizeof(si); 361 ZeroMemory(&pi, sizeof(pi)); 362 363 ret = CreateProcess(NULL, /* module name */ 364 cmd, /* command line */ 365 NULL, /* process handle not inheritable */ 366 NULL, /* thread handle not inheritable */ 367 FALSE, /* set handle inheritance to FALSE */ 368 0, /* No creation flags */ 369 NULL, /* use parent's environment block */ 370 NULL, /* use parent's starting directory */ 371 &si, /* pointer to STARTUPINFO structure */ 372 &pi /* pointer to PROCESS_INFORMATION structure */ 373 ); 374 if (ret == 0) { 375 fprintf(stderr, "%s:%d: unable to create a new process (%s)\n", 376 __FILE__, __LINE__, strerror(GetLastError())); 377 abort(); 378 } 379 380 return (pid_t)pi.hProcess; 381 } 382 #endif /* _WIN32 */ 383 384 static QTestState *G_GNUC_PRINTF(1, 2) qtest_spawn_qemu(const char *fmt, ...) 385 { 386 va_list ap; 387 QTestState *s = g_new0(QTestState, 1); 388 const char *trace = g_getenv("QTEST_TRACE"); 389 g_autofree char *tracearg = trace ? 390 g_strdup_printf("-trace %s ", trace) : g_strdup(""); 391 g_autoptr(GString) command = g_string_new(""); 392 393 va_start(ap, fmt); 394 g_string_append_printf(command, CMD_EXEC "%s %s", 395 qtest_qemu_binary(), tracearg); 396 g_string_append_vprintf(command, fmt, ap); 397 va_end(ap); 398 399 qtest_add_abrt_handler(kill_qemu_hook_func, s); 400 401 g_test_message("starting QEMU: %s", command->str); 402 403 #ifndef _WIN32 404 s->qemu_pid = fork(); 405 if (s->qemu_pid == 0) { 406 #ifdef __linux__ 407 /* 408 * Although we register a ABRT handler to kill off QEMU 409 * when g_assert() triggers, we want an extra safety 410 * net. The QEMU process might be non-functional and 411 * thus not have responded to SIGTERM. The test script 412 * might also have crashed with SEGV, in which case the 413 * cleanup handlers won't ever run. 414 * 415 * This PR_SET_PDEATHSIG setup will ensure any remaining 416 * QEMU will get terminated with SIGKILL in these cases. 417 */ 418 prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); 419 #endif /* __linux__ */ 420 #ifdef __FreeBSD__ 421 int sig = SIGKILL; 422 procctl(P_PID, getpid(), PROC_PDEATHSIG_CTL, &sig); 423 #endif /* __FreeBSD__ */ 424 if (!g_setenv("QEMU_AUDIO_DRV", "none", true)) { 425 exit(1); 426 } 427 execlp("/bin/sh", "sh", "-c", command->str, NULL); 428 exit(1); 429 } 430 #else 431 s->qemu_pid = qtest_create_process(command->str); 432 #endif /* _WIN32 */ 433 434 return s; 435 } 436 437 QTestState *qtest_init_without_qmp_handshake(const char *extra_args) 438 { 439 QTestState *s; 440 int sock, qmpsock, i; 441 gchar *socket_path; 442 gchar *qmp_socket_path; 443 444 socket_path = g_strdup_printf("%s/qtest-%d.sock", 445 g_get_tmp_dir(), getpid()); 446 qmp_socket_path = g_strdup_printf("%s/qtest-%d.qmp", 447 g_get_tmp_dir(), getpid()); 448 449 /* 450 * It's possible that if an earlier test run crashed it might 451 * have left a stale unix socket lying around. Delete any 452 * stale old socket to avoid spurious test failures with 453 * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1) 454 */ 455 unlink(socket_path); 456 unlink(qmp_socket_path); 457 458 socket_init(); 459 sock = init_socket(socket_path); 460 qmpsock = init_socket(qmp_socket_path); 461 462 s = qtest_spawn_qemu("-qtest unix:%s " 463 "-qtest-log %s " 464 "-chardev socket,path=%s,id=char0 " 465 "-mon chardev=char0,mode=control " 466 "-display none " 467 "%s" 468 " -accel qtest", 469 socket_path, 470 getenv("QTEST_LOG") ? DEV_STDERR : DEV_NULL, 471 qmp_socket_path, 472 extra_args ?: ""); 473 474 qtest_client_set_rx_handler(s, qtest_client_socket_recv_line); 475 qtest_client_set_tx_handler(s, qtest_client_socket_send); 476 477 s->fd = socket_accept(sock); 478 if (s->fd >= 0) { 479 s->qmp_fd = socket_accept(qmpsock); 480 } 481 unlink(socket_path); 482 unlink(qmp_socket_path); 483 g_free(socket_path); 484 g_free(qmp_socket_path); 485 486 g_assert(s->fd >= 0 && s->qmp_fd >= 0); 487 488 s->rx = g_string_new(""); 489 for (i = 0; i < MAX_IRQ; i++) { 490 s->irq_level[i] = false; 491 } 492 493 /* 494 * Stopping QEMU for debugging is not supported on Windows. 495 * 496 * Using DebugActiveProcess() API can suspend the QEMU process, 497 * but gdb cannot attach to the process. Using the undocumented 498 * NtSuspendProcess() can suspend the QEMU process and gdb can 499 * attach to the process, but gdb cannot resume it. 500 */ 501 #ifndef _WIN32 502 if (getenv("QTEST_STOP")) { 503 kill(s->qemu_pid, SIGSTOP); 504 } 505 #endif 506 507 /* ask endianness of the target */ 508 509 s->big_endian = qtest_query_target_endianness(s); 510 511 return s; 512 } 513 514 QTestState *qtest_init(const char *extra_args) 515 { 516 QTestState *s = qtest_init_without_qmp_handshake(extra_args); 517 QDict *greeting; 518 519 /* Read the QMP greeting and then do the handshake */ 520 greeting = qtest_qmp_receive(s); 521 qobject_unref(greeting); 522 qobject_unref(qtest_qmp(s, "{ 'execute': 'qmp_capabilities' }")); 523 524 return s; 525 } 526 527 QTestState *qtest_vinitf(const char *fmt, va_list ap) 528 { 529 char *args = g_strdup_vprintf(fmt, ap); 530 QTestState *s; 531 532 s = qtest_init(args); 533 g_free(args); 534 return s; 535 } 536 537 QTestState *qtest_initf(const char *fmt, ...) 538 { 539 va_list ap; 540 QTestState *s; 541 542 va_start(ap, fmt); 543 s = qtest_vinitf(fmt, ap); 544 va_end(ap); 545 return s; 546 } 547 548 QTestState *qtest_init_with_serial(const char *extra_args, int *sock_fd) 549 { 550 int sock_fd_init; 551 g_autofree char *sock_dir = NULL; 552 char *sock_path; 553 QTestState *qts; 554 555 sock_dir = g_dir_make_tmp("qtest-serial-XXXXXX", NULL); 556 g_assert_true(sock_dir != NULL); 557 sock_path = g_strdup_printf("%s/sock", sock_dir); 558 559 socket_init(); 560 sock_fd_init = init_socket(sock_path); 561 562 qts = qtest_initf("-chardev socket,id=s0,path=%s -serial chardev:s0 %s", 563 sock_path, extra_args); 564 565 *sock_fd = socket_accept(sock_fd_init); 566 567 unlink(sock_path); 568 g_free(sock_path); 569 rmdir(sock_dir); 570 571 g_assert_true(*sock_fd >= 0); 572 573 return qts; 574 } 575 576 void qtest_quit(QTestState *s) 577 { 578 qtest_remove_abrt_handler(s); 579 580 qtest_kill_qemu(s); 581 close(s->fd); 582 close(s->qmp_fd); 583 g_string_free(s->rx, true); 584 585 for (GList *it = s->pending_events; it != NULL; it = it->next) { 586 qobject_unref((QDict *)it->data); 587 } 588 589 g_list_free(s->pending_events); 590 591 g_free(s); 592 } 593 594 static void socket_send(int fd, const char *buf, size_t size) 595 { 596 ssize_t res = qemu_send_full(fd, buf, size); 597 598 assert(res == size); 599 } 600 601 static void qtest_client_socket_send(QTestState *s, const char *buf) 602 { 603 socket_send(s->fd, buf, strlen(buf)); 604 } 605 606 static void G_GNUC_PRINTF(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...) 607 { 608 va_list ap; 609 610 va_start(ap, fmt); 611 gchar *str = g_strdup_vprintf(fmt, ap); 612 va_end(ap); 613 614 s->ops.send(s, str); 615 g_free(str); 616 } 617 618 static GString *qtest_client_socket_recv_line(QTestState *s) 619 { 620 GString *line; 621 size_t offset; 622 char *eol; 623 624 while ((eol = strchr(s->rx->str, '\n')) == NULL) { 625 ssize_t len; 626 char buffer[1024]; 627 628 len = recv(s->fd, buffer, sizeof(buffer), 0); 629 if (len == -1 && errno == EINTR) { 630 continue; 631 } 632 633 if (len == -1 || len == 0) { 634 fprintf(stderr, "Broken pipe\n"); 635 abort(); 636 } 637 638 g_string_append_len(s->rx, buffer, len); 639 } 640 641 offset = eol - s->rx->str; 642 line = g_string_new_len(s->rx->str, offset); 643 g_string_erase(s->rx, 0, offset + 1); 644 645 return line; 646 } 647 648 static gchar **qtest_rsp_args(QTestState *s, int expected_args) 649 { 650 GString *line; 651 gchar **words; 652 int i; 653 654 redo: 655 line = s->ops.recv_line(s); 656 words = g_strsplit(line->str, " ", 0); 657 g_string_free(line, TRUE); 658 659 if (strcmp(words[0], "IRQ") == 0) { 660 long irq; 661 int ret; 662 663 g_assert(words[1] != NULL); 664 g_assert(words[2] != NULL); 665 666 ret = qemu_strtol(words[2], NULL, 0, &irq); 667 g_assert(!ret); 668 g_assert_cmpint(irq, >=, 0); 669 g_assert_cmpint(irq, <, MAX_IRQ); 670 671 if (strcmp(words[1], "raise") == 0) { 672 s->irq_level[irq] = true; 673 } else { 674 s->irq_level[irq] = false; 675 } 676 677 g_strfreev(words); 678 goto redo; 679 } 680 681 g_assert(words[0] != NULL); 682 g_assert_cmpstr(words[0], ==, "OK"); 683 684 for (i = 0; i < expected_args; i++) { 685 g_assert(words[i] != NULL); 686 } 687 688 return words; 689 } 690 691 static void qtest_rsp(QTestState *s) 692 { 693 gchar **words = qtest_rsp_args(s, 0); 694 695 g_strfreev(words); 696 } 697 698 static int qtest_query_target_endianness(QTestState *s) 699 { 700 gchar **args; 701 int big_endian; 702 703 qtest_sendf(s, "endianness\n"); 704 args = qtest_rsp_args(s, 1); 705 g_assert(strcmp(args[1], "big") == 0 || strcmp(args[1], "little") == 0); 706 big_endian = strcmp(args[1], "big") == 0; 707 g_strfreev(args); 708 709 return big_endian; 710 } 711 712 QDict *qtest_qmp_receive(QTestState *s) 713 { 714 while (true) { 715 QDict *response = qtest_qmp_receive_dict(s); 716 717 if (!qdict_get_try_str(response, "event")) { 718 return response; 719 } 720 721 if (!s->eventCB || 722 !s->eventCB(s, qdict_get_str(response, "event"), 723 response, s->eventData)) { 724 /* Stash the event for a later consumption */ 725 s->pending_events = g_list_append(s->pending_events, response); 726 } 727 } 728 } 729 730 QDict *qtest_qmp_receive_dict(QTestState *s) 731 { 732 return qmp_fd_receive(s->qmp_fd); 733 } 734 735 int qtest_socket_server(const char *socket_path) 736 { 737 struct sockaddr_un addr; 738 int sock; 739 int ret; 740 741 sock = socket(PF_UNIX, SOCK_STREAM, 0); 742 g_assert_cmpint(sock, !=, -1); 743 744 addr.sun_family = AF_UNIX; 745 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path); 746 747 ret = RETRY_ON_EINTR(bind(sock, (struct sockaddr *)&addr, sizeof(addr))); 748 g_assert_cmpint(ret, !=, -1); 749 ret = listen(sock, 1); 750 g_assert_cmpint(ret, !=, -1); 751 752 return sock; 753 } 754 755 #ifndef _WIN32 756 void qtest_qmp_vsend_fds(QTestState *s, int *fds, size_t fds_num, 757 const char *fmt, va_list ap) 758 { 759 qmp_fd_vsend_fds(s->qmp_fd, fds, fds_num, fmt, ap); 760 } 761 #endif 762 763 void qtest_qmp_vsend(QTestState *s, const char *fmt, va_list ap) 764 { 765 qmp_fd_vsend(s->qmp_fd, fmt, ap); 766 } 767 768 #ifndef _WIN32 769 QDict *qtest_vqmp_fds(QTestState *s, int *fds, size_t fds_num, 770 const char *fmt, va_list ap) 771 { 772 qtest_qmp_vsend_fds(s, fds, fds_num, fmt, ap); 773 774 /* Receive reply */ 775 return qtest_qmp_receive(s); 776 } 777 #endif 778 779 QDict *qtest_vqmp(QTestState *s, const char *fmt, va_list ap) 780 { 781 qtest_qmp_vsend(s, fmt, ap); 782 783 /* Receive reply */ 784 return qtest_qmp_receive(s); 785 } 786 787 #ifndef _WIN32 788 QDict *qtest_qmp_fds(QTestState *s, int *fds, size_t fds_num, 789 const char *fmt, ...) 790 { 791 va_list ap; 792 QDict *response; 793 794 va_start(ap, fmt); 795 response = qtest_vqmp_fds(s, fds, fds_num, fmt, ap); 796 va_end(ap); 797 return response; 798 } 799 #endif 800 801 QDict *qtest_qmp(QTestState *s, const char *fmt, ...) 802 { 803 va_list ap; 804 QDict *response; 805 806 va_start(ap, fmt); 807 response = qtest_vqmp(s, fmt, ap); 808 va_end(ap); 809 return response; 810 } 811 812 void qtest_qmp_send(QTestState *s, const char *fmt, ...) 813 { 814 va_list ap; 815 816 va_start(ap, fmt); 817 qtest_qmp_vsend(s, fmt, ap); 818 va_end(ap); 819 } 820 821 void qtest_qmp_send_raw(QTestState *s, const char *fmt, ...) 822 { 823 va_list ap; 824 825 va_start(ap, fmt); 826 qmp_fd_vsend_raw(s->qmp_fd, fmt, ap); 827 va_end(ap); 828 } 829 830 void qtest_qmp_set_event_callback(QTestState *s, 831 QTestQMPEventCallback cb, void *opaque) 832 { 833 s->eventCB = cb; 834 s->eventData = opaque; 835 } 836 837 QDict *qtest_qmp_event_ref(QTestState *s, const char *event) 838 { 839 while (s->pending_events) { 840 841 GList *first = s->pending_events; 842 QDict *response = (QDict *)first->data; 843 844 s->pending_events = g_list_delete_link(s->pending_events, first); 845 846 if (!strcmp(qdict_get_str(response, "event"), event)) { 847 return response; 848 } 849 qobject_unref(response); 850 } 851 return NULL; 852 } 853 854 QDict *qtest_qmp_eventwait_ref(QTestState *s, const char *event) 855 { 856 QDict *response = qtest_qmp_event_ref(s, event); 857 858 if (response) { 859 return response; 860 } 861 862 for (;;) { 863 response = qtest_qmp_receive_dict(s); 864 if ((qdict_haskey(response, "event")) && 865 (strcmp(qdict_get_str(response, "event"), event) == 0)) { 866 return response; 867 } 868 qobject_unref(response); 869 } 870 } 871 872 void qtest_qmp_eventwait(QTestState *s, const char *event) 873 { 874 QDict *response; 875 876 response = qtest_qmp_eventwait_ref(s, event); 877 qobject_unref(response); 878 } 879 880 char *qtest_vhmp(QTestState *s, const char *fmt, va_list ap) 881 { 882 char *cmd; 883 QDict *resp; 884 char *ret; 885 886 cmd = g_strdup_vprintf(fmt, ap); 887 resp = qtest_qmp(s, "{'execute': 'human-monitor-command'," 888 " 'arguments': {'command-line': %s}}", 889 cmd); 890 ret = g_strdup(qdict_get_try_str(resp, "return")); 891 g_assert(ret); 892 qobject_unref(resp); 893 g_free(cmd); 894 return ret; 895 } 896 897 char *qtest_hmp(QTestState *s, const char *fmt, ...) 898 { 899 va_list ap; 900 char *ret; 901 902 va_start(ap, fmt); 903 ret = qtest_vhmp(s, fmt, ap); 904 va_end(ap); 905 return ret; 906 } 907 908 const char *qtest_get_arch(void) 909 { 910 const char *qemu = qtest_qemu_binary(); 911 const char *end = strrchr(qemu, '-'); 912 913 if (!end) { 914 fprintf(stderr, "Can't determine architecture from binary name.\n"); 915 exit(1); 916 } 917 918 if (!strstr(qemu, "-system-")) { 919 fprintf(stderr, "QTEST_QEMU_BINARY must end with *-system-<arch> " 920 "where 'arch' is the target\narchitecture (x86_64, aarch64, " 921 "etc).\n"); 922 exit(1); 923 } 924 925 return end + 1; 926 } 927 928 bool qtest_has_accel(const char *accel_name) 929 { 930 if (g_str_equal(accel_name, "tcg")) { 931 #if defined(CONFIG_TCG) 932 return true; 933 #else 934 return false; 935 #endif 936 } else if (g_str_equal(accel_name, "kvm")) { 937 int i; 938 const char *arch = qtest_get_arch(); 939 const char *targets[] = { CONFIG_KVM_TARGETS }; 940 941 for (i = 0; i < ARRAY_SIZE(targets); i++) { 942 if (!strncmp(targets[i], arch, strlen(arch))) { 943 if (!access("/dev/kvm", R_OK | W_OK)) { 944 return true; 945 } 946 } 947 } 948 } else { 949 /* not implemented */ 950 g_assert_not_reached(); 951 } 952 return false; 953 } 954 955 bool qtest_get_irq(QTestState *s, int num) 956 { 957 /* dummy operation in order to make sure irq is up to date */ 958 qtest_inb(s, 0); 959 960 return s->irq_level[num]; 961 } 962 963 void qtest_module_load(QTestState *s, const char *prefix, const char *libname) 964 { 965 qtest_sendf(s, "module_load %s %s\n", prefix, libname); 966 qtest_rsp(s); 967 } 968 969 static int64_t qtest_clock_rsp(QTestState *s) 970 { 971 gchar **words; 972 int64_t clock; 973 words = qtest_rsp_args(s, 2); 974 clock = g_ascii_strtoll(words[1], NULL, 0); 975 g_strfreev(words); 976 return clock; 977 } 978 979 int64_t qtest_clock_step_next(QTestState *s) 980 { 981 qtest_sendf(s, "clock_step\n"); 982 return qtest_clock_rsp(s); 983 } 984 985 int64_t qtest_clock_step(QTestState *s, int64_t step) 986 { 987 qtest_sendf(s, "clock_step %"PRIi64"\n", step); 988 return qtest_clock_rsp(s); 989 } 990 991 int64_t qtest_clock_set(QTestState *s, int64_t val) 992 { 993 qtest_sendf(s, "clock_set %"PRIi64"\n", val); 994 return qtest_clock_rsp(s); 995 } 996 997 void qtest_irq_intercept_out(QTestState *s, const char *qom_path) 998 { 999 qtest_sendf(s, "irq_intercept_out %s\n", qom_path); 1000 qtest_rsp(s); 1001 } 1002 1003 void qtest_irq_intercept_out_named(QTestState *s, const char *qom_path, const char *name) 1004 { 1005 qtest_sendf(s, "irq_intercept_out %s %s\n", qom_path, name); 1006 qtest_rsp(s); 1007 } 1008 1009 void qtest_irq_intercept_in(QTestState *s, const char *qom_path) 1010 { 1011 qtest_sendf(s, "irq_intercept_in %s\n", qom_path); 1012 qtest_rsp(s); 1013 } 1014 1015 void qtest_set_irq_in(QTestState *s, const char *qom_path, const char *name, 1016 int num, int level) 1017 { 1018 if (!name) { 1019 name = "unnamed-gpio-in"; 1020 } 1021 qtest_sendf(s, "set_irq_in %s %s %d %d\n", qom_path, name, num, level); 1022 qtest_rsp(s); 1023 } 1024 1025 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value) 1026 { 1027 qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value); 1028 qtest_rsp(s); 1029 } 1030 1031 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value) 1032 { 1033 qtest_out(s, "outb", addr, value); 1034 } 1035 1036 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value) 1037 { 1038 qtest_out(s, "outw", addr, value); 1039 } 1040 1041 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value) 1042 { 1043 qtest_out(s, "outl", addr, value); 1044 } 1045 1046 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr) 1047 { 1048 gchar **args; 1049 int ret; 1050 unsigned long value; 1051 1052 qtest_sendf(s, "%s 0x%x\n", cmd, addr); 1053 args = qtest_rsp_args(s, 2); 1054 ret = qemu_strtoul(args[1], NULL, 0, &value); 1055 g_assert(!ret && value <= UINT32_MAX); 1056 g_strfreev(args); 1057 1058 return value; 1059 } 1060 1061 uint8_t qtest_inb(QTestState *s, uint16_t addr) 1062 { 1063 return qtest_in(s, "inb", addr); 1064 } 1065 1066 uint16_t qtest_inw(QTestState *s, uint16_t addr) 1067 { 1068 return qtest_in(s, "inw", addr); 1069 } 1070 1071 uint32_t qtest_inl(QTestState *s, uint16_t addr) 1072 { 1073 return qtest_in(s, "inl", addr); 1074 } 1075 1076 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr, 1077 uint64_t value) 1078 { 1079 qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value); 1080 qtest_rsp(s); 1081 } 1082 1083 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value) 1084 { 1085 qtest_write(s, "writeb", addr, value); 1086 } 1087 1088 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value) 1089 { 1090 qtest_write(s, "writew", addr, value); 1091 } 1092 1093 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value) 1094 { 1095 qtest_write(s, "writel", addr, value); 1096 } 1097 1098 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value) 1099 { 1100 qtest_write(s, "writeq", addr, value); 1101 } 1102 1103 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr) 1104 { 1105 gchar **args; 1106 int ret; 1107 uint64_t value; 1108 1109 qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr); 1110 args = qtest_rsp_args(s, 2); 1111 ret = qemu_strtou64(args[1], NULL, 0, &value); 1112 g_assert(!ret); 1113 g_strfreev(args); 1114 1115 return value; 1116 } 1117 1118 uint8_t qtest_readb(QTestState *s, uint64_t addr) 1119 { 1120 return qtest_read(s, "readb", addr); 1121 } 1122 1123 uint16_t qtest_readw(QTestState *s, uint64_t addr) 1124 { 1125 return qtest_read(s, "readw", addr); 1126 } 1127 1128 uint32_t qtest_readl(QTestState *s, uint64_t addr) 1129 { 1130 return qtest_read(s, "readl", addr); 1131 } 1132 1133 uint64_t qtest_readq(QTestState *s, uint64_t addr) 1134 { 1135 return qtest_read(s, "readq", addr); 1136 } 1137 1138 static int hex2nib(char ch) 1139 { 1140 if (ch >= '0' && ch <= '9') { 1141 return ch - '0'; 1142 } else if (ch >= 'a' && ch <= 'f') { 1143 return 10 + (ch - 'a'); 1144 } else if (ch >= 'A' && ch <= 'F') { 1145 return 10 + (ch - 'a'); 1146 } else { 1147 return -1; 1148 } 1149 } 1150 1151 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size) 1152 { 1153 uint8_t *ptr = data; 1154 gchar **args; 1155 size_t i; 1156 1157 if (!size) { 1158 return; 1159 } 1160 1161 qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size); 1162 args = qtest_rsp_args(s, 2); 1163 1164 for (i = 0; i < size; i++) { 1165 ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4; 1166 ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]); 1167 } 1168 1169 g_strfreev(args); 1170 } 1171 1172 uint64_t qtest_rtas_call(QTestState *s, const char *name, 1173 uint32_t nargs, uint64_t args, 1174 uint32_t nret, uint64_t ret) 1175 { 1176 qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n", 1177 name, nargs, args, nret, ret); 1178 qtest_rsp(s); 1179 return 0; 1180 } 1181 1182 void qtest_add_func(const char *str, void (*fn)(void)) 1183 { 1184 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str); 1185 g_test_add_func(path, fn); 1186 g_free(path); 1187 } 1188 1189 void qtest_add_data_func_full(const char *str, void *data, 1190 void (*fn)(const void *), 1191 GDestroyNotify data_free_func) 1192 { 1193 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str); 1194 g_test_add_data_func_full(path, data, fn, data_free_func); 1195 g_free(path); 1196 } 1197 1198 void qtest_add_data_func(const char *str, const void *data, 1199 void (*fn)(const void *)) 1200 { 1201 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str); 1202 g_test_add_data_func(path, data, fn); 1203 g_free(path); 1204 } 1205 1206 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size) 1207 { 1208 gchar *bdata; 1209 1210 bdata = g_base64_encode(data, size); 1211 qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size); 1212 s->ops.send(s, bdata); 1213 s->ops.send(s, "\n"); 1214 qtest_rsp(s); 1215 g_free(bdata); 1216 } 1217 1218 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size) 1219 { 1220 gchar **args; 1221 size_t len; 1222 1223 qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size); 1224 args = qtest_rsp_args(s, 2); 1225 1226 g_base64_decode_inplace(args[1], &len); 1227 if (size != len) { 1228 fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n", 1229 size, len); 1230 len = MIN(len, size); 1231 } 1232 1233 memcpy(data, args[1], len); 1234 g_strfreev(args); 1235 } 1236 1237 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size) 1238 { 1239 const uint8_t *ptr = data; 1240 size_t i; 1241 char *enc; 1242 1243 if (!size) { 1244 return; 1245 } 1246 1247 enc = g_malloc(2 * size + 1); 1248 1249 for (i = 0; i < size; i++) { 1250 sprintf(&enc[i * 2], "%02x", ptr[i]); 1251 } 1252 1253 qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc); 1254 qtest_rsp(s); 1255 g_free(enc); 1256 } 1257 1258 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size) 1259 { 1260 qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern); 1261 qtest_rsp(s); 1262 } 1263 1264 QDict *qtest_vqmp_assert_success_ref(QTestState *qts, 1265 const char *fmt, va_list args) 1266 { 1267 QDict *response; 1268 QDict *ret; 1269 1270 response = qtest_vqmp(qts, fmt, args); 1271 1272 g_assert(response); 1273 if (!qdict_haskey(response, "return")) { 1274 g_autoptr(GString) s = qobject_to_json_pretty(QOBJECT(response), true); 1275 g_test_message("%s", s->str); 1276 } 1277 g_assert(qdict_haskey(response, "return")); 1278 ret = qdict_get_qdict(response, "return"); 1279 qobject_ref(ret); 1280 qobject_unref(response); 1281 1282 return ret; 1283 } 1284 1285 void qtest_vqmp_assert_success(QTestState *qts, 1286 const char *fmt, va_list args) 1287 { 1288 QDict *response; 1289 1290 response = qtest_vqmp_assert_success_ref(qts, fmt, args); 1291 1292 qobject_unref(response); 1293 } 1294 1295 #ifndef _WIN32 1296 QDict *qtest_vqmp_fds_assert_success_ref(QTestState *qts, int *fds, size_t nfds, 1297 const char *fmt, va_list args) 1298 { 1299 QDict *response; 1300 QDict *ret; 1301 1302 response = qtest_vqmp_fds(qts, fds, nfds, fmt, args); 1303 1304 g_assert(response); 1305 if (!qdict_haskey(response, "return")) { 1306 g_autoptr(GString) s = qobject_to_json_pretty(QOBJECT(response), true); 1307 g_test_message("%s", s->str); 1308 } 1309 g_assert(qdict_haskey(response, "return")); 1310 ret = qdict_get_qdict(response, "return"); 1311 qobject_ref(ret); 1312 qobject_unref(response); 1313 1314 return ret; 1315 } 1316 1317 void qtest_vqmp_fds_assert_success(QTestState *qts, int *fds, size_t nfds, 1318 const char *fmt, va_list args) 1319 { 1320 QDict *response; 1321 response = qtest_vqmp_fds_assert_success_ref(qts, fds, nfds, fmt, args); 1322 qobject_unref(response); 1323 } 1324 #endif /* !_WIN32 */ 1325 1326 QDict *qtest_qmp_assert_success_ref(QTestState *qts, const char *fmt, ...) 1327 { 1328 QDict *response; 1329 va_list ap; 1330 va_start(ap, fmt); 1331 response = qtest_vqmp_assert_success_ref(qts, fmt, ap); 1332 va_end(ap); 1333 return response; 1334 } 1335 1336 void qtest_qmp_assert_success(QTestState *qts, const char *fmt, ...) 1337 { 1338 va_list ap; 1339 va_start(ap, fmt); 1340 qtest_vqmp_assert_success(qts, fmt, ap); 1341 va_end(ap); 1342 } 1343 1344 #ifndef _WIN32 1345 QDict *qtest_qmp_fds_assert_success_ref(QTestState *qts, int *fds, size_t nfds, 1346 const char *fmt, ...) 1347 { 1348 QDict *response; 1349 va_list ap; 1350 va_start(ap, fmt); 1351 response = qtest_vqmp_fds_assert_success_ref(qts, fds, nfds, fmt, ap); 1352 va_end(ap); 1353 return response; 1354 } 1355 1356 void qtest_qmp_fds_assert_success(QTestState *qts, int *fds, size_t nfds, 1357 const char *fmt, ...) 1358 { 1359 va_list ap; 1360 va_start(ap, fmt); 1361 qtest_vqmp_fds_assert_success(qts, fds, nfds, fmt, ap); 1362 va_end(ap); 1363 } 1364 #endif /* !_WIN32 */ 1365 1366 bool qtest_big_endian(QTestState *s) 1367 { 1368 return s->big_endian; 1369 } 1370 1371 static bool qtest_check_machine_version(const char *mname, const char *basename, 1372 int major, int minor) 1373 { 1374 char *newname; 1375 bool is_equal; 1376 1377 newname = g_strdup_printf("%s-%i.%i", basename, major, minor); 1378 is_equal = g_str_equal(mname, newname); 1379 g_free(newname); 1380 1381 return is_equal; 1382 } 1383 1384 static bool qtest_is_old_versioned_machine(const char *mname) 1385 { 1386 const char *dash = strrchr(mname, '-'); 1387 const char *dot = strrchr(mname, '.'); 1388 const char *chr; 1389 char *bname; 1390 const int major = QEMU_VERSION_MAJOR; 1391 const int minor = QEMU_VERSION_MINOR; 1392 bool res = false; 1393 1394 if (dash && dot && dot > dash) { 1395 for (chr = dash + 1; *chr; chr++) { 1396 if (!qemu_isdigit(*chr) && *chr != '.') { 1397 return false; 1398 } 1399 } 1400 /* 1401 * Now check if it is one of the latest versions. Check major + 1 1402 * and minor + 1 versions as well, since they might already exist 1403 * in the development branch. 1404 */ 1405 bname = g_strdup(mname); 1406 bname[dash - mname] = 0; 1407 res = !qtest_check_machine_version(mname, bname, major + 1, 0) && 1408 !qtest_check_machine_version(mname, bname, major, minor + 1) && 1409 !qtest_check_machine_version(mname, bname, major, minor); 1410 g_free(bname); 1411 } 1412 1413 return res; 1414 } 1415 1416 struct MachInfo { 1417 char *name; 1418 char *alias; 1419 }; 1420 1421 /* 1422 * Returns an array with pointers to the available machine names. 1423 * The terminating entry has the name set to NULL. 1424 */ 1425 static struct MachInfo *qtest_get_machines(void) 1426 { 1427 static struct MachInfo *machines; 1428 QDict *response, *minfo; 1429 QList *list; 1430 const QListEntry *p; 1431 QObject *qobj; 1432 QString *qstr; 1433 QTestState *qts; 1434 int idx; 1435 1436 if (machines) { 1437 return machines; 1438 } 1439 1440 qts = qtest_init("-machine none"); 1441 response = qtest_qmp(qts, "{ 'execute': 'query-machines' }"); 1442 g_assert(response); 1443 list = qdict_get_qlist(response, "return"); 1444 g_assert(list); 1445 1446 machines = g_new(struct MachInfo, qlist_size(list) + 1); 1447 1448 for (p = qlist_first(list), idx = 0; p; p = qlist_next(p), idx++) { 1449 minfo = qobject_to(QDict, qlist_entry_obj(p)); 1450 g_assert(minfo); 1451 1452 qobj = qdict_get(minfo, "name"); 1453 g_assert(qobj); 1454 qstr = qobject_to(QString, qobj); 1455 g_assert(qstr); 1456 machines[idx].name = g_strdup(qstring_get_str(qstr)); 1457 1458 qobj = qdict_get(minfo, "alias"); 1459 if (qobj) { /* The alias is optional */ 1460 qstr = qobject_to(QString, qobj); 1461 g_assert(qstr); 1462 machines[idx].alias = g_strdup(qstring_get_str(qstr)); 1463 } else { 1464 machines[idx].alias = NULL; 1465 } 1466 } 1467 1468 qtest_quit(qts); 1469 qobject_unref(response); 1470 1471 memset(&machines[idx], 0, sizeof(struct MachInfo)); /* Terminating entry */ 1472 return machines; 1473 } 1474 1475 void qtest_cb_for_every_machine(void (*cb)(const char *machine), 1476 bool skip_old_versioned) 1477 { 1478 struct MachInfo *machines; 1479 int i; 1480 1481 machines = qtest_get_machines(); 1482 1483 for (i = 0; machines[i].name != NULL; i++) { 1484 /* Ignore machines that cannot be used for qtests */ 1485 if (!strncmp("xenfv", machines[i].name, 5) || 1486 g_str_equal("xenpv", machines[i].name) || 1487 g_str_equal("xenpvh", machines[i].name)) { 1488 continue; 1489 } 1490 if (!skip_old_versioned || 1491 !qtest_is_old_versioned_machine(machines[i].name)) { 1492 cb(machines[i].name); 1493 } 1494 } 1495 } 1496 1497 bool qtest_has_machine(const char *machine) 1498 { 1499 struct MachInfo *machines; 1500 int i; 1501 1502 machines = qtest_get_machines(); 1503 1504 for (i = 0; machines[i].name != NULL; i++) { 1505 if (g_str_equal(machine, machines[i].name) || 1506 (machines[i].alias && g_str_equal(machine, machines[i].alias))) { 1507 return true; 1508 } 1509 } 1510 1511 return false; 1512 } 1513 1514 bool qtest_has_device(const char *device) 1515 { 1516 static QList *list; 1517 const QListEntry *p; 1518 QObject *qobj; 1519 QString *qstr; 1520 QDict *devinfo; 1521 int idx; 1522 1523 if (!list) { 1524 QDict *resp; 1525 QDict *args; 1526 QTestState *qts = qtest_init("-machine none"); 1527 1528 args = qdict_new(); 1529 qdict_put_bool(args, "abstract", false); 1530 qdict_put_str(args, "implements", "device"); 1531 1532 resp = qtest_qmp(qts, "{'execute': 'qom-list-types', 'arguments': %p }", 1533 args); 1534 g_assert(qdict_haskey(resp, "return")); 1535 list = qdict_get_qlist(resp, "return"); 1536 qobject_ref(list); 1537 qobject_unref(resp); 1538 1539 qtest_quit(qts); 1540 } 1541 1542 for (p = qlist_first(list), idx = 0; p; p = qlist_next(p), idx++) { 1543 devinfo = qobject_to(QDict, qlist_entry_obj(p)); 1544 g_assert(devinfo); 1545 1546 qobj = qdict_get(devinfo, "name"); 1547 g_assert(qobj); 1548 qstr = qobject_to(QString, qobj); 1549 g_assert(qstr); 1550 if (g_str_equal(qstring_get_str(qstr), device)) { 1551 return true; 1552 } 1553 } 1554 1555 return false; 1556 } 1557 1558 /* 1559 * Generic hot-plugging test via the device_add QMP commands. 1560 */ 1561 void qtest_qmp_device_add_qdict(QTestState *qts, const char *drv, 1562 const QDict *arguments) 1563 { 1564 QDict *resp; 1565 QDict *args = arguments ? qdict_clone_shallow(arguments) : qdict_new(); 1566 1567 g_assert(!qdict_haskey(args, "driver")); 1568 qdict_put_str(args, "driver", drv); 1569 resp = qtest_qmp(qts, "{'execute': 'device_add', 'arguments': %p}", args); 1570 g_assert(resp); 1571 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */ 1572 if (qdict_haskey(resp, "error")) { 1573 fprintf(stderr, "error: %s\n", 1574 qdict_get_str(qdict_get_qdict(resp, "error"), "desc")); 1575 } 1576 g_assert(!qdict_haskey(resp, "error")); 1577 qobject_unref(resp); 1578 } 1579 1580 void qtest_qmp_device_add(QTestState *qts, const char *driver, const char *id, 1581 const char *fmt, ...) 1582 { 1583 QDict *args; 1584 va_list ap; 1585 1586 va_start(ap, fmt); 1587 args = qdict_from_vjsonf_nofail(fmt, ap); 1588 va_end(ap); 1589 1590 g_assert(!qdict_haskey(args, "id")); 1591 qdict_put_str(args, "id", id); 1592 1593 qtest_qmp_device_add_qdict(qts, driver, args); 1594 qobject_unref(args); 1595 } 1596 1597 void qtest_qmp_add_client(QTestState *qts, const char *protocol, int fd) 1598 { 1599 QDict *resp; 1600 1601 #ifdef WIN32 1602 WSAPROTOCOL_INFOW info; 1603 g_autofree char *info64 = NULL; 1604 SOCKET s; 1605 1606 assert(fd_is_socket(fd)); 1607 s = _get_osfhandle(fd); 1608 if (WSADuplicateSocketW(s, GetProcessId((HANDLE)qts->qemu_pid), &info) == SOCKET_ERROR) { 1609 g_autofree char *emsg = g_win32_error_message(WSAGetLastError()); 1610 g_error("WSADuplicateSocketW failed: %s", emsg); 1611 } 1612 info64 = g_base64_encode((guchar *)&info, sizeof(info)); 1613 resp = qtest_qmp(qts, "{'execute': 'get-win32-socket'," 1614 "'arguments': {'fdname': 'fdname', 'info': %s}}", info64); 1615 #else 1616 resp = qtest_qmp_fds(qts, &fd, 1, "{'execute': 'getfd'," 1617 "'arguments': {'fdname': 'fdname'}}"); 1618 #endif 1619 g_assert(resp); 1620 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */ 1621 g_assert(!qdict_haskey(resp, "error")); 1622 qobject_unref(resp); 1623 1624 resp = qtest_qmp( 1625 qts, "{'execute': 'add_client'," 1626 "'arguments': {'protocol': %s, 'fdname': 'fdname'}}", protocol); 1627 g_assert(resp); 1628 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */ 1629 g_assert(!qdict_haskey(resp, "error")); 1630 qobject_unref(resp); 1631 } 1632 1633 /* 1634 * Generic hot-unplugging test via the device_del QMP command. 1635 * Device deletion will get one response and one event. For example: 1636 * 1637 * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}} 1638 * 1639 * will get this one: 1640 * 1641 * {"timestamp": {"seconds": 1505289667, "microseconds": 569862}, 1642 * "event": "DEVICE_DELETED", "data": {"device": "scsi-hd", 1643 * "path": "/machine/peripheral/scsi-hd"}} 1644 * 1645 * and this one: 1646 * 1647 * {"return": {}} 1648 */ 1649 void qtest_qmp_device_del_send(QTestState *qts, const char *id) 1650 { 1651 QDict *rsp = qtest_qmp(qts, "{'execute': 'device_del', " 1652 "'arguments': {'id': %s}}", id); 1653 g_assert(rsp); 1654 g_assert(qdict_haskey(rsp, "return")); 1655 g_assert(!qdict_haskey(rsp, "error")); 1656 qobject_unref(rsp); 1657 } 1658 1659 void qtest_qmp_device_del(QTestState *qts, const char *id) 1660 { 1661 qtest_qmp_device_del_send(qts, id); 1662 qtest_qmp_eventwait(qts, "DEVICE_DELETED"); 1663 } 1664 1665 static void qtest_client_set_tx_handler(QTestState *s, 1666 QTestSendFn send) 1667 { 1668 s->ops.send = send; 1669 } 1670 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv) 1671 { 1672 s->ops.recv_line = recv; 1673 } 1674 /* A type-safe wrapper for s->send() */ 1675 static void send_wrapper(QTestState *s, const char *buf) 1676 { 1677 s->ops.external_send(s, buf); 1678 } 1679 1680 static GString *qtest_client_inproc_recv_line(QTestState *s) 1681 { 1682 GString *line; 1683 size_t offset; 1684 char *eol; 1685 1686 eol = strchr(s->rx->str, '\n'); 1687 offset = eol - s->rx->str; 1688 line = g_string_new_len(s->rx->str, offset); 1689 g_string_erase(s->rx, 0, offset + 1); 1690 return line; 1691 } 1692 1693 QTestState *qtest_inproc_init(QTestState **s, bool log, const char* arch, 1694 void (*send)(void*, const char*)) 1695 { 1696 QTestState *qts; 1697 qts = g_new0(QTestState, 1); 1698 qts->pending_events = NULL; 1699 *s = qts; /* Expose qts early on, since the query endianness relies on it */ 1700 qts->wstatus = 0; 1701 for (int i = 0; i < MAX_IRQ; i++) { 1702 qts->irq_level[i] = false; 1703 } 1704 1705 qtest_client_set_rx_handler(qts, qtest_client_inproc_recv_line); 1706 1707 /* send() may not have a matching prototype, so use a type-safe wrapper */ 1708 qts->ops.external_send = send; 1709 qtest_client_set_tx_handler(qts, send_wrapper); 1710 1711 qts->big_endian = qtest_query_target_endianness(qts); 1712 1713 /* 1714 * Set a dummy path for QTEST_QEMU_BINARY. Doesn't need to exist, but this 1715 * way, qtest_get_arch works for inproc qtest. 1716 */ 1717 gchar *bin_path = g_strconcat("/qemu-system-", arch, NULL); 1718 g_setenv("QTEST_QEMU_BINARY", bin_path, 0); 1719 g_free(bin_path); 1720 1721 return qts; 1722 } 1723 1724 void qtest_client_inproc_recv(void *opaque, const char *str) 1725 { 1726 QTestState *qts = *(QTestState **)opaque; 1727 1728 if (!qts->rx) { 1729 qts->rx = g_string_new(NULL); 1730 } 1731 g_string_append(qts->rx, str); 1732 return; 1733 } 1734 1735 void qtest_qom_set_bool(QTestState *s, const char *path, const char *property, 1736 bool value) 1737 { 1738 QDict *r; 1739 1740 r = qtest_qmp(s, "{ 'execute': 'qom-set', 'arguments': " 1741 "{ 'path': %s, 'property': %s, 'value': %i } }", 1742 path, property, value); 1743 qobject_unref(r); 1744 } 1745 1746 bool qtest_qom_get_bool(QTestState *s, const char *path, const char *property) 1747 { 1748 QDict *r; 1749 bool b; 1750 1751 r = qtest_qmp(s, "{ 'execute': 'qom-get', 'arguments': " 1752 "{ 'path': %s, 'property': %s } }", path, property); 1753 b = qdict_get_bool(r, "return"); 1754 qobject_unref(r); 1755 1756 return b; 1757 } 1758 1759 bool have_qemu_img(void) 1760 { 1761 char *rpath; 1762 const char *path = getenv("QTEST_QEMU_IMG"); 1763 if (!path) { 1764 return false; 1765 } 1766 1767 rpath = realpath(path, NULL); 1768 if (!rpath) { 1769 return false; 1770 } else { 1771 free(rpath); 1772 return true; 1773 } 1774 } 1775 1776 bool mkimg(const char *file, const char *fmt, unsigned size_mb) 1777 { 1778 gchar *cli; 1779 bool ret; 1780 int rc; 1781 GError *err = NULL; 1782 char *qemu_img_path; 1783 gchar *out, *out2; 1784 char *qemu_img_abs_path; 1785 1786 qemu_img_path = getenv("QTEST_QEMU_IMG"); 1787 if (!qemu_img_path) { 1788 return false; 1789 } 1790 qemu_img_abs_path = realpath(qemu_img_path, NULL); 1791 if (!qemu_img_abs_path) { 1792 return false; 1793 } 1794 1795 cli = g_strdup_printf("%s create -f %s %s %uM", qemu_img_abs_path, 1796 fmt, file, size_mb); 1797 ret = g_spawn_command_line_sync(cli, &out, &out2, &rc, &err); 1798 if (err || !g_spawn_check_exit_status(rc, &err)) { 1799 fprintf(stderr, "%s\n", err->message); 1800 g_error_free(err); 1801 } 1802 1803 g_free(out); 1804 g_free(out2); 1805 g_free(cli); 1806 free(qemu_img_abs_path); 1807 1808 return ret && !err; 1809 } 1810