tests/qtest: migration: Add migrate_incoming_qmp helper
[qemu/armbru.git] / tests / qtest / libqtest.c
blob3f94a4f4773aa374342214e46c9c9c1353c553d3
1 /*
2 * QTest
4 * Copyright IBM, Corp. 2012
5 * Copyright Red Hat, Inc. 2012
6 * Copyright SUSE LINUX Products GmbH 2013
8 * Authors:
9 * Anthony Liguori <aliguori@us.ibm.com>
10 * Paolo Bonzini <pbonzini@redhat.com>
11 * Andreas Färber <afaerber@suse.de>
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.
17 #include "qemu/osdep.h"
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__ */
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"
41 #define MAX_IRQ 256
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
55 #define WAITPID_TIMEOUT 30
57 typedef void (*QTestSendFn)(QTestState *s, const char *buf);
58 typedef void (*ExternalSendFn)(void *s, const char *buf);
59 typedef GString* (*QTestRecvFn)(QTestState *);
61 typedef struct QTestClientTransportOps {
62 QTestSendFn send; /* for sending qtest commands */
65 * use external_send to send qtest command strings through functions which
66 * do not accept a QTestState as the first parameter.
68 ExternalSendFn external_send;
70 QTestRecvFn recv_line; /* for receiving qtest command responses */
71 } QTestTransportOps;
73 struct QTestState
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;
92 static GHookList abrt_hooks;
93 static void (*sighandler_old)(int);
95 static int qtest_query_target_endianness(QTestState *s);
97 static void qtest_client_socket_send(QTestState*, const char *buf);
98 static void socket_send(int fd, const char *buf, size_t size);
100 static GString *qtest_client_socket_recv_line(QTestState *);
102 static void qtest_client_set_tx_handler(QTestState *s, QTestSendFn send);
103 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv);
105 static int init_socket(const char *socket_path)
107 int sock = qtest_socket_server(socket_path);
108 qemu_set_cloexec(sock);
109 return sock;
112 static int socket_accept(int sock)
114 struct sockaddr_un addr;
115 socklen_t addrlen;
116 int ret;
118 * timeout unit of blocking receive calls is different among platforms.
119 * It's in seconds on non-Windows platforms but milliseconds on Windows.
121 #ifndef _WIN32
122 struct timeval timeout = { .tv_sec = SOCKET_TIMEOUT,
123 .tv_usec = 0 };
124 #else
125 DWORD timeout = SOCKET_TIMEOUT;
126 #endif
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;
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));
143 close(sock);
145 return ret;
148 pid_t qtest_pid(QTestState *s)
150 return s->qemu_pid;
153 bool qtest_probe_child(QTestState *s)
155 pid_t pid = s->qemu_pid;
157 if (pid != -1) {
158 #ifndef _WIN32
159 pid = waitpid(pid, &s->wstatus, WNOHANG);
160 if (pid == 0) {
161 return true;
163 #else
164 GetExitCodeProcess((HANDLE)pid, &s->exit_code);
165 if (s->exit_code == STILL_ACTIVE) {
166 return true;
168 CloseHandle((HANDLE)pid);
169 #endif
170 s->qemu_pid = -1;
171 qtest_remove_abrt_handler(s);
173 return false;
176 void qtest_set_expected_status(QTestState *s, int status)
178 s->expected_status = status;
181 static void qtest_check_status(QTestState *s)
183 assert(s->qemu_pid == -1);
186 * Check whether qemu exited with expected exit status; anything else is
187 * fishy and should be logged with as much detail as possible.
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)" : "";
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();
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();
213 #endif
216 void qtest_wait_qemu(QTestState *s)
218 if (s->qemu_pid != -1) {
219 #ifndef _WIN32
220 pid_t pid;
221 uint64_t end;
223 /* poll for a while until sending SIGKILL */
224 end = g_get_monotonic_time() + WAITPID_TIMEOUT * G_TIME_SPAN_SECOND;
226 do {
227 pid = waitpid(s->qemu_pid, &s->wstatus, WNOHANG);
228 if (pid != 0) {
229 break;
231 g_usleep(100 * 1000);
232 } while (g_get_monotonic_time() < end);
234 if (pid == 0) {
235 kill(s->qemu_pid, SIGKILL);
236 pid = RETRY_ON_EINTR(waitpid(s->qemu_pid, &s->wstatus, 0));
239 assert(pid == s->qemu_pid);
240 #else
241 DWORD ret;
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
249 s->qemu_pid = -1;
250 qtest_remove_abrt_handler(s);
252 qtest_check_status(s);
255 void qtest_kill_qemu(QTestState *s)
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;
268 qtest_check_status(s);
271 static void kill_qemu_hook_func(void *s)
273 qtest_kill_qemu(s);
276 static void sigabrt_handler(int signo)
278 g_hook_list_invoke(&abrt_hooks, FALSE);
281 static void setup_sigabrt_handler(void)
283 sighandler_old = signal(SIGABRT, sigabrt_handler);
286 static void cleanup_sigabrt_handler(void)
288 signal(SIGABRT, sighandler_old);
291 static bool hook_list_is_empty(GHookList *hook_list)
293 GHook *hook = g_hook_first_valid(hook_list, TRUE);
295 if (!hook) {
296 return true;
299 g_hook_unref(hook_list, hook);
300 return false;
303 void qtest_add_abrt_handler(GHookFunc fn, const void *data)
305 GHook *hook;
307 if (!abrt_hooks.is_setup) {
308 g_hook_list_init(&abrt_hooks, sizeof(GHook));
311 /* Only install SIGABRT handler once */
312 if (hook_list_is_empty(&abrt_hooks)) {
313 setup_sigabrt_handler();
316 hook = g_hook_alloc(&abrt_hooks);
317 hook->func = fn;
318 hook->data = (void *)data;
320 g_hook_prepend(&abrt_hooks, hook);
323 void qtest_remove_abrt_handler(void *data)
325 GHook *hook = g_hook_find_data(&abrt_hooks, TRUE, data);
327 if (!hook) {
328 return;
331 g_hook_destroy_link(&abrt_hooks, hook);
333 /* Uninstall SIGABRT handler on last instance */
334 if (hook_list_is_empty(&abrt_hooks)) {
335 cleanup_sigabrt_handler();
339 static const char *qtest_qemu_binary(void)
341 const char *qemu_bin;
343 qemu_bin = getenv("QTEST_QEMU_BINARY");
344 if (!qemu_bin) {
345 fprintf(stderr, "Environment variable QTEST_QEMU_BINARY required\n");
346 exit(1);
349 return qemu_bin;
352 #ifdef _WIN32
353 static pid_t qtest_create_process(char *cmd)
355 STARTUPINFO si;
356 PROCESS_INFORMATION pi;
357 BOOL ret;
359 ZeroMemory(&si, sizeof(si));
360 si.cb = sizeof(si);
361 ZeroMemory(&pi, sizeof(pi));
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 */
374 if (ret == 0) {
375 fprintf(stderr, "%s:%d: unable to create a new process (%s)\n",
376 __FILE__, __LINE__, strerror(GetLastError()));
377 abort();
380 return (pid_t)pi.hProcess;
382 #endif /* _WIN32 */
384 static QTestState *G_GNUC_PRINTF(1, 2) qtest_spawn_qemu(const char *fmt, ...)
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("");
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);
399 qtest_add_abrt_handler(kill_qemu_hook_func, s);
401 g_test_message("starting QEMU: %s", command->str);
403 #ifndef _WIN32
404 s->qemu_pid = fork();
405 if (s->qemu_pid == 0) {
406 #ifdef __linux__
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.
415 * This PR_SET_PDEATHSIG setup will ensure any remaining
416 * QEMU will get terminated with SIGKILL in these cases.
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 execlp("/bin/sh", "sh", "-c", command->str, NULL);
425 exit(1);
427 #else
428 s->qemu_pid = qtest_create_process(command->str);
429 #endif /* _WIN32 */
431 return s;
434 QTestState *qtest_init_without_qmp_handshake(const char *extra_args)
436 QTestState *s;
437 int sock, qmpsock, i;
438 gchar *socket_path;
439 gchar *qmp_socket_path;
441 socket_path = g_strdup_printf("%s/qtest-%d.sock",
442 g_get_tmp_dir(), getpid());
443 qmp_socket_path = g_strdup_printf("%s/qtest-%d.qmp",
444 g_get_tmp_dir(), getpid());
447 * It's possible that if an earlier test run crashed it might
448 * have left a stale unix socket lying around. Delete any
449 * stale old socket to avoid spurious test failures with
450 * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1)
452 unlink(socket_path);
453 unlink(qmp_socket_path);
455 socket_init();
456 sock = init_socket(socket_path);
457 qmpsock = init_socket(qmp_socket_path);
459 s = qtest_spawn_qemu("-qtest unix:%s "
460 "-qtest-log %s "
461 "-chardev socket,path=%s,id=char0 "
462 "-mon chardev=char0,mode=control "
463 "-display none "
464 "-audio none "
465 "%s"
466 " -accel qtest",
467 socket_path,
468 getenv("QTEST_LOG") ? DEV_STDERR : DEV_NULL,
469 qmp_socket_path,
470 extra_args ?: "");
472 qtest_client_set_rx_handler(s, qtest_client_socket_recv_line);
473 qtest_client_set_tx_handler(s, qtest_client_socket_send);
475 s->fd = socket_accept(sock);
476 if (s->fd >= 0) {
477 s->qmp_fd = socket_accept(qmpsock);
479 unlink(socket_path);
480 unlink(qmp_socket_path);
481 g_free(socket_path);
482 g_free(qmp_socket_path);
484 g_assert(s->fd >= 0 && s->qmp_fd >= 0);
486 s->rx = g_string_new("");
487 for (i = 0; i < MAX_IRQ; i++) {
488 s->irq_level[i] = false;
492 * Stopping QEMU for debugging is not supported on Windows.
494 * Using DebugActiveProcess() API can suspend the QEMU process,
495 * but gdb cannot attach to the process. Using the undocumented
496 * NtSuspendProcess() can suspend the QEMU process and gdb can
497 * attach to the process, but gdb cannot resume it.
499 #ifndef _WIN32
500 if (getenv("QTEST_STOP")) {
501 kill(s->qemu_pid, SIGSTOP);
503 #endif
505 /* ask endianness of the target */
507 s->big_endian = qtest_query_target_endianness(s);
509 return s;
512 QTestState *qtest_init(const char *extra_args)
514 QTestState *s = qtest_init_without_qmp_handshake(extra_args);
515 QDict *greeting;
517 /* Read the QMP greeting and then do the handshake */
518 greeting = qtest_qmp_receive(s);
519 qobject_unref(greeting);
520 qobject_unref(qtest_qmp(s, "{ 'execute': 'qmp_capabilities' }"));
522 return s;
525 QTestState *qtest_vinitf(const char *fmt, va_list ap)
527 char *args = g_strdup_vprintf(fmt, ap);
528 QTestState *s;
530 s = qtest_init(args);
531 g_free(args);
532 return s;
535 QTestState *qtest_initf(const char *fmt, ...)
537 va_list ap;
538 QTestState *s;
540 va_start(ap, fmt);
541 s = qtest_vinitf(fmt, ap);
542 va_end(ap);
543 return s;
546 QTestState *qtest_init_with_serial(const char *extra_args, int *sock_fd)
548 int sock_fd_init;
549 g_autofree char *sock_dir = NULL;
550 char *sock_path;
551 QTestState *qts;
553 sock_dir = g_dir_make_tmp("qtest-serial-XXXXXX", NULL);
554 g_assert_true(sock_dir != NULL);
555 sock_path = g_strdup_printf("%s/sock", sock_dir);
557 socket_init();
558 sock_fd_init = init_socket(sock_path);
560 qts = qtest_initf("-chardev socket,id=s0,path=%s -serial chardev:s0 %s",
561 sock_path, extra_args);
563 *sock_fd = socket_accept(sock_fd_init);
565 unlink(sock_path);
566 g_free(sock_path);
567 rmdir(sock_dir);
569 g_assert_true(*sock_fd >= 0);
571 return qts;
574 void qtest_quit(QTestState *s)
576 qtest_remove_abrt_handler(s);
578 qtest_kill_qemu(s);
579 close(s->fd);
580 close(s->qmp_fd);
581 g_string_free(s->rx, true);
583 for (GList *it = s->pending_events; it != NULL; it = it->next) {
584 qobject_unref((QDict *)it->data);
587 g_list_free(s->pending_events);
589 g_free(s);
592 static void socket_send(int fd, const char *buf, size_t size)
594 ssize_t res = qemu_send_full(fd, buf, size);
596 assert(res == size);
599 static void qtest_client_socket_send(QTestState *s, const char *buf)
601 socket_send(s->fd, buf, strlen(buf));
604 static void G_GNUC_PRINTF(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...)
606 va_list ap;
608 va_start(ap, fmt);
609 gchar *str = g_strdup_vprintf(fmt, ap);
610 va_end(ap);
612 s->ops.send(s, str);
613 g_free(str);
616 static GString *qtest_client_socket_recv_line(QTestState *s)
618 GString *line;
619 size_t offset;
620 char *eol;
622 while ((eol = strchr(s->rx->str, '\n')) == NULL) {
623 ssize_t len;
624 char buffer[1024];
626 len = recv(s->fd, buffer, sizeof(buffer), 0);
627 if (len == -1 && errno == EINTR) {
628 continue;
631 if (len == -1 || len == 0) {
632 fprintf(stderr, "Broken pipe\n");
633 abort();
636 g_string_append_len(s->rx, buffer, len);
639 offset = eol - s->rx->str;
640 line = g_string_new_len(s->rx->str, offset);
641 g_string_erase(s->rx, 0, offset + 1);
643 return line;
646 static gchar **qtest_rsp_args(QTestState *s, int expected_args)
648 GString *line;
649 gchar **words;
650 int i;
652 redo:
653 line = s->ops.recv_line(s);
654 words = g_strsplit(line->str, " ", 0);
655 g_string_free(line, TRUE);
657 if (strcmp(words[0], "IRQ") == 0) {
658 long irq;
659 int ret;
661 g_assert(words[1] != NULL);
662 g_assert(words[2] != NULL);
664 ret = qemu_strtol(words[2], NULL, 0, &irq);
665 g_assert(!ret);
666 g_assert_cmpint(irq, >=, 0);
667 g_assert_cmpint(irq, <, MAX_IRQ);
669 if (strcmp(words[1], "raise") == 0) {
670 s->irq_level[irq] = true;
671 } else {
672 s->irq_level[irq] = false;
675 g_strfreev(words);
676 goto redo;
679 g_assert(words[0] != NULL);
680 g_assert_cmpstr(words[0], ==, "OK");
682 for (i = 0; i < expected_args; i++) {
683 g_assert(words[i] != NULL);
686 return words;
689 static void qtest_rsp(QTestState *s)
691 gchar **words = qtest_rsp_args(s, 0);
693 g_strfreev(words);
696 static int qtest_query_target_endianness(QTestState *s)
698 gchar **args;
699 int big_endian;
701 qtest_sendf(s, "endianness\n");
702 args = qtest_rsp_args(s, 1);
703 g_assert(strcmp(args[1], "big") == 0 || strcmp(args[1], "little") == 0);
704 big_endian = strcmp(args[1], "big") == 0;
705 g_strfreev(args);
707 return big_endian;
710 QDict *qtest_qmp_receive(QTestState *s)
712 while (true) {
713 QDict *response = qtest_qmp_receive_dict(s);
715 if (!qdict_get_try_str(response, "event")) {
716 return response;
719 if (!s->eventCB ||
720 !s->eventCB(s, qdict_get_str(response, "event"),
721 response, s->eventData)) {
722 /* Stash the event for a later consumption */
723 s->pending_events = g_list_append(s->pending_events, response);
728 QDict *qtest_qmp_receive_dict(QTestState *s)
730 return qmp_fd_receive(s->qmp_fd);
733 int qtest_socket_server(const char *socket_path)
735 struct sockaddr_un addr;
736 int sock;
737 int ret;
739 sock = socket(PF_UNIX, SOCK_STREAM, 0);
740 g_assert_cmpint(sock, !=, -1);
742 addr.sun_family = AF_UNIX;
743 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
745 ret = RETRY_ON_EINTR(bind(sock, (struct sockaddr *)&addr, sizeof(addr)));
746 g_assert_cmpint(ret, !=, -1);
747 ret = listen(sock, 1);
748 g_assert_cmpint(ret, !=, -1);
750 return sock;
753 #ifndef _WIN32
754 void qtest_qmp_vsend_fds(QTestState *s, int *fds, size_t fds_num,
755 const char *fmt, va_list ap)
757 qmp_fd_vsend_fds(s->qmp_fd, fds, fds_num, fmt, ap);
759 #endif
761 void qtest_qmp_vsend(QTestState *s, const char *fmt, va_list ap)
763 qmp_fd_vsend(s->qmp_fd, fmt, ap);
766 #ifndef _WIN32
767 QDict *qtest_vqmp_fds(QTestState *s, int *fds, size_t fds_num,
768 const char *fmt, va_list ap)
770 qtest_qmp_vsend_fds(s, fds, fds_num, fmt, ap);
772 /* Receive reply */
773 return qtest_qmp_receive(s);
775 #endif
777 QDict *qtest_vqmp(QTestState *s, const char *fmt, va_list ap)
779 qtest_qmp_vsend(s, fmt, ap);
781 /* Receive reply */
782 return qtest_qmp_receive(s);
785 #ifndef _WIN32
786 QDict *qtest_qmp_fds(QTestState *s, int *fds, size_t fds_num,
787 const char *fmt, ...)
789 va_list ap;
790 QDict *response;
792 va_start(ap, fmt);
793 response = qtest_vqmp_fds(s, fds, fds_num, fmt, ap);
794 va_end(ap);
795 return response;
797 #endif
799 QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
801 va_list ap;
802 QDict *response;
804 va_start(ap, fmt);
805 response = qtest_vqmp(s, fmt, ap);
806 va_end(ap);
807 return response;
810 void qtest_qmp_send(QTestState *s, const char *fmt, ...)
812 va_list ap;
814 va_start(ap, fmt);
815 qtest_qmp_vsend(s, fmt, ap);
816 va_end(ap);
819 void qtest_qmp_send_raw(QTestState *s, const char *fmt, ...)
821 va_list ap;
823 va_start(ap, fmt);
824 qmp_fd_vsend_raw(s->qmp_fd, fmt, ap);
825 va_end(ap);
828 void qtest_qmp_set_event_callback(QTestState *s,
829 QTestQMPEventCallback cb, void *opaque)
831 s->eventCB = cb;
832 s->eventData = opaque;
835 QDict *qtest_qmp_event_ref(QTestState *s, const char *event)
837 while (s->pending_events) {
839 GList *first = s->pending_events;
840 QDict *response = (QDict *)first->data;
842 s->pending_events = g_list_delete_link(s->pending_events, first);
844 if (!strcmp(qdict_get_str(response, "event"), event)) {
845 return response;
847 qobject_unref(response);
849 return NULL;
852 QDict *qtest_qmp_eventwait_ref(QTestState *s, const char *event)
854 QDict *response = qtest_qmp_event_ref(s, event);
856 if (response) {
857 return response;
860 for (;;) {
861 response = qtest_qmp_receive_dict(s);
862 if ((qdict_haskey(response, "event")) &&
863 (strcmp(qdict_get_str(response, "event"), event) == 0)) {
864 return response;
866 qobject_unref(response);
870 void qtest_qmp_eventwait(QTestState *s, const char *event)
872 QDict *response;
874 response = qtest_qmp_eventwait_ref(s, event);
875 qobject_unref(response);
878 char *qtest_vhmp(QTestState *s, const char *fmt, va_list ap)
880 char *cmd;
881 QDict *resp;
882 char *ret;
884 cmd = g_strdup_vprintf(fmt, ap);
885 resp = qtest_qmp(s, "{'execute': 'human-monitor-command',"
886 " 'arguments': {'command-line': %s}}",
887 cmd);
888 ret = g_strdup(qdict_get_try_str(resp, "return"));
889 g_assert(ret);
890 qobject_unref(resp);
891 g_free(cmd);
892 return ret;
895 char *qtest_hmp(QTestState *s, const char *fmt, ...)
897 va_list ap;
898 char *ret;
900 va_start(ap, fmt);
901 ret = qtest_vhmp(s, fmt, ap);
902 va_end(ap);
903 return ret;
906 const char *qtest_get_arch(void)
908 const char *qemu = qtest_qemu_binary();
909 const char *end = strrchr(qemu, '-');
911 if (!end) {
912 fprintf(stderr, "Can't determine architecture from binary name.\n");
913 exit(1);
916 if (!strstr(qemu, "-system-")) {
917 fprintf(stderr, "QTEST_QEMU_BINARY must end with *-system-<arch> "
918 "where 'arch' is the target\narchitecture (x86_64, aarch64, "
919 "etc).\n");
920 exit(1);
923 return end + 1;
926 bool qtest_has_accel(const char *accel_name)
928 if (g_str_equal(accel_name, "tcg")) {
929 #if defined(CONFIG_TCG)
930 return true;
931 #else
932 return false;
933 #endif
934 } else if (g_str_equal(accel_name, "kvm")) {
935 int i;
936 const char *arch = qtest_get_arch();
937 const char *targets[] = { CONFIG_KVM_TARGETS };
939 for (i = 0; i < ARRAY_SIZE(targets); i++) {
940 if (!strncmp(targets[i], arch, strlen(arch))) {
941 if (!access("/dev/kvm", R_OK | W_OK)) {
942 return true;
946 } else {
947 /* not implemented */
948 g_assert_not_reached();
950 return false;
953 bool qtest_get_irq(QTestState *s, int num)
955 /* dummy operation in order to make sure irq is up to date */
956 qtest_inb(s, 0);
958 return s->irq_level[num];
961 void qtest_module_load(QTestState *s, const char *prefix, const char *libname)
963 qtest_sendf(s, "module_load %s %s\n", prefix, libname);
964 qtest_rsp(s);
967 static int64_t qtest_clock_rsp(QTestState *s)
969 gchar **words;
970 int64_t clock;
971 words = qtest_rsp_args(s, 2);
972 clock = g_ascii_strtoll(words[1], NULL, 0);
973 g_strfreev(words);
974 return clock;
977 int64_t qtest_clock_step_next(QTestState *s)
979 qtest_sendf(s, "clock_step\n");
980 return qtest_clock_rsp(s);
983 int64_t qtest_clock_step(QTestState *s, int64_t step)
985 qtest_sendf(s, "clock_step %"PRIi64"\n", step);
986 return qtest_clock_rsp(s);
989 int64_t qtest_clock_set(QTestState *s, int64_t val)
991 qtest_sendf(s, "clock_set %"PRIi64"\n", val);
992 return qtest_clock_rsp(s);
995 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
997 qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
998 qtest_rsp(s);
1001 void qtest_irq_intercept_out_named(QTestState *s, const char *qom_path, const char *name)
1003 qtest_sendf(s, "irq_intercept_out %s %s\n", qom_path, name);
1004 qtest_rsp(s);
1007 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
1009 qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
1010 qtest_rsp(s);
1013 void qtest_set_irq_in(QTestState *s, const char *qom_path, const char *name,
1014 int num, int level)
1016 if (!name) {
1017 name = "unnamed-gpio-in";
1019 qtest_sendf(s, "set_irq_in %s %s %d %d\n", qom_path, name, num, level);
1020 qtest_rsp(s);
1023 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
1025 qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
1026 qtest_rsp(s);
1029 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
1031 qtest_out(s, "outb", addr, value);
1034 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
1036 qtest_out(s, "outw", addr, value);
1039 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
1041 qtest_out(s, "outl", addr, value);
1044 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
1046 gchar **args;
1047 int ret;
1048 unsigned long value;
1050 qtest_sendf(s, "%s 0x%x\n", cmd, addr);
1051 args = qtest_rsp_args(s, 2);
1052 ret = qemu_strtoul(args[1], NULL, 0, &value);
1053 g_assert(!ret && value <= UINT32_MAX);
1054 g_strfreev(args);
1056 return value;
1059 uint8_t qtest_inb(QTestState *s, uint16_t addr)
1061 return qtest_in(s, "inb", addr);
1064 uint16_t qtest_inw(QTestState *s, uint16_t addr)
1066 return qtest_in(s, "inw", addr);
1069 uint32_t qtest_inl(QTestState *s, uint16_t addr)
1071 return qtest_in(s, "inl", addr);
1074 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
1075 uint64_t value)
1077 qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
1078 qtest_rsp(s);
1081 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
1083 qtest_write(s, "writeb", addr, value);
1086 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
1088 qtest_write(s, "writew", addr, value);
1091 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
1093 qtest_write(s, "writel", addr, value);
1096 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
1098 qtest_write(s, "writeq", addr, value);
1101 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
1103 gchar **args;
1104 int ret;
1105 uint64_t value;
1107 qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
1108 args = qtest_rsp_args(s, 2);
1109 ret = qemu_strtou64(args[1], NULL, 0, &value);
1110 g_assert(!ret);
1111 g_strfreev(args);
1113 return value;
1116 uint8_t qtest_readb(QTestState *s, uint64_t addr)
1118 return qtest_read(s, "readb", addr);
1121 uint16_t qtest_readw(QTestState *s, uint64_t addr)
1123 return qtest_read(s, "readw", addr);
1126 uint32_t qtest_readl(QTestState *s, uint64_t addr)
1128 return qtest_read(s, "readl", addr);
1131 uint64_t qtest_readq(QTestState *s, uint64_t addr)
1133 return qtest_read(s, "readq", addr);
1136 static int hex2nib(char ch)
1138 if (ch >= '0' && ch <= '9') {
1139 return ch - '0';
1140 } else if (ch >= 'a' && ch <= 'f') {
1141 return 10 + (ch - 'a');
1142 } else if (ch >= 'A' && ch <= 'F') {
1143 return 10 + (ch - 'a');
1144 } else {
1145 return -1;
1149 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
1151 uint8_t *ptr = data;
1152 gchar **args;
1153 size_t i;
1155 if (!size) {
1156 return;
1159 qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
1160 args = qtest_rsp_args(s, 2);
1162 for (i = 0; i < size; i++) {
1163 ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
1164 ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
1167 g_strfreev(args);
1170 uint64_t qtest_rtas_call(QTestState *s, const char *name,
1171 uint32_t nargs, uint64_t args,
1172 uint32_t nret, uint64_t ret)
1174 qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n",
1175 name, nargs, args, nret, ret);
1176 qtest_rsp(s);
1177 return 0;
1180 void qtest_add_func(const char *str, void (*fn)(void))
1182 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1183 g_test_add_func(path, fn);
1184 g_free(path);
1187 void qtest_add_data_func_full(const char *str, void *data,
1188 void (*fn)(const void *),
1189 GDestroyNotify data_free_func)
1191 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1192 g_test_add_data_func_full(path, data, fn, data_free_func);
1193 g_free(path);
1196 void qtest_add_data_func(const char *str, const void *data,
1197 void (*fn)(const void *))
1199 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1200 g_test_add_data_func(path, data, fn);
1201 g_free(path);
1204 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1206 gchar *bdata;
1208 bdata = g_base64_encode(data, size);
1209 qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
1210 s->ops.send(s, bdata);
1211 s->ops.send(s, "\n");
1212 qtest_rsp(s);
1213 g_free(bdata);
1216 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
1218 gchar **args;
1219 size_t len;
1221 qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
1222 args = qtest_rsp_args(s, 2);
1224 g_base64_decode_inplace(args[1], &len);
1225 if (size != len) {
1226 fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
1227 size, len);
1228 len = MIN(len, size);
1231 memcpy(data, args[1], len);
1232 g_strfreev(args);
1235 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1237 const uint8_t *ptr = data;
1238 size_t i;
1239 char *enc;
1241 if (!size) {
1242 return;
1245 enc = g_malloc(2 * size + 1);
1247 for (i = 0; i < size; i++) {
1248 sprintf(&enc[i * 2], "%02x", ptr[i]);
1251 qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
1252 qtest_rsp(s);
1253 g_free(enc);
1256 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
1258 qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
1259 qtest_rsp(s);
1262 QDict *qtest_vqmp_assert_success_ref(QTestState *qts,
1263 const char *fmt, va_list args)
1265 QDict *response;
1266 QDict *ret;
1268 response = qtest_vqmp(qts, fmt, args);
1270 g_assert(response);
1271 if (!qdict_haskey(response, "return")) {
1272 g_autoptr(GString) s = qobject_to_json_pretty(QOBJECT(response), true);
1273 g_test_message("%s", s->str);
1275 g_assert(qdict_haskey(response, "return"));
1276 ret = qdict_get_qdict(response, "return");
1277 qobject_ref(ret);
1278 qobject_unref(response);
1280 return ret;
1283 void qtest_vqmp_assert_success(QTestState *qts,
1284 const char *fmt, va_list args)
1286 QDict *response;
1288 response = qtest_vqmp_assert_success_ref(qts, fmt, args);
1290 qobject_unref(response);
1293 #ifndef _WIN32
1294 QDict *qtest_vqmp_fds_assert_success_ref(QTestState *qts, int *fds, size_t nfds,
1295 const char *fmt, va_list args)
1297 QDict *response;
1298 QDict *ret;
1300 response = qtest_vqmp_fds(qts, fds, nfds, fmt, args);
1302 g_assert(response);
1303 if (!qdict_haskey(response, "return")) {
1304 g_autoptr(GString) s = qobject_to_json_pretty(QOBJECT(response), true);
1305 g_test_message("%s", s->str);
1307 g_assert(qdict_haskey(response, "return"));
1308 ret = qdict_get_qdict(response, "return");
1309 qobject_ref(ret);
1310 qobject_unref(response);
1312 return ret;
1315 void qtest_vqmp_fds_assert_success(QTestState *qts, int *fds, size_t nfds,
1316 const char *fmt, va_list args)
1318 QDict *response;
1319 response = qtest_vqmp_fds_assert_success_ref(qts, fds, nfds, fmt, args);
1320 qobject_unref(response);
1322 #endif /* !_WIN32 */
1324 QDict *qtest_qmp_assert_success_ref(QTestState *qts, const char *fmt, ...)
1326 QDict *response;
1327 va_list ap;
1328 va_start(ap, fmt);
1329 response = qtest_vqmp_assert_success_ref(qts, fmt, ap);
1330 va_end(ap);
1331 return response;
1334 void qtest_qmp_assert_success(QTestState *qts, const char *fmt, ...)
1336 va_list ap;
1337 va_start(ap, fmt);
1338 qtest_vqmp_assert_success(qts, fmt, ap);
1339 va_end(ap);
1342 #ifndef _WIN32
1343 QDict *qtest_qmp_fds_assert_success_ref(QTestState *qts, int *fds, size_t nfds,
1344 const char *fmt, ...)
1346 QDict *response;
1347 va_list ap;
1348 va_start(ap, fmt);
1349 response = qtest_vqmp_fds_assert_success_ref(qts, fds, nfds, fmt, ap);
1350 va_end(ap);
1351 return response;
1354 void qtest_qmp_fds_assert_success(QTestState *qts, int *fds, size_t nfds,
1355 const char *fmt, ...)
1357 va_list ap;
1358 va_start(ap, fmt);
1359 qtest_vqmp_fds_assert_success(qts, fds, nfds, fmt, ap);
1360 va_end(ap);
1362 #endif /* !_WIN32 */
1364 bool qtest_big_endian(QTestState *s)
1366 return s->big_endian;
1369 static bool qtest_check_machine_version(const char *mname, const char *basename,
1370 int major, int minor)
1372 char *newname;
1373 bool is_equal;
1375 newname = g_strdup_printf("%s-%i.%i", basename, major, minor);
1376 is_equal = g_str_equal(mname, newname);
1377 g_free(newname);
1379 return is_equal;
1382 static bool qtest_is_old_versioned_machine(const char *mname)
1384 const char *dash = strrchr(mname, '-');
1385 const char *dot = strrchr(mname, '.');
1386 const char *chr;
1387 char *bname;
1388 const int major = QEMU_VERSION_MAJOR;
1389 const int minor = QEMU_VERSION_MINOR;
1390 bool res = false;
1392 if (dash && dot && dot > dash) {
1393 for (chr = dash + 1; *chr; chr++) {
1394 if (!qemu_isdigit(*chr) && *chr != '.') {
1395 return false;
1399 * Now check if it is one of the latest versions. Check major + 1
1400 * and minor + 1 versions as well, since they might already exist
1401 * in the development branch.
1403 bname = g_strdup(mname);
1404 bname[dash - mname] = 0;
1405 res = !qtest_check_machine_version(mname, bname, major + 1, 0) &&
1406 !qtest_check_machine_version(mname, bname, major, minor + 1) &&
1407 !qtest_check_machine_version(mname, bname, major, minor);
1408 g_free(bname);
1411 return res;
1414 struct MachInfo {
1415 char *name;
1416 char *alias;
1420 * Returns an array with pointers to the available machine names.
1421 * The terminating entry has the name set to NULL.
1423 static struct MachInfo *qtest_get_machines(void)
1425 static struct MachInfo *machines;
1426 QDict *response, *minfo;
1427 QList *list;
1428 const QListEntry *p;
1429 QObject *qobj;
1430 QString *qstr;
1431 QTestState *qts;
1432 int idx;
1434 if (machines) {
1435 return machines;
1438 qts = qtest_init("-machine none");
1439 response = qtest_qmp(qts, "{ 'execute': 'query-machines' }");
1440 g_assert(response);
1441 list = qdict_get_qlist(response, "return");
1442 g_assert(list);
1444 machines = g_new(struct MachInfo, qlist_size(list) + 1);
1446 for (p = qlist_first(list), idx = 0; p; p = qlist_next(p), idx++) {
1447 minfo = qobject_to(QDict, qlist_entry_obj(p));
1448 g_assert(minfo);
1450 qobj = qdict_get(minfo, "name");
1451 g_assert(qobj);
1452 qstr = qobject_to(QString, qobj);
1453 g_assert(qstr);
1454 machines[idx].name = g_strdup(qstring_get_str(qstr));
1456 qobj = qdict_get(minfo, "alias");
1457 if (qobj) { /* The alias is optional */
1458 qstr = qobject_to(QString, qobj);
1459 g_assert(qstr);
1460 machines[idx].alias = g_strdup(qstring_get_str(qstr));
1461 } else {
1462 machines[idx].alias = NULL;
1466 qtest_quit(qts);
1467 qobject_unref(response);
1469 memset(&machines[idx], 0, sizeof(struct MachInfo)); /* Terminating entry */
1470 return machines;
1473 void qtest_cb_for_every_machine(void (*cb)(const char *machine),
1474 bool skip_old_versioned)
1476 struct MachInfo *machines;
1477 int i;
1479 machines = qtest_get_machines();
1481 for (i = 0; machines[i].name != NULL; i++) {
1482 /* Ignore machines that cannot be used for qtests */
1483 if (!strncmp("xenfv", machines[i].name, 5) ||
1484 g_str_equal("xenpv", machines[i].name) ||
1485 g_str_equal("xenpvh", machines[i].name)) {
1486 continue;
1488 if (!skip_old_versioned ||
1489 !qtest_is_old_versioned_machine(machines[i].name)) {
1490 cb(machines[i].name);
1495 bool qtest_has_machine(const char *machine)
1497 struct MachInfo *machines;
1498 int i;
1500 machines = qtest_get_machines();
1502 for (i = 0; machines[i].name != NULL; i++) {
1503 if (g_str_equal(machine, machines[i].name) ||
1504 (machines[i].alias && g_str_equal(machine, machines[i].alias))) {
1505 return true;
1509 return false;
1512 bool qtest_has_device(const char *device)
1514 static QList *list;
1515 const QListEntry *p;
1516 QObject *qobj;
1517 QString *qstr;
1518 QDict *devinfo;
1519 int idx;
1521 if (!list) {
1522 QDict *resp;
1523 QDict *args;
1524 QTestState *qts = qtest_init("-machine none");
1526 args = qdict_new();
1527 qdict_put_bool(args, "abstract", false);
1528 qdict_put_str(args, "implements", "device");
1530 resp = qtest_qmp(qts, "{'execute': 'qom-list-types', 'arguments': %p }",
1531 args);
1532 g_assert(qdict_haskey(resp, "return"));
1533 list = qdict_get_qlist(resp, "return");
1534 qobject_ref(list);
1535 qobject_unref(resp);
1537 qtest_quit(qts);
1540 for (p = qlist_first(list), idx = 0; p; p = qlist_next(p), idx++) {
1541 devinfo = qobject_to(QDict, qlist_entry_obj(p));
1542 g_assert(devinfo);
1544 qobj = qdict_get(devinfo, "name");
1545 g_assert(qobj);
1546 qstr = qobject_to(QString, qobj);
1547 g_assert(qstr);
1548 if (g_str_equal(qstring_get_str(qstr), device)) {
1549 return true;
1553 return false;
1557 * Generic hot-plugging test via the device_add QMP commands.
1559 void qtest_qmp_device_add_qdict(QTestState *qts, const char *drv,
1560 const QDict *arguments)
1562 QDict *resp;
1563 QDict *args = arguments ? qdict_clone_shallow(arguments) : qdict_new();
1565 g_assert(!qdict_haskey(args, "driver"));
1566 qdict_put_str(args, "driver", drv);
1567 resp = qtest_qmp(qts, "{'execute': 'device_add', 'arguments': %p}", args);
1568 g_assert(resp);
1569 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1570 if (qdict_haskey(resp, "error")) {
1571 fprintf(stderr, "error: %s\n",
1572 qdict_get_str(qdict_get_qdict(resp, "error"), "desc"));
1574 g_assert(!qdict_haskey(resp, "error"));
1575 qobject_unref(resp);
1578 void qtest_qmp_device_add(QTestState *qts, const char *driver, const char *id,
1579 const char *fmt, ...)
1581 QDict *args;
1582 va_list ap;
1584 va_start(ap, fmt);
1585 args = qdict_from_vjsonf_nofail(fmt, ap);
1586 va_end(ap);
1588 g_assert(!qdict_haskey(args, "id"));
1589 qdict_put_str(args, "id", id);
1591 qtest_qmp_device_add_qdict(qts, driver, args);
1592 qobject_unref(args);
1595 void qtest_qmp_add_client(QTestState *qts, const char *protocol, int fd)
1597 QDict *resp;
1599 #ifdef WIN32
1600 WSAPROTOCOL_INFOW info;
1601 g_autofree char *info64 = NULL;
1602 SOCKET s;
1604 assert(fd_is_socket(fd));
1605 s = _get_osfhandle(fd);
1606 if (WSADuplicateSocketW(s, GetProcessId((HANDLE)qts->qemu_pid), &info) == SOCKET_ERROR) {
1607 g_autofree char *emsg = g_win32_error_message(WSAGetLastError());
1608 g_error("WSADuplicateSocketW failed: %s", emsg);
1610 info64 = g_base64_encode((guchar *)&info, sizeof(info));
1611 resp = qtest_qmp(qts, "{'execute': 'get-win32-socket',"
1612 "'arguments': {'fdname': 'fdname', 'info': %s}}", info64);
1613 #else
1614 resp = qtest_qmp_fds(qts, &fd, 1, "{'execute': 'getfd',"
1615 "'arguments': {'fdname': 'fdname'}}");
1616 #endif
1617 g_assert(resp);
1618 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1619 g_assert(!qdict_haskey(resp, "error"));
1620 qobject_unref(resp);
1622 resp = qtest_qmp(
1623 qts, "{'execute': 'add_client',"
1624 "'arguments': {'protocol': %s, 'fdname': 'fdname'}}", protocol);
1625 g_assert(resp);
1626 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1627 g_assert(!qdict_haskey(resp, "error"));
1628 qobject_unref(resp);
1632 * Generic hot-unplugging test via the device_del QMP command.
1633 * Device deletion will get one response and one event. For example:
1635 * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1637 * will get this one:
1639 * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1640 * "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1641 * "path": "/machine/peripheral/scsi-hd"}}
1643 * and this one:
1645 * {"return": {}}
1647 void qtest_qmp_device_del_send(QTestState *qts, const char *id)
1649 QDict *rsp = qtest_qmp(qts, "{'execute': 'device_del', "
1650 "'arguments': {'id': %s}}", id);
1651 g_assert(rsp);
1652 g_assert(qdict_haskey(rsp, "return"));
1653 g_assert(!qdict_haskey(rsp, "error"));
1654 qobject_unref(rsp);
1657 void qtest_qmp_device_del(QTestState *qts, const char *id)
1659 qtest_qmp_device_del_send(qts, id);
1660 qtest_qmp_eventwait(qts, "DEVICE_DELETED");
1663 static void qtest_client_set_tx_handler(QTestState *s,
1664 QTestSendFn send)
1666 s->ops.send = send;
1668 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv)
1670 s->ops.recv_line = recv;
1672 /* A type-safe wrapper for s->send() */
1673 static void send_wrapper(QTestState *s, const char *buf)
1675 s->ops.external_send(s, buf);
1678 static GString *qtest_client_inproc_recv_line(QTestState *s)
1680 GString *line;
1681 size_t offset;
1682 char *eol;
1684 eol = strchr(s->rx->str, '\n');
1685 offset = eol - s->rx->str;
1686 line = g_string_new_len(s->rx->str, offset);
1687 g_string_erase(s->rx, 0, offset + 1);
1688 return line;
1691 QTestState *qtest_inproc_init(QTestState **s, bool log, const char* arch,
1692 void (*send)(void*, const char*))
1694 QTestState *qts;
1695 qts = g_new0(QTestState, 1);
1696 qts->pending_events = NULL;
1697 *s = qts; /* Expose qts early on, since the query endianness relies on it */
1698 qts->wstatus = 0;
1699 for (int i = 0; i < MAX_IRQ; i++) {
1700 qts->irq_level[i] = false;
1703 qtest_client_set_rx_handler(qts, qtest_client_inproc_recv_line);
1705 /* send() may not have a matching prototype, so use a type-safe wrapper */
1706 qts->ops.external_send = send;
1707 qtest_client_set_tx_handler(qts, send_wrapper);
1709 qts->big_endian = qtest_query_target_endianness(qts);
1712 * Set a dummy path for QTEST_QEMU_BINARY. Doesn't need to exist, but this
1713 * way, qtest_get_arch works for inproc qtest.
1715 gchar *bin_path = g_strconcat("/qemu-system-", arch, NULL);
1716 g_setenv("QTEST_QEMU_BINARY", bin_path, 0);
1717 g_free(bin_path);
1719 return qts;
1722 void qtest_client_inproc_recv(void *opaque, const char *str)
1724 QTestState *qts = *(QTestState **)opaque;
1726 if (!qts->rx) {
1727 qts->rx = g_string_new(NULL);
1729 g_string_append(qts->rx, str);
1730 return;
1733 void qtest_qom_set_bool(QTestState *s, const char *path, const char *property,
1734 bool value)
1736 QDict *r;
1738 r = qtest_qmp(s, "{ 'execute': 'qom-set', 'arguments': "
1739 "{ 'path': %s, 'property': %s, 'value': %i } }",
1740 path, property, value);
1741 qobject_unref(r);
1744 bool qtest_qom_get_bool(QTestState *s, const char *path, const char *property)
1746 QDict *r;
1747 bool b;
1749 r = qtest_qmp(s, "{ 'execute': 'qom-get', 'arguments': "
1750 "{ 'path': %s, 'property': %s } }", path, property);
1751 b = qdict_get_bool(r, "return");
1752 qobject_unref(r);
1754 return b;
1757 bool have_qemu_img(void)
1759 char *rpath;
1760 const char *path = getenv("QTEST_QEMU_IMG");
1761 if (!path) {
1762 return false;
1765 rpath = realpath(path, NULL);
1766 if (!rpath) {
1767 return false;
1768 } else {
1769 free(rpath);
1770 return true;
1774 bool mkimg(const char *file, const char *fmt, unsigned size_mb)
1776 gchar *cli;
1777 bool ret;
1778 int rc;
1779 GError *err = NULL;
1780 char *qemu_img_path;
1781 gchar *out, *out2;
1782 char *qemu_img_abs_path;
1784 qemu_img_path = getenv("QTEST_QEMU_IMG");
1785 if (!qemu_img_path) {
1786 return false;
1788 qemu_img_abs_path = realpath(qemu_img_path, NULL);
1789 if (!qemu_img_abs_path) {
1790 return false;
1793 cli = g_strdup_printf("%s create -f %s %s %uM", qemu_img_abs_path,
1794 fmt, file, size_mb);
1795 ret = g_spawn_command_line_sync(cli, &out, &out2, &rc, &err);
1796 if (err || !g_spawn_check_exit_status(rc, &err)) {
1797 fprintf(stderr, "%s\n", err->message);
1798 g_error_free(err);
1801 g_free(out);
1802 g_free(out2);
1803 g_free(cli);
1804 free(qemu_img_abs_path);
1806 return ret && !err;