4 * Copyright IBM, Corp. 2012
5 * Copyright Red Hat, Inc. 2012
6 * Copyright SUSE LINUX Products GmbH 2013
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"
20 #include <sys/socket.h>
25 #include <sys/prctl.h>
26 #endif /* __linux__ */
28 #include <sys/procctl.h>
29 #endif /* __FreeBSD__ */
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"
44 # define SOCKET_TIMEOUT 50
45 # define CMD_EXEC "exec "
46 # define DEV_STDERR "/dev/fd/2"
47 # define DEV_NULL "/dev/null"
49 # define SOCKET_TIMEOUT 50000
51 # define DEV_STDERR "2"
52 # define DEV_NULL "nul"
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 */
77 pid_t qemu_pid
; /* our child QEMU process */
84 bool irq_level
[MAX_IRQ
];
86 QTestTransportOps ops
;
87 GList
*pending_events
;
88 QTestQMPEventCallback eventCB
;
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
);
112 static int socket_accept(int sock
)
114 struct sockaddr_un addr
;
118 * timeout unit of blocking receive calls is different among platforms.
119 * It's in seconds on non-Windows platforms but milliseconds on Windows.
122 struct timeval timeout
= { .tv_sec
= SOCKET_TIMEOUT
,
125 DWORD timeout
= SOCKET_TIMEOUT
;
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
));
137 addrlen
= sizeof(addr
);
138 ret
= accept(sock
, (struct sockaddr
*)&addr
, &addrlen
);
139 } while (ret
== -1 && errno
== EINTR
);
141 fprintf(stderr
, "%s failed: %s\n", __func__
, strerror(errno
));
148 pid_t
qtest_pid(QTestState
*s
)
153 bool qtest_probe_child(QTestState
*s
)
155 pid_t pid
= s
->qemu_pid
;
159 pid
= waitpid(pid
, &s
->wstatus
, WNOHANG
);
164 GetExitCodeProcess((HANDLE
)pid
, &s
->exit_code
);
165 if (s
->exit_code
== STILL_ACTIVE
) {
168 CloseHandle((HANDLE
)pid
);
171 qtest_remove_abrt_handler(s
);
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.
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
);
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
);
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
);
216 void qtest_wait_qemu(QTestState
*s
)
218 if (s
->qemu_pid
!= -1) {
223 /* poll for a while until sending SIGKILL */
224 end
= g_get_monotonic_time() + WAITPID_TIMEOUT
* G_TIME_SPAN_SECOND
;
227 pid
= waitpid(s
->qemu_pid
, &s
->wstatus
, WNOHANG
);
231 g_usleep(100 * 1000);
232 } while (g_get_monotonic_time() < end
);
235 kill(s
->qemu_pid
, SIGKILL
);
236 pid
= RETRY_ON_EINTR(waitpid(s
->qemu_pid
, &s
->wstatus
, 0));
239 assert(pid
== s
->qemu_pid
);
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
);
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) {
260 kill(s
->qemu_pid
, SIGTERM
);
262 TerminateProcess((HANDLE
)s
->qemu_pid
, s
->expected_status
);
268 qtest_check_status(s
);
271 static void kill_qemu_hook_func(void *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
);
299 g_hook_unref(hook_list
, hook
);
303 void qtest_add_abrt_handler(GHookFunc fn
, const void *data
)
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
);
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
);
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");
345 fprintf(stderr
, "Environment variable QTEST_QEMU_BINARY required\n");
353 static pid_t
qtest_create_process(char *cmd
)
356 PROCESS_INFORMATION pi
;
359 ZeroMemory(&si
, 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 */
375 fprintf(stderr
, "%s:%d: unable to create a new process (%s)\n",
376 __FILE__
, __LINE__
, strerror(GetLastError()));
380 return (pid_t
)pi
.hProcess
;
384 static QTestState
*G_GNUC_PRINTF(1, 2) qtest_spawn_qemu(const char *fmt
, ...)
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("");
394 g_string_append_printf(command
, CMD_EXEC
"%s %s",
395 qtest_qemu_binary(), tracearg
);
396 g_string_append_vprintf(command
, fmt
, ap
);
399 qtest_add_abrt_handler(kill_qemu_hook_func
, s
);
401 g_test_message("starting QEMU: %s", command
->str
);
404 s
->qemu_pid
= fork();
405 if (s
->qemu_pid
== 0) {
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__ */
422 procctl(P_PID
, getpid(), PROC_PDEATHSIG_CTL
, &sig
);
423 #endif /* __FreeBSD__ */
424 execlp("/bin/sh", "sh", "-c", command
->str
, NULL
);
428 s
->qemu_pid
= qtest_create_process(command
->str
);
434 QTestState
*qtest_init_without_qmp_handshake(const char *extra_args
)
437 int sock
, qmpsock
, i
;
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)
453 unlink(qmp_socket_path
);
456 sock
= init_socket(socket_path
);
457 qmpsock
= init_socket(qmp_socket_path
);
459 s
= qtest_spawn_qemu("-qtest unix:%s "
461 "-chardev socket,path=%s,id=char0 "
462 "-mon chardev=char0,mode=control "
468 getenv("QTEST_LOG") ? DEV_STDERR
: DEV_NULL
,
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
);
477 s
->qmp_fd
= socket_accept(qmpsock
);
480 unlink(qmp_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.
500 if (getenv("QTEST_STOP")) {
501 kill(s
->qemu_pid
, SIGSTOP
);
505 /* ask endianness of the target */
507 s
->big_endian
= qtest_query_target_endianness(s
);
512 QTestState
*qtest_init(const char *extra_args
)
514 QTestState
*s
= qtest_init_without_qmp_handshake(extra_args
);
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' }"));
525 QTestState
*qtest_vinitf(const char *fmt
, va_list ap
)
527 char *args
= g_strdup_vprintf(fmt
, ap
);
530 s
= qtest_init(args
);
535 QTestState
*qtest_initf(const char *fmt
, ...)
541 s
= qtest_vinitf(fmt
, ap
);
546 QTestState
*qtest_init_with_serial(const char *extra_args
, int *sock_fd
)
549 g_autofree
char *sock_dir
= NULL
;
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
);
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
);
569 g_assert_true(*sock_fd
>= 0);
574 void qtest_quit(QTestState
*s
)
576 qtest_remove_abrt_handler(s
);
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
);
592 static void socket_send(int fd
, const char *buf
, size_t size
)
594 ssize_t res
= qemu_send_full(fd
, buf
, 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
, ...)
609 gchar
*str
= g_strdup_vprintf(fmt
, ap
);
616 static GString
*qtest_client_socket_recv_line(QTestState
*s
)
622 while ((eol
= strchr(s
->rx
->str
, '\n')) == NULL
) {
626 len
= recv(s
->fd
, buffer
, sizeof(buffer
), 0);
627 if (len
== -1 && errno
== EINTR
) {
631 if (len
== -1 || len
== 0) {
632 fprintf(stderr
, "Broken pipe\n");
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);
646 static gchar
**qtest_rsp_args(QTestState
*s
, int expected_args
)
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) {
661 g_assert(words
[1] != NULL
);
662 g_assert(words
[2] != NULL
);
664 ret
= qemu_strtol(words
[2], NULL
, 0, &irq
);
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;
672 s
->irq_level
[irq
] = false;
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
);
689 static void qtest_rsp(QTestState
*s
)
691 gchar
**words
= qtest_rsp_args(s
, 0);
696 static int qtest_query_target_endianness(QTestState
*s
)
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;
710 QDict
*qtest_qmp_receive(QTestState
*s
)
713 QDict
*response
= qtest_qmp_receive_dict(s
);
715 if (!qdict_get_try_str(response
, "event")) {
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
;
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);
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
);
761 void qtest_qmp_vsend(QTestState
*s
, const char *fmt
, va_list ap
)
763 qmp_fd_vsend(s
->qmp_fd
, fmt
, ap
);
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
);
773 return qtest_qmp_receive(s
);
777 QDict
*qtest_vqmp(QTestState
*s
, const char *fmt
, va_list ap
)
779 qtest_qmp_vsend(s
, fmt
, ap
);
782 return qtest_qmp_receive(s
);
786 QDict
*qtest_qmp_fds(QTestState
*s
, int *fds
, size_t fds_num
,
787 const char *fmt
, ...)
793 response
= qtest_vqmp_fds(s
, fds
, fds_num
, fmt
, ap
);
799 QDict
*qtest_qmp(QTestState
*s
, const char *fmt
, ...)
805 response
= qtest_vqmp(s
, fmt
, ap
);
810 void qtest_qmp_send(QTestState
*s
, const char *fmt
, ...)
815 qtest_qmp_vsend(s
, fmt
, ap
);
819 void qtest_qmp_send_raw(QTestState
*s
, const char *fmt
, ...)
824 qmp_fd_vsend_raw(s
->qmp_fd
, fmt
, ap
);
828 void qtest_qmp_set_event_callback(QTestState
*s
,
829 QTestQMPEventCallback cb
, void *opaque
)
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
)) {
847 qobject_unref(response
);
852 QDict
*qtest_qmp_eventwait_ref(QTestState
*s
, const char *event
)
854 QDict
*response
= qtest_qmp_event_ref(s
, event
);
861 response
= qtest_qmp_receive_dict(s
);
862 if ((qdict_haskey(response
, "event")) &&
863 (strcmp(qdict_get_str(response
, "event"), event
) == 0)) {
866 qobject_unref(response
);
870 void qtest_qmp_eventwait(QTestState
*s
, const char *event
)
874 response
= qtest_qmp_eventwait_ref(s
, event
);
875 qobject_unref(response
);
878 char *qtest_vhmp(QTestState
*s
, const char *fmt
, va_list ap
)
884 cmd
= g_strdup_vprintf(fmt
, ap
);
885 resp
= qtest_qmp(s
, "{'execute': 'human-monitor-command',"
886 " 'arguments': {'command-line': %s}}",
888 ret
= g_strdup(qdict_get_try_str(resp
, "return"));
895 char *qtest_hmp(QTestState
*s
, const char *fmt
, ...)
901 ret
= qtest_vhmp(s
, fmt
, ap
);
906 const char *qtest_get_arch(void)
908 const char *qemu
= qtest_qemu_binary();
909 const char *end
= strrchr(qemu
, '-');
912 fprintf(stderr
, "Can't determine architecture from binary name.\n");
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, "
926 bool qtest_has_accel(const char *accel_name
)
928 if (g_str_equal(accel_name
, "tcg")) {
929 #if defined(CONFIG_TCG)
934 } else if (g_str_equal(accel_name
, "kvm")) {
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
)) {
947 /* not implemented */
948 g_assert_not_reached();
953 bool qtest_get_irq(QTestState
*s
, int num
)
955 /* dummy operation in order to make sure irq is up to date */
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
);
967 static int64_t qtest_clock_rsp(QTestState
*s
)
971 words
= qtest_rsp_args(s
, 2);
972 clock
= g_ascii_strtoll(words
[1], NULL
, 0);
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
);
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
);
1007 void qtest_irq_intercept_in(QTestState
*s
, const char *qom_path
)
1009 qtest_sendf(s
, "irq_intercept_in %s\n", qom_path
);
1013 void qtest_set_irq_in(QTestState
*s
, const char *qom_path
, const char *name
,
1017 name
= "unnamed-gpio-in";
1019 qtest_sendf(s
, "set_irq_in %s %s %d %d\n", qom_path
, name
, num
, level
);
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
);
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
)
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
);
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
,
1077 qtest_sendf(s
, "%s 0x%" PRIx64
" 0x%" PRIx64
"\n", cmd
, addr
, value
);
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
)
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
);
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') {
1140 } else if (ch
>= 'a' && ch
<= 'f') {
1141 return 10 + (ch
- 'a');
1142 } else if (ch
>= 'A' && ch
<= 'F') {
1143 return 10 + (ch
- 'a');
1149 void qtest_memread(QTestState
*s
, uint64_t addr
, void *data
, size_t size
)
1151 uint8_t *ptr
= data
;
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]);
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
);
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
);
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
);
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
);
1204 void qtest_bufwrite(QTestState
*s
, uint64_t addr
, const void *data
, size_t size
)
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");
1216 void qtest_bufread(QTestState
*s
, uint64_t addr
, void *data
, size_t size
)
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
);
1226 fprintf(stderr
, "bufread: asked for %zu bytes but decoded %zu\n",
1228 len
= MIN(len
, size
);
1231 memcpy(data
, args
[1], len
);
1235 void qtest_memwrite(QTestState
*s
, uint64_t addr
, const void *data
, size_t size
)
1237 const uint8_t *ptr
= data
;
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
);
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
);
1262 QDict
*qtest_vqmp_assert_success_ref(QTestState
*qts
,
1263 const char *fmt
, va_list args
)
1268 response
= qtest_vqmp(qts
, fmt
, args
);
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");
1278 qobject_unref(response
);
1283 void qtest_vqmp_assert_success(QTestState
*qts
,
1284 const char *fmt
, va_list args
)
1288 response
= qtest_vqmp_assert_success_ref(qts
, fmt
, args
);
1290 qobject_unref(response
);
1294 QDict
*qtest_vqmp_fds_assert_success_ref(QTestState
*qts
, int *fds
, size_t nfds
,
1295 const char *fmt
, va_list args
)
1300 response
= qtest_vqmp_fds(qts
, fds
, nfds
, fmt
, args
);
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");
1310 qobject_unref(response
);
1315 void qtest_vqmp_fds_assert_success(QTestState
*qts
, int *fds
, size_t nfds
,
1316 const char *fmt
, va_list args
)
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
, ...)
1329 response
= qtest_vqmp_assert_success_ref(qts
, fmt
, ap
);
1334 void qtest_qmp_assert_success(QTestState
*qts
, const char *fmt
, ...)
1338 qtest_vqmp_assert_success(qts
, fmt
, ap
);
1343 QDict
*qtest_qmp_fds_assert_success_ref(QTestState
*qts
, int *fds
, size_t nfds
,
1344 const char *fmt
, ...)
1349 response
= qtest_vqmp_fds_assert_success_ref(qts
, fds
, nfds
, fmt
, ap
);
1354 void qtest_qmp_fds_assert_success(QTestState
*qts
, int *fds
, size_t nfds
,
1355 const char *fmt
, ...)
1359 qtest_vqmp_fds_assert_success(qts
, fds
, nfds
, fmt
, 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
)
1375 newname
= g_strdup_printf("%s-%i.%i", basename
, major
, minor
);
1376 is_equal
= g_str_equal(mname
, newname
);
1382 static bool qtest_is_old_versioned_machine(const char *mname
)
1384 const char *dash
= strrchr(mname
, '-');
1385 const char *dot
= strrchr(mname
, '.');
1388 const int major
= QEMU_VERSION_MAJOR
;
1389 const int minor
= QEMU_VERSION_MINOR
;
1392 if (dash
&& dot
&& dot
> dash
) {
1393 for (chr
= dash
+ 1; *chr
; chr
++) {
1394 if (!qemu_isdigit(*chr
) && *chr
!= '.') {
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
);
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
;
1428 const QListEntry
*p
;
1438 qts
= qtest_init("-machine none");
1439 response
= qtest_qmp(qts
, "{ 'execute': 'query-machines' }");
1441 list
= qdict_get_qlist(response
, "return");
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
));
1450 qobj
= qdict_get(minfo
, "name");
1452 qstr
= qobject_to(QString
, qobj
);
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
);
1460 machines
[idx
].alias
= g_strdup(qstring_get_str(qstr
));
1462 machines
[idx
].alias
= NULL
;
1467 qobject_unref(response
);
1469 memset(&machines
[idx
], 0, sizeof(struct MachInfo
)); /* Terminating entry */
1473 void qtest_cb_for_every_machine(void (*cb
)(const char *machine
),
1474 bool skip_old_versioned
)
1476 struct MachInfo
*machines
;
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
)) {
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
;
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
))) {
1512 bool qtest_has_device(const char *device
)
1515 const QListEntry
*p
;
1524 QTestState
*qts
= qtest_init("-machine none");
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 }",
1532 g_assert(qdict_haskey(resp
, "return"));
1533 list
= qdict_get_qlist(resp
, "return");
1535 qobject_unref(resp
);
1540 for (p
= qlist_first(list
), idx
= 0; p
; p
= qlist_next(p
), idx
++) {
1541 devinfo
= qobject_to(QDict
, qlist_entry_obj(p
));
1544 qobj
= qdict_get(devinfo
, "name");
1546 qstr
= qobject_to(QString
, qobj
);
1548 if (g_str_equal(qstring_get_str(qstr
), device
)) {
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
)
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
);
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
, ...)
1585 args
= qdict_from_vjsonf_nofail(fmt
, 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
)
1600 WSAPROTOCOL_INFOW info
;
1601 g_autofree
char *info64
= NULL
;
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
);
1614 resp
= qtest_qmp_fds(qts
, &fd
, 1, "{'execute': 'getfd',"
1615 "'arguments': {'fdname': 'fdname'}}");
1618 g_assert(!qdict_haskey(resp
, "event")); /* We don't expect any events */
1619 g_assert(!qdict_haskey(resp
, "error"));
1620 qobject_unref(resp
);
1623 qts
, "{'execute': 'add_client',"
1624 "'arguments': {'protocol': %s, 'fdname': 'fdname'}}", protocol
);
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"}}
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
);
1652 g_assert(qdict_haskey(rsp
, "return"));
1653 g_assert(!qdict_haskey(rsp
, "error"));
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
,
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
)
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);
1691 QTestState
*qtest_inproc_init(QTestState
**s
, bool log
, const char* arch
,
1692 void (*send
)(void*, const char*))
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 */
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);
1722 void qtest_client_inproc_recv(void *opaque
, const char *str
)
1724 QTestState
*qts
= *(QTestState
**)opaque
;
1727 qts
->rx
= g_string_new(NULL
);
1729 g_string_append(qts
->rx
, str
);
1733 void qtest_qom_set_bool(QTestState
*s
, const char *path
, const char *property
,
1738 r
= qtest_qmp(s
, "{ 'execute': 'qom-set', 'arguments': "
1739 "{ 'path': %s, 'property': %s, 'value': %i } }",
1740 path
, property
, value
);
1744 bool qtest_qom_get_bool(QTestState
*s
, const char *path
, const char *property
)
1749 r
= qtest_qmp(s
, "{ 'execute': 'qom-get', 'arguments': "
1750 "{ 'path': %s, 'property': %s } }", path
, property
);
1751 b
= qdict_get_bool(r
, "return");
1757 bool have_qemu_img(void)
1760 const char *path
= getenv("QTEST_QEMU_IMG");
1765 rpath
= realpath(path
, NULL
);
1774 bool mkimg(const char *file
, const char *fmt
, unsigned size_mb
)
1780 char *qemu_img_path
;
1782 char *qemu_img_abs_path
;
1784 qemu_img_path
= getenv("QTEST_QEMU_IMG");
1785 if (!qemu_img_path
) {
1788 qemu_img_abs_path
= realpath(qemu_img_path
, NULL
);
1789 if (!qemu_img_abs_path
) {
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
);
1804 free(qemu_img_abs_path
);