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