KVM: remove support for kernel-irqchip=off
[qemu.git] / tests / qtest / libqtest.c
blob2fbc3b88f32e8eb9cf872a856713388dcbc03643
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__ */
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"
38 #define MAX_IRQ 256
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
52 typedef void (*QTestSendFn)(QTestState *s, const char *buf);
53 typedef void (*ExternalSendFn)(void *s, const char *buf);
54 typedef GString* (*QTestRecvFn)(QTestState *);
56 typedef struct QTestClientTransportOps {
57 QTestSendFn send; /* for sending qtest commands */
60 * use external_send to send qtest command strings through functions which
61 * do not accept a QTestState as the first parameter.
63 ExternalSendFn external_send;
65 QTestRecvFn recv_line; /* for receiving qtest command responses */
66 } QTestTransportOps;
68 struct QTestState
70 int fd;
71 int qmp_fd;
72 pid_t qemu_pid; /* our child QEMU process */
73 int wstatus;
74 #ifdef _WIN32
75 DWORD exit_code;
76 #endif
77 int expected_status;
78 bool big_endian;
79 bool irq_level[MAX_IRQ];
80 GString *rx;
81 QTestTransportOps ops;
82 GList *pending_events;
85 static GHookList abrt_hooks;
86 static void (*sighandler_old)(int);
88 static int qtest_query_target_endianness(QTestState *s);
90 static void qtest_client_socket_send(QTestState*, const char *buf);
91 static void socket_send(int fd, const char *buf, size_t size);
93 static GString *qtest_client_socket_recv_line(QTestState *);
95 static void qtest_client_set_tx_handler(QTestState *s, QTestSendFn send);
96 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv);
98 static int init_socket(const char *socket_path)
100 int sock = qtest_socket_server(socket_path);
101 qemu_set_cloexec(sock);
102 return sock;
105 static int socket_accept(int sock)
107 struct sockaddr_un addr;
108 socklen_t addrlen;
109 int ret;
111 * timeout unit of blocking receive calls is different among platfoms.
112 * It's in seconds on non-Windows platforms but milliseconds on Windows.
114 #ifndef _WIN32
115 struct timeval timeout = { .tv_sec = SOCKET_TIMEOUT,
116 .tv_usec = 0 };
117 #else
118 DWORD timeout = SOCKET_TIMEOUT;
119 #endif
121 if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
122 (void *)&timeout, sizeof(timeout))) {
123 fprintf(stderr, "%s failed to set SO_RCVTIMEO: %s\n",
124 __func__, strerror(errno));
125 closesocket(sock);
126 return -1;
129 do {
130 addrlen = sizeof(addr);
131 ret = accept(sock, (struct sockaddr *)&addr, &addrlen);
132 } while (ret == -1 && errno == EINTR);
133 if (ret == -1) {
134 fprintf(stderr, "%s failed: %s\n", __func__, strerror(errno));
136 closesocket(sock);
138 return ret;
141 bool qtest_probe_child(QTestState *s)
143 pid_t pid = s->qemu_pid;
145 if (pid != -1) {
146 #ifndef _WIN32
147 pid = waitpid(pid, &s->wstatus, WNOHANG);
148 if (pid == 0) {
149 return true;
151 #else
152 GetExitCodeProcess((HANDLE)pid, &s->exit_code);
153 if (s->exit_code == STILL_ACTIVE) {
154 return true;
156 CloseHandle((HANDLE)pid);
157 #endif
158 s->qemu_pid = -1;
160 return false;
163 void qtest_set_expected_status(QTestState *s, int status)
165 s->expected_status = status;
168 static void qtest_check_status(QTestState *s)
171 * Check whether qemu exited with expected exit status; anything else is
172 * fishy and should be logged with as much detail as possible.
174 #ifndef _WIN32
175 int wstatus = s->wstatus;
176 if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != s->expected_status) {
177 fprintf(stderr, "%s:%d: kill_qemu() tried to terminate QEMU "
178 "process but encountered exit status %d (expected %d)\n",
179 __FILE__, __LINE__, WEXITSTATUS(wstatus), s->expected_status);
180 abort();
181 } else if (WIFSIGNALED(wstatus)) {
182 int sig = WTERMSIG(wstatus);
183 const char *signame = strsignal(sig) ?: "unknown ???";
184 const char *dump = WCOREDUMP(wstatus) ? " (core dumped)" : "";
186 fprintf(stderr, "%s:%d: kill_qemu() detected QEMU death "
187 "from signal %d (%s)%s\n",
188 __FILE__, __LINE__, sig, signame, dump);
189 abort();
191 #else
192 if (s->exit_code != s->expected_status) {
193 fprintf(stderr, "%s:%d: kill_qemu() tried to terminate QEMU "
194 "process but encountered exit status %ld (expected %d)\n",
195 __FILE__, __LINE__, s->exit_code, s->expected_status);
196 abort();
198 #endif
201 void qtest_wait_qemu(QTestState *s)
203 #ifndef _WIN32
204 pid_t pid;
206 TFR(pid = waitpid(s->qemu_pid, &s->wstatus, 0));
207 assert(pid == s->qemu_pid);
208 #else
209 DWORD ret;
211 ret = WaitForSingleObject((HANDLE)s->qemu_pid, INFINITE);
212 assert(ret == WAIT_OBJECT_0);
213 GetExitCodeProcess((HANDLE)s->qemu_pid, &s->exit_code);
214 CloseHandle((HANDLE)s->qemu_pid);
215 #endif
217 qtest_check_status(s);
220 void qtest_kill_qemu(QTestState *s)
222 /* Skip wait if qtest_probe_child() already reaped */
223 if (s->qemu_pid != -1) {
224 #ifndef _WIN32
225 kill(s->qemu_pid, SIGTERM);
226 #else
227 TerminateProcess((HANDLE)s->qemu_pid, s->expected_status);
228 #endif
229 qtest_wait_qemu(s);
230 s->qemu_pid = -1;
231 return;
234 qtest_check_status(s);
237 static void kill_qemu_hook_func(void *s)
239 qtest_kill_qemu(s);
242 static void sigabrt_handler(int signo)
244 g_hook_list_invoke(&abrt_hooks, FALSE);
247 static void setup_sigabrt_handler(void)
249 sighandler_old = signal(SIGABRT, sigabrt_handler);
252 static void cleanup_sigabrt_handler(void)
254 signal(SIGABRT, sighandler_old);
257 static bool hook_list_is_empty(GHookList *hook_list)
259 GHook *hook = g_hook_first_valid(hook_list, TRUE);
261 if (!hook) {
262 return true;
265 g_hook_unref(hook_list, hook);
266 return false;
269 void qtest_add_abrt_handler(GHookFunc fn, const void *data)
271 GHook *hook;
273 if (!abrt_hooks.is_setup) {
274 g_hook_list_init(&abrt_hooks, sizeof(GHook));
277 /* Only install SIGABRT handler once */
278 if (hook_list_is_empty(&abrt_hooks)) {
279 setup_sigabrt_handler();
282 hook = g_hook_alloc(&abrt_hooks);
283 hook->func = fn;
284 hook->data = (void *)data;
286 g_hook_prepend(&abrt_hooks, hook);
289 void qtest_remove_abrt_handler(void *data)
291 GHook *hook = g_hook_find_data(&abrt_hooks, TRUE, data);
292 g_hook_destroy_link(&abrt_hooks, hook);
294 /* Uninstall SIGABRT handler on last instance */
295 if (hook_list_is_empty(&abrt_hooks)) {
296 cleanup_sigabrt_handler();
300 static const char *qtest_qemu_binary(void)
302 const char *qemu_bin;
304 qemu_bin = getenv("QTEST_QEMU_BINARY");
305 if (!qemu_bin) {
306 fprintf(stderr, "Environment variable QTEST_QEMU_BINARY required\n");
307 exit(1);
310 return qemu_bin;
313 #ifdef _WIN32
314 static pid_t qtest_create_process(char *cmd)
316 STARTUPINFO si;
317 PROCESS_INFORMATION pi;
318 BOOL ret;
320 ZeroMemory(&si, sizeof(si));
321 si.cb = sizeof(si);
322 ZeroMemory(&pi, sizeof(pi));
324 ret = CreateProcess(NULL, /* module name */
325 cmd, /* command line */
326 NULL, /* process handle not inheritable */
327 NULL, /* thread handle not inheritable */
328 FALSE, /* set handle inheritance to FALSE */
329 0, /* No creation flags */
330 NULL, /* use parent's environment block */
331 NULL, /* use parent's starting directory */
332 &si, /* pointer to STARTUPINFO structure */
333 &pi /* pointer to PROCESS_INFORMATION structure */
335 if (ret == 0) {
336 fprintf(stderr, "%s:%d: unable to create a new process (%s)\n",
337 __FILE__, __LINE__, strerror(GetLastError()));
338 abort();
341 return (pid_t)pi.hProcess;
343 #endif /* _WIN32 */
345 QTestState *qtest_init_without_qmp_handshake(const char *extra_args)
347 QTestState *s;
348 int sock, qmpsock, i;
349 gchar *socket_path;
350 gchar *qmp_socket_path;
351 gchar *command;
352 const char *qemu_binary = qtest_qemu_binary();
353 const char *trace = g_getenv("QTEST_TRACE");
354 g_autofree char *tracearg = trace ?
355 g_strdup_printf("-trace %s ", trace) : g_strdup("");
357 s = g_new(QTestState, 1);
359 socket_path = g_strdup_printf("%s/qtest-%d.sock",
360 g_get_tmp_dir(), getpid());
361 qmp_socket_path = g_strdup_printf("%s/qtest-%d.qmp",
362 g_get_tmp_dir(), getpid());
364 /* It's possible that if an earlier test run crashed it might
365 * have left a stale unix socket lying around. Delete any
366 * stale old socket to avoid spurious test failures with
367 * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1)
369 unlink(socket_path);
370 unlink(qmp_socket_path);
372 socket_init();
373 sock = init_socket(socket_path);
374 qmpsock = init_socket(qmp_socket_path);
376 qtest_client_set_rx_handler(s, qtest_client_socket_recv_line);
377 qtest_client_set_tx_handler(s, qtest_client_socket_send);
379 qtest_add_abrt_handler(kill_qemu_hook_func, s);
381 command = g_strdup_printf(CMD_EXEC "%s %s"
382 "-qtest unix:%s "
383 "-qtest-log %s "
384 "-chardev socket,path=%s,id=char0 "
385 "-mon chardev=char0,mode=control "
386 "-display none "
387 "%s"
388 " -accel qtest",
389 qemu_binary, tracearg, socket_path,
390 getenv("QTEST_LOG") ? DEV_STDERR : DEV_NULL,
391 qmp_socket_path,
392 extra_args ?: "");
394 g_test_message("starting QEMU: %s", command);
396 s->pending_events = NULL;
397 s->wstatus = 0;
398 s->expected_status = 0;
399 #ifndef _WIN32
400 s->qemu_pid = fork();
401 if (s->qemu_pid == 0) {
402 #ifdef __linux__
404 * Although we register a ABRT handler to kill off QEMU
405 * when g_assert() triggers, we want an extra safety
406 * net. The QEMU process might be non-functional and
407 * thus not have responded to SIGTERM. The test script
408 * might also have crashed with SEGV, in which case the
409 * cleanup handlers won't ever run.
411 * This PR_SET_PDEATHSIG setup will ensure any remaining
412 * QEMU will get terminated with SIGKILL in these cases.
414 prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
415 #endif /* __linux__ */
416 if (!g_setenv("QEMU_AUDIO_DRV", "none", true)) {
417 exit(1);
419 execlp("/bin/sh", "sh", "-c", command, NULL);
420 exit(1);
422 #else
423 s->qemu_pid = qtest_create_process(command);
424 #endif /* _WIN32 */
426 g_free(command);
427 s->fd = socket_accept(sock);
428 if (s->fd >= 0) {
429 s->qmp_fd = socket_accept(qmpsock);
431 unlink(socket_path);
432 unlink(qmp_socket_path);
433 g_free(socket_path);
434 g_free(qmp_socket_path);
436 g_assert(s->fd >= 0 && s->qmp_fd >= 0);
438 s->rx = g_string_new("");
439 for (i = 0; i < MAX_IRQ; i++) {
440 s->irq_level[i] = false;
444 * Stopping QEMU for debugging is not supported on Windows.
446 * Using DebugActiveProcess() API can suspend the QEMU process,
447 * but gdb cannot attach to the process. Using the undocumented
448 * NtSuspendProcess() can suspend the QEMU process and gdb can
449 * attach to the process, but gdb cannot resume it.
451 #ifndef _WIN32
452 if (getenv("QTEST_STOP")) {
453 kill(s->qemu_pid, SIGSTOP);
455 #endif
457 /* ask endianness of the target */
459 s->big_endian = qtest_query_target_endianness(s);
461 return s;
464 QTestState *qtest_init(const char *extra_args)
466 QTestState *s = qtest_init_without_qmp_handshake(extra_args);
467 QDict *greeting;
469 /* Read the QMP greeting and then do the handshake */
470 greeting = qtest_qmp_receive(s);
471 qobject_unref(greeting);
472 qobject_unref(qtest_qmp(s, "{ 'execute': 'qmp_capabilities' }"));
474 return s;
477 QTestState *qtest_vinitf(const char *fmt, va_list ap)
479 char *args = g_strdup_vprintf(fmt, ap);
480 QTestState *s;
482 s = qtest_init(args);
483 g_free(args);
484 return s;
487 QTestState *qtest_initf(const char *fmt, ...)
489 va_list ap;
490 QTestState *s;
492 va_start(ap, fmt);
493 s = qtest_vinitf(fmt, ap);
494 va_end(ap);
495 return s;
498 QTestState *qtest_init_with_serial(const char *extra_args, int *sock_fd)
500 int sock_fd_init;
501 g_autofree char *sock_dir = NULL;
502 char *sock_path;
503 QTestState *qts;
505 sock_dir = g_dir_make_tmp("qtest-serial-XXXXXX", NULL);
506 g_assert_true(sock_dir != NULL);
507 sock_path = g_strdup_printf("%s/sock", sock_dir);
509 socket_init();
510 sock_fd_init = init_socket(sock_path);
512 qts = qtest_initf("-chardev socket,id=s0,path=%s -serial chardev:s0 %s",
513 sock_path, extra_args);
515 *sock_fd = socket_accept(sock_fd_init);
517 unlink(sock_path);
518 g_free(sock_path);
519 rmdir(sock_dir);
521 g_assert_true(*sock_fd >= 0);
523 return qts;
526 void qtest_quit(QTestState *s)
528 qtest_remove_abrt_handler(s);
530 qtest_kill_qemu(s);
531 closesocket(s->fd);
532 closesocket(s->qmp_fd);
533 g_string_free(s->rx, true);
535 for (GList *it = s->pending_events; it != NULL; it = it->next) {
536 qobject_unref((QDict *)it->data);
539 g_list_free(s->pending_events);
541 g_free(s);
544 static void socket_send(int fd, const char *buf, size_t size)
546 ssize_t res = qemu_send_full(fd, buf, size);
548 assert(res == size);
551 static void qtest_client_socket_send(QTestState *s, const char *buf)
553 socket_send(s->fd, buf, strlen(buf));
556 static void G_GNUC_PRINTF(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...)
558 va_list ap;
560 va_start(ap, fmt);
561 gchar *str = g_strdup_vprintf(fmt, ap);
562 va_end(ap);
564 s->ops.send(s, str);
565 g_free(str);
568 static GString *qtest_client_socket_recv_line(QTestState *s)
570 GString *line;
571 size_t offset;
572 char *eol;
574 while ((eol = strchr(s->rx->str, '\n')) == NULL) {
575 ssize_t len;
576 char buffer[1024];
578 len = recv(s->fd, buffer, sizeof(buffer), 0);
579 if (len == -1 && errno == EINTR) {
580 continue;
583 if (len == -1 || len == 0) {
584 fprintf(stderr, "Broken pipe\n");
585 abort();
588 g_string_append_len(s->rx, buffer, len);
591 offset = eol - s->rx->str;
592 line = g_string_new_len(s->rx->str, offset);
593 g_string_erase(s->rx, 0, offset + 1);
595 return line;
598 static gchar **qtest_rsp_args(QTestState *s, int expected_args)
600 GString *line;
601 gchar **words;
602 int i;
604 redo:
605 line = s->ops.recv_line(s);
606 words = g_strsplit(line->str, " ", 0);
607 g_string_free(line, TRUE);
609 if (strcmp(words[0], "IRQ") == 0) {
610 long irq;
611 int ret;
613 g_assert(words[1] != NULL);
614 g_assert(words[2] != NULL);
616 ret = qemu_strtol(words[2], NULL, 0, &irq);
617 g_assert(!ret);
618 g_assert_cmpint(irq, >=, 0);
619 g_assert_cmpint(irq, <, MAX_IRQ);
621 if (strcmp(words[1], "raise") == 0) {
622 s->irq_level[irq] = true;
623 } else {
624 s->irq_level[irq] = false;
627 g_strfreev(words);
628 goto redo;
631 g_assert(words[0] != NULL);
632 g_assert_cmpstr(words[0], ==, "OK");
634 for (i = 0; i < expected_args; i++) {
635 g_assert(words[i] != NULL);
638 return words;
641 static void qtest_rsp(QTestState *s)
643 gchar **words = qtest_rsp_args(s, 0);
645 g_strfreev(words);
648 static int qtest_query_target_endianness(QTestState *s)
650 gchar **args;
651 int big_endian;
653 qtest_sendf(s, "endianness\n");
654 args = qtest_rsp_args(s, 1);
655 g_assert(strcmp(args[1], "big") == 0 || strcmp(args[1], "little") == 0);
656 big_endian = strcmp(args[1], "big") == 0;
657 g_strfreev(args);
659 return big_endian;
662 QDict *qtest_qmp_receive(QTestState *s)
664 while (true) {
665 QDict *response = qtest_qmp_receive_dict(s);
667 if (!qdict_get_try_str(response, "event")) {
668 return response;
670 /* Stash the event for a later consumption */
671 s->pending_events = g_list_append(s->pending_events, response);
675 QDict *qtest_qmp_receive_dict(QTestState *s)
677 return qmp_fd_receive(s->qmp_fd);
680 int qtest_socket_server(const char *socket_path)
682 struct sockaddr_un addr;
683 int sock;
684 int ret;
686 sock = socket(PF_UNIX, SOCK_STREAM, 0);
687 g_assert_cmpint(sock, !=, -1);
689 addr.sun_family = AF_UNIX;
690 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
692 do {
693 ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
694 } while (ret == -1 && errno == EINTR);
695 g_assert_cmpint(ret, !=, -1);
696 ret = listen(sock, 1);
697 g_assert_cmpint(ret, !=, -1);
699 return sock;
702 #ifndef _WIN32
703 void qtest_qmp_vsend_fds(QTestState *s, int *fds, size_t fds_num,
704 const char *fmt, va_list ap)
706 qmp_fd_vsend_fds(s->qmp_fd, fds, fds_num, fmt, ap);
708 #endif
710 void qtest_qmp_vsend(QTestState *s, const char *fmt, va_list ap)
712 qmp_fd_vsend(s->qmp_fd, fmt, ap);
715 #ifndef _WIN32
716 QDict *qtest_vqmp_fds(QTestState *s, int *fds, size_t fds_num,
717 const char *fmt, va_list ap)
719 qtest_qmp_vsend_fds(s, fds, fds_num, fmt, ap);
721 /* Receive reply */
722 return qtest_qmp_receive(s);
724 #endif
726 QDict *qtest_vqmp(QTestState *s, const char *fmt, va_list ap)
728 qtest_qmp_vsend(s, fmt, ap);
730 /* Receive reply */
731 return qtest_qmp_receive(s);
734 #ifndef _WIN32
735 QDict *qtest_qmp_fds(QTestState *s, int *fds, size_t fds_num,
736 const char *fmt, ...)
738 va_list ap;
739 QDict *response;
741 va_start(ap, fmt);
742 response = qtest_vqmp_fds(s, fds, fds_num, fmt, ap);
743 va_end(ap);
744 return response;
746 #endif
748 QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
750 va_list ap;
751 QDict *response;
753 va_start(ap, fmt);
754 response = qtest_vqmp(s, fmt, ap);
755 va_end(ap);
756 return response;
759 void qtest_qmp_send(QTestState *s, const char *fmt, ...)
761 va_list ap;
763 va_start(ap, fmt);
764 qtest_qmp_vsend(s, fmt, ap);
765 va_end(ap);
768 void qtest_qmp_send_raw(QTestState *s, const char *fmt, ...)
770 va_list ap;
772 va_start(ap, fmt);
773 qmp_fd_vsend_raw(s->qmp_fd, fmt, ap);
774 va_end(ap);
777 QDict *qtest_qmp_event_ref(QTestState *s, const char *event)
779 while (s->pending_events) {
781 GList *first = s->pending_events;
782 QDict *response = (QDict *)first->data;
784 s->pending_events = g_list_delete_link(s->pending_events, first);
786 if (!strcmp(qdict_get_str(response, "event"), event)) {
787 return response;
789 qobject_unref(response);
791 return NULL;
794 QDict *qtest_qmp_eventwait_ref(QTestState *s, const char *event)
796 QDict *response = qtest_qmp_event_ref(s, event);
798 if (response) {
799 return response;
802 for (;;) {
803 response = qtest_qmp_receive_dict(s);
804 if ((qdict_haskey(response, "event")) &&
805 (strcmp(qdict_get_str(response, "event"), event) == 0)) {
806 return response;
808 qobject_unref(response);
812 void qtest_qmp_eventwait(QTestState *s, const char *event)
814 QDict *response;
816 response = qtest_qmp_eventwait_ref(s, event);
817 qobject_unref(response);
820 char *qtest_vhmp(QTestState *s, const char *fmt, va_list ap)
822 char *cmd;
823 QDict *resp;
824 char *ret;
826 cmd = g_strdup_vprintf(fmt, ap);
827 resp = qtest_qmp(s, "{'execute': 'human-monitor-command',"
828 " 'arguments': {'command-line': %s}}",
829 cmd);
830 ret = g_strdup(qdict_get_try_str(resp, "return"));
831 g_assert(ret);
832 qobject_unref(resp);
833 g_free(cmd);
834 return ret;
837 char *qtest_hmp(QTestState *s, const char *fmt, ...)
839 va_list ap;
840 char *ret;
842 va_start(ap, fmt);
843 ret = qtest_vhmp(s, fmt, ap);
844 va_end(ap);
845 return ret;
848 const char *qtest_get_arch(void)
850 const char *qemu = qtest_qemu_binary();
851 const char *end = strrchr(qemu, '-');
853 if (!end) {
854 fprintf(stderr, "Can't determine architecture from binary name.\n");
855 exit(1);
858 if (!strstr(qemu, "-system-")) {
859 fprintf(stderr, "QTEST_QEMU_BINARY must end with *-system-<arch> "
860 "where 'arch' is the target\narchitecture (x86_64, aarch64, "
861 "etc).\n");
862 exit(1);
865 return end + 1;
868 bool qtest_has_accel(const char *accel_name)
870 if (g_str_equal(accel_name, "tcg")) {
871 #if defined(CONFIG_TCG)
872 return true;
873 #else
874 return false;
875 #endif
876 } else if (g_str_equal(accel_name, "kvm")) {
877 int i;
878 const char *arch = qtest_get_arch();
879 const char *targets[] = { CONFIG_KVM_TARGETS };
881 for (i = 0; i < ARRAY_SIZE(targets); i++) {
882 if (!strncmp(targets[i], arch, strlen(arch))) {
883 if (!access("/dev/kvm", R_OK | W_OK)) {
884 return true;
888 } else {
889 /* not implemented */
890 g_assert_not_reached();
892 return false;
895 bool qtest_get_irq(QTestState *s, int num)
897 /* dummy operation in order to make sure irq is up to date */
898 qtest_inb(s, 0);
900 return s->irq_level[num];
903 void qtest_module_load(QTestState *s, const char *prefix, const char *libname)
905 qtest_sendf(s, "module_load %s %s\n", prefix, libname);
906 qtest_rsp(s);
909 static int64_t qtest_clock_rsp(QTestState *s)
911 gchar **words;
912 int64_t clock;
913 words = qtest_rsp_args(s, 2);
914 clock = g_ascii_strtoll(words[1], NULL, 0);
915 g_strfreev(words);
916 return clock;
919 int64_t qtest_clock_step_next(QTestState *s)
921 qtest_sendf(s, "clock_step\n");
922 return qtest_clock_rsp(s);
925 int64_t qtest_clock_step(QTestState *s, int64_t step)
927 qtest_sendf(s, "clock_step %"PRIi64"\n", step);
928 return qtest_clock_rsp(s);
931 int64_t qtest_clock_set(QTestState *s, int64_t val)
933 qtest_sendf(s, "clock_set %"PRIi64"\n", val);
934 return qtest_clock_rsp(s);
937 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
939 qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
940 qtest_rsp(s);
943 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
945 qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
946 qtest_rsp(s);
949 void qtest_set_irq_in(QTestState *s, const char *qom_path, const char *name,
950 int num, int level)
952 if (!name) {
953 name = "unnamed-gpio-in";
955 qtest_sendf(s, "set_irq_in %s %s %d %d\n", qom_path, name, num, level);
956 qtest_rsp(s);
959 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
961 qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
962 qtest_rsp(s);
965 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
967 qtest_out(s, "outb", addr, value);
970 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
972 qtest_out(s, "outw", addr, value);
975 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
977 qtest_out(s, "outl", addr, value);
980 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
982 gchar **args;
983 int ret;
984 unsigned long value;
986 qtest_sendf(s, "%s 0x%x\n", cmd, addr);
987 args = qtest_rsp_args(s, 2);
988 ret = qemu_strtoul(args[1], NULL, 0, &value);
989 g_assert(!ret && value <= UINT32_MAX);
990 g_strfreev(args);
992 return value;
995 uint8_t qtest_inb(QTestState *s, uint16_t addr)
997 return qtest_in(s, "inb", addr);
1000 uint16_t qtest_inw(QTestState *s, uint16_t addr)
1002 return qtest_in(s, "inw", addr);
1005 uint32_t qtest_inl(QTestState *s, uint16_t addr)
1007 return qtest_in(s, "inl", addr);
1010 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
1011 uint64_t value)
1013 qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
1014 qtest_rsp(s);
1017 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
1019 qtest_write(s, "writeb", addr, value);
1022 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
1024 qtest_write(s, "writew", addr, value);
1027 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
1029 qtest_write(s, "writel", addr, value);
1032 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
1034 qtest_write(s, "writeq", addr, value);
1037 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
1039 gchar **args;
1040 int ret;
1041 uint64_t value;
1043 qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
1044 args = qtest_rsp_args(s, 2);
1045 ret = qemu_strtou64(args[1], NULL, 0, &value);
1046 g_assert(!ret);
1047 g_strfreev(args);
1049 return value;
1052 uint8_t qtest_readb(QTestState *s, uint64_t addr)
1054 return qtest_read(s, "readb", addr);
1057 uint16_t qtest_readw(QTestState *s, uint64_t addr)
1059 return qtest_read(s, "readw", addr);
1062 uint32_t qtest_readl(QTestState *s, uint64_t addr)
1064 return qtest_read(s, "readl", addr);
1067 uint64_t qtest_readq(QTestState *s, uint64_t addr)
1069 return qtest_read(s, "readq", addr);
1072 static int hex2nib(char ch)
1074 if (ch >= '0' && ch <= '9') {
1075 return ch - '0';
1076 } else if (ch >= 'a' && ch <= 'f') {
1077 return 10 + (ch - 'a');
1078 } else if (ch >= 'A' && ch <= 'F') {
1079 return 10 + (ch - 'a');
1080 } else {
1081 return -1;
1085 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
1087 uint8_t *ptr = data;
1088 gchar **args;
1089 size_t i;
1091 if (!size) {
1092 return;
1095 qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
1096 args = qtest_rsp_args(s, 2);
1098 for (i = 0; i < size; i++) {
1099 ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
1100 ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
1103 g_strfreev(args);
1106 uint64_t qtest_rtas_call(QTestState *s, const char *name,
1107 uint32_t nargs, uint64_t args,
1108 uint32_t nret, uint64_t ret)
1110 qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n",
1111 name, nargs, args, nret, ret);
1112 qtest_rsp(s);
1113 return 0;
1116 void qtest_add_func(const char *str, void (*fn)(void))
1118 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1119 g_test_add_func(path, fn);
1120 g_free(path);
1123 void qtest_add_data_func_full(const char *str, void *data,
1124 void (*fn)(const void *),
1125 GDestroyNotify data_free_func)
1127 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1128 g_test_add_data_func_full(path, data, fn, data_free_func);
1129 g_free(path);
1132 void qtest_add_data_func(const char *str, const void *data,
1133 void (*fn)(const void *))
1135 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1136 g_test_add_data_func(path, data, fn);
1137 g_free(path);
1140 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1142 gchar *bdata;
1144 bdata = g_base64_encode(data, size);
1145 qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
1146 s->ops.send(s, bdata);
1147 s->ops.send(s, "\n");
1148 qtest_rsp(s);
1149 g_free(bdata);
1152 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
1154 gchar **args;
1155 size_t len;
1157 qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
1158 args = qtest_rsp_args(s, 2);
1160 g_base64_decode_inplace(args[1], &len);
1161 if (size != len) {
1162 fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
1163 size, len);
1164 len = MIN(len, size);
1167 memcpy(data, args[1], len);
1168 g_strfreev(args);
1171 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1173 const uint8_t *ptr = data;
1174 size_t i;
1175 char *enc;
1177 if (!size) {
1178 return;
1181 enc = g_malloc(2 * size + 1);
1183 for (i = 0; i < size; i++) {
1184 sprintf(&enc[i * 2], "%02x", ptr[i]);
1187 qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
1188 qtest_rsp(s);
1189 g_free(enc);
1192 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
1194 qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
1195 qtest_rsp(s);
1198 void qtest_qmp_assert_success(QTestState *qts, const char *fmt, ...)
1200 va_list ap;
1201 QDict *response;
1203 va_start(ap, fmt);
1204 response = qtest_vqmp(qts, fmt, ap);
1205 va_end(ap);
1207 g_assert(response);
1208 if (!qdict_haskey(response, "return")) {
1209 GString *s = qobject_to_json_pretty(QOBJECT(response), true);
1210 g_test_message("%s", s->str);
1211 g_string_free(s, true);
1213 g_assert(qdict_haskey(response, "return"));
1214 qobject_unref(response);
1217 bool qtest_big_endian(QTestState *s)
1219 return s->big_endian;
1222 static bool qtest_check_machine_version(const char *mname, const char *basename,
1223 int major, int minor)
1225 char *newname;
1226 bool is_equal;
1228 newname = g_strdup_printf("%s-%i.%i", basename, major, minor);
1229 is_equal = g_str_equal(mname, newname);
1230 g_free(newname);
1232 return is_equal;
1235 static bool qtest_is_old_versioned_machine(const char *mname)
1237 const char *dash = strrchr(mname, '-');
1238 const char *dot = strrchr(mname, '.');
1239 const char *chr;
1240 char *bname;
1241 const int major = QEMU_VERSION_MAJOR;
1242 const int minor = QEMU_VERSION_MINOR;
1243 bool res = false;
1245 if (dash && dot && dot > dash) {
1246 for (chr = dash + 1; *chr; chr++) {
1247 if (!qemu_isdigit(*chr) && *chr != '.') {
1248 return false;
1252 * Now check if it is one of the latest versions. Check major + 1
1253 * and minor + 1 versions as well, since they might already exist
1254 * in the development branch.
1256 bname = g_strdup(mname);
1257 bname[dash - mname] = 0;
1258 res = !qtest_check_machine_version(mname, bname, major + 1, 0) &&
1259 !qtest_check_machine_version(mname, bname, major, minor + 1) &&
1260 !qtest_check_machine_version(mname, bname, major, minor);
1261 g_free(bname);
1264 return res;
1267 struct MachInfo {
1268 char *name;
1269 char *alias;
1273 * Returns an array with pointers to the available machine names.
1274 * The terminating entry has the name set to NULL.
1276 static struct MachInfo *qtest_get_machines(void)
1278 static struct MachInfo *machines;
1279 QDict *response, *minfo;
1280 QList *list;
1281 const QListEntry *p;
1282 QObject *qobj;
1283 QString *qstr;
1284 QTestState *qts;
1285 int idx;
1287 if (machines) {
1288 return machines;
1291 qts = qtest_init("-machine none");
1292 response = qtest_qmp(qts, "{ 'execute': 'query-machines' }");
1293 g_assert(response);
1294 list = qdict_get_qlist(response, "return");
1295 g_assert(list);
1297 machines = g_new(struct MachInfo, qlist_size(list) + 1);
1299 for (p = qlist_first(list), idx = 0; p; p = qlist_next(p), idx++) {
1300 minfo = qobject_to(QDict, qlist_entry_obj(p));
1301 g_assert(minfo);
1303 qobj = qdict_get(minfo, "name");
1304 g_assert(qobj);
1305 qstr = qobject_to(QString, qobj);
1306 g_assert(qstr);
1307 machines[idx].name = g_strdup(qstring_get_str(qstr));
1309 qobj = qdict_get(minfo, "alias");
1310 if (qobj) { /* The alias is optional */
1311 qstr = qobject_to(QString, qobj);
1312 g_assert(qstr);
1313 machines[idx].alias = g_strdup(qstring_get_str(qstr));
1314 } else {
1315 machines[idx].alias = NULL;
1319 qtest_quit(qts);
1320 qobject_unref(response);
1322 memset(&machines[idx], 0, sizeof(struct MachInfo)); /* Terminating entry */
1323 return machines;
1326 void qtest_cb_for_every_machine(void (*cb)(const char *machine),
1327 bool skip_old_versioned)
1329 struct MachInfo *machines;
1330 int i;
1332 machines = qtest_get_machines();
1334 for (i = 0; machines[i].name != NULL; i++) {
1335 /* Ignore machines that cannot be used for qtests */
1336 if (!strncmp("xenfv", machines[i].name, 5) ||
1337 g_str_equal("xenpv", machines[i].name)) {
1338 continue;
1340 if (!skip_old_versioned ||
1341 !qtest_is_old_versioned_machine(machines[i].name)) {
1342 cb(machines[i].name);
1347 bool qtest_has_machine(const char *machine)
1349 struct MachInfo *machines;
1350 int i;
1352 machines = qtest_get_machines();
1354 for (i = 0; machines[i].name != NULL; i++) {
1355 if (g_str_equal(machine, machines[i].name) ||
1356 (machines[i].alias && g_str_equal(machine, machines[i].alias))) {
1357 return true;
1361 return false;
1364 bool qtest_has_device(const char *device)
1366 static QList *list;
1367 const QListEntry *p;
1368 QObject *qobj;
1369 QString *qstr;
1370 QDict *devinfo;
1371 int idx;
1373 if (!list) {
1374 QDict *resp;
1375 QDict *args;
1376 QTestState *qts = qtest_init("-machine none");
1378 args = qdict_new();
1379 qdict_put_bool(args, "abstract", false);
1380 qdict_put_str(args, "implements", "device");
1382 resp = qtest_qmp(qts, "{'execute': 'qom-list-types', 'arguments': %p }",
1383 args);
1384 g_assert(qdict_haskey(resp, "return"));
1385 list = qdict_get_qlist(resp, "return");
1386 qobject_ref(list);
1387 qobject_unref(resp);
1389 qtest_quit(qts);
1392 for (p = qlist_first(list), idx = 0; p; p = qlist_next(p), idx++) {
1393 devinfo = qobject_to(QDict, qlist_entry_obj(p));
1394 g_assert(devinfo);
1396 qobj = qdict_get(devinfo, "name");
1397 g_assert(qobj);
1398 qstr = qobject_to(QString, qobj);
1399 g_assert(qstr);
1400 if (g_str_equal(qstring_get_str(qstr), device)) {
1401 return true;
1405 return false;
1409 * Generic hot-plugging test via the device_add QMP commands.
1411 void qtest_qmp_device_add_qdict(QTestState *qts, const char *drv,
1412 const QDict *arguments)
1414 QDict *resp;
1415 QDict *args = arguments ? qdict_clone_shallow(arguments) : qdict_new();
1417 g_assert(!qdict_haskey(args, "driver"));
1418 qdict_put_str(args, "driver", drv);
1419 resp = qtest_qmp(qts, "{'execute': 'device_add', 'arguments': %p}", args);
1420 g_assert(resp);
1421 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1422 g_assert(!qdict_haskey(resp, "error"));
1423 qobject_unref(resp);
1426 void qtest_qmp_device_add(QTestState *qts, const char *driver, const char *id,
1427 const char *fmt, ...)
1429 QDict *args;
1430 va_list ap;
1432 va_start(ap, fmt);
1433 args = qdict_from_vjsonf_nofail(fmt, ap);
1434 va_end(ap);
1436 g_assert(!qdict_haskey(args, "id"));
1437 qdict_put_str(args, "id", id);
1439 qtest_qmp_device_add_qdict(qts, driver, args);
1440 qobject_unref(args);
1443 #ifndef _WIN32
1444 void qtest_qmp_add_client(QTestState *qts, const char *protocol, int fd)
1446 QDict *resp;
1448 resp = qtest_qmp_fds(qts, &fd, 1, "{'execute': 'getfd',"
1449 "'arguments': {'fdname': 'fdname'}}");
1450 g_assert(resp);
1451 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1452 g_assert(!qdict_haskey(resp, "error"));
1453 qobject_unref(resp);
1455 resp = qtest_qmp(
1456 qts, "{'execute': 'add_client',"
1457 "'arguments': {'protocol': %s, 'fdname': 'fdname'}}", protocol);
1458 g_assert(resp);
1459 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1460 g_assert(!qdict_haskey(resp, "error"));
1461 qobject_unref(resp);
1463 #endif
1466 * Generic hot-unplugging test via the device_del QMP command.
1467 * Device deletion will get one response and one event. For example:
1469 * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1471 * will get this one:
1473 * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1474 * "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1475 * "path": "/machine/peripheral/scsi-hd"}}
1477 * and this one:
1479 * {"return": {}}
1481 void qtest_qmp_device_del_send(QTestState *qts, const char *id)
1483 QDict *rsp = qtest_qmp(qts, "{'execute': 'device_del', "
1484 "'arguments': {'id': %s}}", id);
1485 g_assert(rsp);
1486 g_assert(qdict_haskey(rsp, "return"));
1487 g_assert(!qdict_haskey(rsp, "error"));
1488 qobject_unref(rsp);
1491 void qtest_qmp_device_del(QTestState *qts, const char *id)
1493 qtest_qmp_device_del_send(qts, id);
1494 qtest_qmp_eventwait(qts, "DEVICE_DELETED");
1497 static void qtest_client_set_tx_handler(QTestState *s,
1498 QTestSendFn send)
1500 s->ops.send = send;
1502 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv)
1504 s->ops.recv_line = recv;
1506 /* A type-safe wrapper for s->send() */
1507 static void send_wrapper(QTestState *s, const char *buf)
1509 s->ops.external_send(s, buf);
1512 static GString *qtest_client_inproc_recv_line(QTestState *s)
1514 GString *line;
1515 size_t offset;
1516 char *eol;
1518 eol = strchr(s->rx->str, '\n');
1519 offset = eol - s->rx->str;
1520 line = g_string_new_len(s->rx->str, offset);
1521 g_string_erase(s->rx, 0, offset + 1);
1522 return line;
1525 QTestState *qtest_inproc_init(QTestState **s, bool log, const char* arch,
1526 void (*send)(void*, const char*))
1528 QTestState *qts;
1529 qts = g_new0(QTestState, 1);
1530 qts->pending_events = NULL;
1531 *s = qts; /* Expose qts early on, since the query endianness relies on it */
1532 qts->wstatus = 0;
1533 for (int i = 0; i < MAX_IRQ; i++) {
1534 qts->irq_level[i] = false;
1537 qtest_client_set_rx_handler(qts, qtest_client_inproc_recv_line);
1539 /* send() may not have a matching protoype, so use a type-safe wrapper */
1540 qts->ops.external_send = send;
1541 qtest_client_set_tx_handler(qts, send_wrapper);
1543 qts->big_endian = qtest_query_target_endianness(qts);
1546 * Set a dummy path for QTEST_QEMU_BINARY. Doesn't need to exist, but this
1547 * way, qtest_get_arch works for inproc qtest.
1549 gchar *bin_path = g_strconcat("/qemu-system-", arch, NULL);
1550 g_setenv("QTEST_QEMU_BINARY", bin_path, 0);
1551 g_free(bin_path);
1553 return qts;
1556 void qtest_client_inproc_recv(void *opaque, const char *str)
1558 QTestState *qts = *(QTestState **)opaque;
1560 if (!qts->rx) {
1561 qts->rx = g_string_new(NULL);
1563 g_string_append(qts->rx, str);
1564 return;
1567 void qtest_qom_set_bool(QTestState *s, const char *path, const char *property,
1568 bool value)
1570 QDict *r;
1572 r = qtest_qmp(s, "{ 'execute': 'qom-set', 'arguments': "
1573 "{ 'path': %s, 'property': %s, 'value': %i } }",
1574 path, property, value);
1575 qobject_unref(r);
1578 bool qtest_qom_get_bool(QTestState *s, const char *path, const char *property)
1580 QDict *r;
1581 bool b;
1583 r = qtest_qmp(s, "{ 'execute': 'qom-get', 'arguments': "
1584 "{ 'path': %s, 'property': %s } }", path, property);
1585 b = qdict_get_bool(r, "return");
1586 qobject_unref(r);
1588 return b;