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__ */
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"
41 # define SOCKET_TIMEOUT 50
42 # define CMD_EXEC "exec "
43 # define DEV_STDERR "/dev/fd/2"
44 # define DEV_NULL "/dev/null"
46 # define SOCKET_TIMEOUT 50000
48 # define DEV_STDERR "2"
49 # define DEV_NULL "nul"
52 #define WAITPID_TIMEOUT 30
54 typedef void (*QTestSendFn
)(QTestState
*s
, const char *buf
);
55 typedef void (*ExternalSendFn
)(void *s
, const char *buf
);
56 typedef GString
* (*QTestRecvFn
)(QTestState
*);
58 typedef struct QTestClientTransportOps
{
59 QTestSendFn send
; /* for sending qtest commands */
62 * use external_send to send qtest command strings through functions which
63 * do not accept a QTestState as the first parameter.
65 ExternalSendFn external_send
;
67 QTestRecvFn recv_line
; /* for receiving qtest command responses */
74 pid_t qemu_pid
; /* our child QEMU process */
81 bool irq_level
[MAX_IRQ
];
83 QTestTransportOps ops
;
84 GList
*pending_events
;
85 QTestQMPEventCallback eventCB
;
89 static GHookList abrt_hooks
;
90 static void (*sighandler_old
)(int);
92 static int qtest_query_target_endianness(QTestState
*s
);
94 static void qtest_client_socket_send(QTestState
*, const char *buf
);
95 static void socket_send(int fd
, const char *buf
, size_t size
);
97 static GString
*qtest_client_socket_recv_line(QTestState
*);
99 static void qtest_client_set_tx_handler(QTestState
*s
, QTestSendFn send
);
100 static void qtest_client_set_rx_handler(QTestState
*s
, QTestRecvFn recv
);
102 static int init_socket(const char *socket_path
)
104 int sock
= qtest_socket_server(socket_path
);
105 qemu_set_cloexec(sock
);
109 static int socket_accept(int sock
)
111 struct sockaddr_un addr
;
115 * timeout unit of blocking receive calls is different among platfoms.
116 * It's in seconds on non-Windows platforms but milliseconds on Windows.
119 struct timeval timeout
= { .tv_sec
= SOCKET_TIMEOUT
,
122 DWORD timeout
= SOCKET_TIMEOUT
;
125 if (setsockopt(sock
, SOL_SOCKET
, SO_RCVTIMEO
,
126 (void *)&timeout
, sizeof(timeout
))) {
127 fprintf(stderr
, "%s failed to set SO_RCVTIMEO: %s\n",
128 __func__
, strerror(errno
));
134 addrlen
= sizeof(addr
);
135 ret
= accept(sock
, (struct sockaddr
*)&addr
, &addrlen
);
136 } while (ret
== -1 && errno
== EINTR
);
138 fprintf(stderr
, "%s failed: %s\n", __func__
, strerror(errno
));
145 pid_t
qtest_pid(QTestState
*s
)
150 bool qtest_probe_child(QTestState
*s
)
152 pid_t pid
= s
->qemu_pid
;
156 pid
= waitpid(pid
, &s
->wstatus
, WNOHANG
);
161 GetExitCodeProcess((HANDLE
)pid
, &s
->exit_code
);
162 if (s
->exit_code
== STILL_ACTIVE
) {
165 CloseHandle((HANDLE
)pid
);
168 qtest_remove_abrt_handler(s
);
173 void qtest_set_expected_status(QTestState
*s
, int status
)
175 s
->expected_status
= status
;
178 static void qtest_check_status(QTestState
*s
)
180 assert(s
->qemu_pid
== -1);
183 * Check whether qemu exited with expected exit status; anything else is
184 * fishy and should be logged with as much detail as possible.
187 int wstatus
= s
->wstatus
;
188 if (WIFEXITED(wstatus
) && WEXITSTATUS(wstatus
) != s
->expected_status
) {
189 fprintf(stderr
, "%s:%d: kill_qemu() tried to terminate QEMU "
190 "process but encountered exit status %d (expected %d)\n",
191 __FILE__
, __LINE__
, WEXITSTATUS(wstatus
), s
->expected_status
);
193 } else if (WIFSIGNALED(wstatus
)) {
194 int sig
= WTERMSIG(wstatus
);
195 const char *signame
= strsignal(sig
) ?: "unknown ???";
196 const char *dump
= WCOREDUMP(wstatus
) ? " (core dumped)" : "";
198 fprintf(stderr
, "%s:%d: kill_qemu() detected QEMU death "
199 "from signal %d (%s)%s\n",
200 __FILE__
, __LINE__
, sig
, signame
, dump
);
204 if (s
->exit_code
!= s
->expected_status
) {
205 fprintf(stderr
, "%s:%d: kill_qemu() tried to terminate QEMU "
206 "process but encountered exit status %ld (expected %d)\n",
207 __FILE__
, __LINE__
, s
->exit_code
, s
->expected_status
);
213 void qtest_wait_qemu(QTestState
*s
)
215 if (s
->qemu_pid
!= -1) {
220 /* poll for a while until sending SIGKILL */
221 end
= g_get_monotonic_time() + WAITPID_TIMEOUT
* G_TIME_SPAN_SECOND
;
224 pid
= waitpid(s
->qemu_pid
, &s
->wstatus
, WNOHANG
);
228 g_usleep(100 * 1000);
229 } while (g_get_monotonic_time() < end
);
232 kill(s
->qemu_pid
, SIGKILL
);
233 pid
= RETRY_ON_EINTR(waitpid(s
->qemu_pid
, &s
->wstatus
, 0));
236 assert(pid
== s
->qemu_pid
);
240 ret
= WaitForSingleObject((HANDLE
)s
->qemu_pid
, INFINITE
);
241 assert(ret
== WAIT_OBJECT_0
);
242 GetExitCodeProcess((HANDLE
)s
->qemu_pid
, &s
->exit_code
);
243 CloseHandle((HANDLE
)s
->qemu_pid
);
247 qtest_remove_abrt_handler(s
);
249 qtest_check_status(s
);
252 void qtest_kill_qemu(QTestState
*s
)
254 /* Skip wait if qtest_probe_child() already reaped */
255 if (s
->qemu_pid
!= -1) {
257 kill(s
->qemu_pid
, SIGTERM
);
259 TerminateProcess((HANDLE
)s
->qemu_pid
, s
->expected_status
);
265 qtest_check_status(s
);
268 static void kill_qemu_hook_func(void *s
)
273 static void sigabrt_handler(int signo
)
275 g_hook_list_invoke(&abrt_hooks
, FALSE
);
278 static void setup_sigabrt_handler(void)
280 sighandler_old
= signal(SIGABRT
, sigabrt_handler
);
283 static void cleanup_sigabrt_handler(void)
285 signal(SIGABRT
, sighandler_old
);
288 static bool hook_list_is_empty(GHookList
*hook_list
)
290 GHook
*hook
= g_hook_first_valid(hook_list
, TRUE
);
296 g_hook_unref(hook_list
, hook
);
300 void qtest_add_abrt_handler(GHookFunc fn
, const void *data
)
304 if (!abrt_hooks
.is_setup
) {
305 g_hook_list_init(&abrt_hooks
, sizeof(GHook
));
308 /* Only install SIGABRT handler once */
309 if (hook_list_is_empty(&abrt_hooks
)) {
310 setup_sigabrt_handler();
313 hook
= g_hook_alloc(&abrt_hooks
);
315 hook
->data
= (void *)data
;
317 g_hook_prepend(&abrt_hooks
, hook
);
320 void qtest_remove_abrt_handler(void *data
)
322 GHook
*hook
= g_hook_find_data(&abrt_hooks
, TRUE
, data
);
328 g_hook_destroy_link(&abrt_hooks
, hook
);
330 /* Uninstall SIGABRT handler on last instance */
331 if (hook_list_is_empty(&abrt_hooks
)) {
332 cleanup_sigabrt_handler();
336 static const char *qtest_qemu_binary(void)
338 const char *qemu_bin
;
340 qemu_bin
= getenv("QTEST_QEMU_BINARY");
342 fprintf(stderr
, "Environment variable QTEST_QEMU_BINARY required\n");
350 static pid_t
qtest_create_process(char *cmd
)
353 PROCESS_INFORMATION pi
;
356 ZeroMemory(&si
, sizeof(si
));
358 ZeroMemory(&pi
, sizeof(pi
));
360 ret
= CreateProcess(NULL
, /* module name */
361 cmd
, /* command line */
362 NULL
, /* process handle not inheritable */
363 NULL
, /* thread handle not inheritable */
364 FALSE
, /* set handle inheritance to FALSE */
365 0, /* No creation flags */
366 NULL
, /* use parent's environment block */
367 NULL
, /* use parent's starting directory */
368 &si
, /* pointer to STARTUPINFO structure */
369 &pi
/* pointer to PROCESS_INFORMATION structure */
372 fprintf(stderr
, "%s:%d: unable to create a new process (%s)\n",
373 __FILE__
, __LINE__
, strerror(GetLastError()));
377 return (pid_t
)pi
.hProcess
;
381 static QTestState
*G_GNUC_PRINTF(1, 2) qtest_spawn_qemu(const char *fmt
, ...)
384 QTestState
*s
= g_new0(QTestState
, 1);
385 const char *trace
= g_getenv("QTEST_TRACE");
386 g_autofree
char *tracearg
= trace
?
387 g_strdup_printf("-trace %s ", trace
) : g_strdup("");
388 g_autoptr(GString
) command
= g_string_new("");
391 g_string_append_printf(command
, CMD_EXEC
"%s %s",
392 qtest_qemu_binary(), tracearg
);
393 g_string_append_vprintf(command
, fmt
, ap
);
396 qtest_add_abrt_handler(kill_qemu_hook_func
, s
);
398 g_test_message("starting QEMU: %s", command
->str
);
401 s
->qemu_pid
= fork();
402 if (s
->qemu_pid
== 0) {
405 * Although we register a ABRT handler to kill off QEMU
406 * when g_assert() triggers, we want an extra safety
407 * net. The QEMU process might be non-functional and
408 * thus not have responded to SIGTERM. The test script
409 * might also have crashed with SEGV, in which case the
410 * cleanup handlers won't ever run.
412 * This PR_SET_PDEATHSIG setup will ensure any remaining
413 * QEMU will get terminated with SIGKILL in these cases.
415 prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0);
416 #endif /* __linux__ */
417 if (!g_setenv("QEMU_AUDIO_DRV", "none", true)) {
420 execlp("/bin/sh", "sh", "-c", command
->str
, NULL
);
424 s
->qemu_pid
= qtest_create_process(command
->str
);
430 QTestState
*qtest_init_without_qmp_handshake(const char *extra_args
)
433 int sock
, qmpsock
, i
;
435 gchar
*qmp_socket_path
;
437 socket_path
= g_strdup_printf("%s/qtest-%d.sock",
438 g_get_tmp_dir(), getpid());
439 qmp_socket_path
= g_strdup_printf("%s/qtest-%d.qmp",
440 g_get_tmp_dir(), getpid());
443 * It's possible that if an earlier test run crashed it might
444 * have left a stale unix socket lying around. Delete any
445 * stale old socket to avoid spurious test failures with
446 * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1)
449 unlink(qmp_socket_path
);
452 sock
= init_socket(socket_path
);
453 qmpsock
= init_socket(qmp_socket_path
);
455 s
= qtest_spawn_qemu("-qtest unix:%s "
457 "-chardev socket,path=%s,id=char0 "
458 "-mon chardev=char0,mode=control "
463 getenv("QTEST_LOG") ? DEV_STDERR
: DEV_NULL
,
467 qtest_client_set_rx_handler(s
, qtest_client_socket_recv_line
);
468 qtest_client_set_tx_handler(s
, qtest_client_socket_send
);
470 s
->fd
= socket_accept(sock
);
472 s
->qmp_fd
= socket_accept(qmpsock
);
475 unlink(qmp_socket_path
);
477 g_free(qmp_socket_path
);
479 g_assert(s
->fd
>= 0 && s
->qmp_fd
>= 0);
481 s
->rx
= g_string_new("");
482 for (i
= 0; i
< MAX_IRQ
; i
++) {
483 s
->irq_level
[i
] = false;
487 * Stopping QEMU for debugging is not supported on Windows.
489 * Using DebugActiveProcess() API can suspend the QEMU process,
490 * but gdb cannot attach to the process. Using the undocumented
491 * NtSuspendProcess() can suspend the QEMU process and gdb can
492 * attach to the process, but gdb cannot resume it.
495 if (getenv("QTEST_STOP")) {
496 kill(s
->qemu_pid
, SIGSTOP
);
500 /* ask endianness of the target */
502 s
->big_endian
= qtest_query_target_endianness(s
);
507 QTestState
*qtest_init(const char *extra_args
)
509 QTestState
*s
= qtest_init_without_qmp_handshake(extra_args
);
512 /* Read the QMP greeting and then do the handshake */
513 greeting
= qtest_qmp_receive(s
);
514 qobject_unref(greeting
);
515 qobject_unref(qtest_qmp(s
, "{ 'execute': 'qmp_capabilities' }"));
520 QTestState
*qtest_vinitf(const char *fmt
, va_list ap
)
522 char *args
= g_strdup_vprintf(fmt
, ap
);
525 s
= qtest_init(args
);
530 QTestState
*qtest_initf(const char *fmt
, ...)
536 s
= qtest_vinitf(fmt
, ap
);
541 QTestState
*qtest_init_with_serial(const char *extra_args
, int *sock_fd
)
544 g_autofree
char *sock_dir
= NULL
;
548 sock_dir
= g_dir_make_tmp("qtest-serial-XXXXXX", NULL
);
549 g_assert_true(sock_dir
!= NULL
);
550 sock_path
= g_strdup_printf("%s/sock", sock_dir
);
553 sock_fd_init
= init_socket(sock_path
);
555 qts
= qtest_initf("-chardev socket,id=s0,path=%s -serial chardev:s0 %s",
556 sock_path
, extra_args
);
558 *sock_fd
= socket_accept(sock_fd_init
);
564 g_assert_true(*sock_fd
>= 0);
569 void qtest_quit(QTestState
*s
)
571 qtest_remove_abrt_handler(s
);
576 g_string_free(s
->rx
, true);
578 for (GList
*it
= s
->pending_events
; it
!= NULL
; it
= it
->next
) {
579 qobject_unref((QDict
*)it
->data
);
582 g_list_free(s
->pending_events
);
587 static void socket_send(int fd
, const char *buf
, size_t size
)
589 ssize_t res
= qemu_send_full(fd
, buf
, size
);
594 static void qtest_client_socket_send(QTestState
*s
, const char *buf
)
596 socket_send(s
->fd
, buf
, strlen(buf
));
599 static void G_GNUC_PRINTF(2, 3) qtest_sendf(QTestState
*s
, const char *fmt
, ...)
604 gchar
*str
= g_strdup_vprintf(fmt
, ap
);
611 static GString
*qtest_client_socket_recv_line(QTestState
*s
)
617 while ((eol
= strchr(s
->rx
->str
, '\n')) == NULL
) {
621 len
= recv(s
->fd
, buffer
, sizeof(buffer
), 0);
622 if (len
== -1 && errno
== EINTR
) {
626 if (len
== -1 || len
== 0) {
627 fprintf(stderr
, "Broken pipe\n");
631 g_string_append_len(s
->rx
, buffer
, len
);
634 offset
= eol
- s
->rx
->str
;
635 line
= g_string_new_len(s
->rx
->str
, offset
);
636 g_string_erase(s
->rx
, 0, offset
+ 1);
641 static gchar
**qtest_rsp_args(QTestState
*s
, int expected_args
)
648 line
= s
->ops
.recv_line(s
);
649 words
= g_strsplit(line
->str
, " ", 0);
650 g_string_free(line
, TRUE
);
652 if (strcmp(words
[0], "IRQ") == 0) {
656 g_assert(words
[1] != NULL
);
657 g_assert(words
[2] != NULL
);
659 ret
= qemu_strtol(words
[2], NULL
, 0, &irq
);
661 g_assert_cmpint(irq
, >=, 0);
662 g_assert_cmpint(irq
, <, MAX_IRQ
);
664 if (strcmp(words
[1], "raise") == 0) {
665 s
->irq_level
[irq
] = true;
667 s
->irq_level
[irq
] = false;
674 g_assert(words
[0] != NULL
);
675 g_assert_cmpstr(words
[0], ==, "OK");
677 for (i
= 0; i
< expected_args
; i
++) {
678 g_assert(words
[i
] != NULL
);
684 static void qtest_rsp(QTestState
*s
)
686 gchar
**words
= qtest_rsp_args(s
, 0);
691 static int qtest_query_target_endianness(QTestState
*s
)
696 qtest_sendf(s
, "endianness\n");
697 args
= qtest_rsp_args(s
, 1);
698 g_assert(strcmp(args
[1], "big") == 0 || strcmp(args
[1], "little") == 0);
699 big_endian
= strcmp(args
[1], "big") == 0;
705 QDict
*qtest_qmp_receive(QTestState
*s
)
708 QDict
*response
= qtest_qmp_receive_dict(s
);
710 if (!qdict_get_try_str(response
, "event")) {
715 !s
->eventCB(s
, qdict_get_str(response
, "event"),
716 response
, s
->eventData
)) {
717 /* Stash the event for a later consumption */
718 s
->pending_events
= g_list_append(s
->pending_events
, response
);
723 QDict
*qtest_qmp_receive_dict(QTestState
*s
)
725 return qmp_fd_receive(s
->qmp_fd
);
728 int qtest_socket_server(const char *socket_path
)
730 struct sockaddr_un addr
;
734 sock
= socket(PF_UNIX
, SOCK_STREAM
, 0);
735 g_assert_cmpint(sock
, !=, -1);
737 addr
.sun_family
= AF_UNIX
;
738 snprintf(addr
.sun_path
, sizeof(addr
.sun_path
), "%s", socket_path
);
740 ret
= RETRY_ON_EINTR(bind(sock
, (struct sockaddr
*)&addr
, sizeof(addr
)));
741 g_assert_cmpint(ret
, !=, -1);
742 ret
= listen(sock
, 1);
743 g_assert_cmpint(ret
, !=, -1);
749 void qtest_qmp_vsend_fds(QTestState
*s
, int *fds
, size_t fds_num
,
750 const char *fmt
, va_list ap
)
752 qmp_fd_vsend_fds(s
->qmp_fd
, fds
, fds_num
, fmt
, ap
);
756 void qtest_qmp_vsend(QTestState
*s
, const char *fmt
, va_list ap
)
758 qmp_fd_vsend(s
->qmp_fd
, fmt
, ap
);
762 QDict
*qtest_vqmp_fds(QTestState
*s
, int *fds
, size_t fds_num
,
763 const char *fmt
, va_list ap
)
765 qtest_qmp_vsend_fds(s
, fds
, fds_num
, fmt
, ap
);
768 return qtest_qmp_receive(s
);
772 QDict
*qtest_vqmp(QTestState
*s
, const char *fmt
, va_list ap
)
774 qtest_qmp_vsend(s
, fmt
, ap
);
777 return qtest_qmp_receive(s
);
781 QDict
*qtest_qmp_fds(QTestState
*s
, int *fds
, size_t fds_num
,
782 const char *fmt
, ...)
788 response
= qtest_vqmp_fds(s
, fds
, fds_num
, fmt
, ap
);
794 QDict
*qtest_qmp(QTestState
*s
, const char *fmt
, ...)
800 response
= qtest_vqmp(s
, fmt
, ap
);
805 void qtest_qmp_send(QTestState
*s
, const char *fmt
, ...)
810 qtest_qmp_vsend(s
, fmt
, ap
);
814 void qtest_qmp_send_raw(QTestState
*s
, const char *fmt
, ...)
819 qmp_fd_vsend_raw(s
->qmp_fd
, fmt
, ap
);
823 void qtest_qmp_set_event_callback(QTestState
*s
,
824 QTestQMPEventCallback cb
, void *opaque
)
827 s
->eventData
= opaque
;
830 QDict
*qtest_qmp_event_ref(QTestState
*s
, const char *event
)
832 while (s
->pending_events
) {
834 GList
*first
= s
->pending_events
;
835 QDict
*response
= (QDict
*)first
->data
;
837 s
->pending_events
= g_list_delete_link(s
->pending_events
, first
);
839 if (!strcmp(qdict_get_str(response
, "event"), event
)) {
842 qobject_unref(response
);
847 QDict
*qtest_qmp_eventwait_ref(QTestState
*s
, const char *event
)
849 QDict
*response
= qtest_qmp_event_ref(s
, event
);
856 response
= qtest_qmp_receive_dict(s
);
857 if ((qdict_haskey(response
, "event")) &&
858 (strcmp(qdict_get_str(response
, "event"), event
) == 0)) {
861 qobject_unref(response
);
865 void qtest_qmp_eventwait(QTestState
*s
, const char *event
)
869 response
= qtest_qmp_eventwait_ref(s
, event
);
870 qobject_unref(response
);
873 char *qtest_vhmp(QTestState
*s
, const char *fmt
, va_list ap
)
879 cmd
= g_strdup_vprintf(fmt
, ap
);
880 resp
= qtest_qmp(s
, "{'execute': 'human-monitor-command',"
881 " 'arguments': {'command-line': %s}}",
883 ret
= g_strdup(qdict_get_try_str(resp
, "return"));
890 char *qtest_hmp(QTestState
*s
, const char *fmt
, ...)
896 ret
= qtest_vhmp(s
, fmt
, ap
);
901 const char *qtest_get_arch(void)
903 const char *qemu
= qtest_qemu_binary();
904 const char *end
= strrchr(qemu
, '-');
907 fprintf(stderr
, "Can't determine architecture from binary name.\n");
911 if (!strstr(qemu
, "-system-")) {
912 fprintf(stderr
, "QTEST_QEMU_BINARY must end with *-system-<arch> "
913 "where 'arch' is the target\narchitecture (x86_64, aarch64, "
921 bool qtest_has_accel(const char *accel_name
)
923 if (g_str_equal(accel_name
, "tcg")) {
924 #if defined(CONFIG_TCG)
929 } else if (g_str_equal(accel_name
, "kvm")) {
931 const char *arch
= qtest_get_arch();
932 const char *targets
[] = { CONFIG_KVM_TARGETS
};
934 for (i
= 0; i
< ARRAY_SIZE(targets
); i
++) {
935 if (!strncmp(targets
[i
], arch
, strlen(arch
))) {
936 if (!access("/dev/kvm", R_OK
| W_OK
)) {
942 /* not implemented */
943 g_assert_not_reached();
948 bool qtest_get_irq(QTestState
*s
, int num
)
950 /* dummy operation in order to make sure irq is up to date */
953 return s
->irq_level
[num
];
956 void qtest_module_load(QTestState
*s
, const char *prefix
, const char *libname
)
958 qtest_sendf(s
, "module_load %s %s\n", prefix
, libname
);
962 static int64_t qtest_clock_rsp(QTestState
*s
)
966 words
= qtest_rsp_args(s
, 2);
967 clock
= g_ascii_strtoll(words
[1], NULL
, 0);
972 int64_t qtest_clock_step_next(QTestState
*s
)
974 qtest_sendf(s
, "clock_step\n");
975 return qtest_clock_rsp(s
);
978 int64_t qtest_clock_step(QTestState
*s
, int64_t step
)
980 qtest_sendf(s
, "clock_step %"PRIi64
"\n", step
);
981 return qtest_clock_rsp(s
);
984 int64_t qtest_clock_set(QTestState
*s
, int64_t val
)
986 qtest_sendf(s
, "clock_set %"PRIi64
"\n", val
);
987 return qtest_clock_rsp(s
);
990 void qtest_irq_intercept_out(QTestState
*s
, const char *qom_path
)
992 qtest_sendf(s
, "irq_intercept_out %s\n", qom_path
);
996 void qtest_irq_intercept_in(QTestState
*s
, const char *qom_path
)
998 qtest_sendf(s
, "irq_intercept_in %s\n", qom_path
);
1002 void qtest_set_irq_in(QTestState
*s
, const char *qom_path
, const char *name
,
1006 name
= "unnamed-gpio-in";
1008 qtest_sendf(s
, "set_irq_in %s %s %d %d\n", qom_path
, name
, num
, level
);
1012 static void qtest_out(QTestState
*s
, const char *cmd
, uint16_t addr
, uint32_t value
)
1014 qtest_sendf(s
, "%s 0x%x 0x%x\n", cmd
, addr
, value
);
1018 void qtest_outb(QTestState
*s
, uint16_t addr
, uint8_t value
)
1020 qtest_out(s
, "outb", addr
, value
);
1023 void qtest_outw(QTestState
*s
, uint16_t addr
, uint16_t value
)
1025 qtest_out(s
, "outw", addr
, value
);
1028 void qtest_outl(QTestState
*s
, uint16_t addr
, uint32_t value
)
1030 qtest_out(s
, "outl", addr
, value
);
1033 static uint32_t qtest_in(QTestState
*s
, const char *cmd
, uint16_t addr
)
1037 unsigned long value
;
1039 qtest_sendf(s
, "%s 0x%x\n", cmd
, addr
);
1040 args
= qtest_rsp_args(s
, 2);
1041 ret
= qemu_strtoul(args
[1], NULL
, 0, &value
);
1042 g_assert(!ret
&& value
<= UINT32_MAX
);
1048 uint8_t qtest_inb(QTestState
*s
, uint16_t addr
)
1050 return qtest_in(s
, "inb", addr
);
1053 uint16_t qtest_inw(QTestState
*s
, uint16_t addr
)
1055 return qtest_in(s
, "inw", addr
);
1058 uint32_t qtest_inl(QTestState
*s
, uint16_t addr
)
1060 return qtest_in(s
, "inl", addr
);
1063 static void qtest_write(QTestState
*s
, const char *cmd
, uint64_t addr
,
1066 qtest_sendf(s
, "%s 0x%" PRIx64
" 0x%" PRIx64
"\n", cmd
, addr
, value
);
1070 void qtest_writeb(QTestState
*s
, uint64_t addr
, uint8_t value
)
1072 qtest_write(s
, "writeb", addr
, value
);
1075 void qtest_writew(QTestState
*s
, uint64_t addr
, uint16_t value
)
1077 qtest_write(s
, "writew", addr
, value
);
1080 void qtest_writel(QTestState
*s
, uint64_t addr
, uint32_t value
)
1082 qtest_write(s
, "writel", addr
, value
);
1085 void qtest_writeq(QTestState
*s
, uint64_t addr
, uint64_t value
)
1087 qtest_write(s
, "writeq", addr
, value
);
1090 static uint64_t qtest_read(QTestState
*s
, const char *cmd
, uint64_t addr
)
1096 qtest_sendf(s
, "%s 0x%" PRIx64
"\n", cmd
, addr
);
1097 args
= qtest_rsp_args(s
, 2);
1098 ret
= qemu_strtou64(args
[1], NULL
, 0, &value
);
1105 uint8_t qtest_readb(QTestState
*s
, uint64_t addr
)
1107 return qtest_read(s
, "readb", addr
);
1110 uint16_t qtest_readw(QTestState
*s
, uint64_t addr
)
1112 return qtest_read(s
, "readw", addr
);
1115 uint32_t qtest_readl(QTestState
*s
, uint64_t addr
)
1117 return qtest_read(s
, "readl", addr
);
1120 uint64_t qtest_readq(QTestState
*s
, uint64_t addr
)
1122 return qtest_read(s
, "readq", addr
);
1125 static int hex2nib(char ch
)
1127 if (ch
>= '0' && ch
<= '9') {
1129 } else if (ch
>= 'a' && ch
<= 'f') {
1130 return 10 + (ch
- 'a');
1131 } else if (ch
>= 'A' && ch
<= 'F') {
1132 return 10 + (ch
- 'a');
1138 void qtest_memread(QTestState
*s
, uint64_t addr
, void *data
, size_t size
)
1140 uint8_t *ptr
= data
;
1148 qtest_sendf(s
, "read 0x%" PRIx64
" 0x%zx\n", addr
, size
);
1149 args
= qtest_rsp_args(s
, 2);
1151 for (i
= 0; i
< size
; i
++) {
1152 ptr
[i
] = hex2nib(args
[1][2 + (i
* 2)]) << 4;
1153 ptr
[i
] |= hex2nib(args
[1][2 + (i
* 2) + 1]);
1159 uint64_t qtest_rtas_call(QTestState
*s
, const char *name
,
1160 uint32_t nargs
, uint64_t args
,
1161 uint32_t nret
, uint64_t ret
)
1163 qtest_sendf(s
, "rtas %s %u 0x%"PRIx64
" %u 0x%"PRIx64
"\n",
1164 name
, nargs
, args
, nret
, ret
);
1169 void qtest_add_func(const char *str
, void (*fn
)(void))
1171 gchar
*path
= g_strdup_printf("/%s/%s", qtest_get_arch(), str
);
1172 g_test_add_func(path
, fn
);
1176 void qtest_add_data_func_full(const char *str
, void *data
,
1177 void (*fn
)(const void *),
1178 GDestroyNotify data_free_func
)
1180 gchar
*path
= g_strdup_printf("/%s/%s", qtest_get_arch(), str
);
1181 g_test_add_data_func_full(path
, data
, fn
, data_free_func
);
1185 void qtest_add_data_func(const char *str
, const void *data
,
1186 void (*fn
)(const void *))
1188 gchar
*path
= g_strdup_printf("/%s/%s", qtest_get_arch(), str
);
1189 g_test_add_data_func(path
, data
, fn
);
1193 void qtest_bufwrite(QTestState
*s
, uint64_t addr
, const void *data
, size_t size
)
1197 bdata
= g_base64_encode(data
, size
);
1198 qtest_sendf(s
, "b64write 0x%" PRIx64
" 0x%zx ", addr
, size
);
1199 s
->ops
.send(s
, bdata
);
1200 s
->ops
.send(s
, "\n");
1205 void qtest_bufread(QTestState
*s
, uint64_t addr
, void *data
, size_t size
)
1210 qtest_sendf(s
, "b64read 0x%" PRIx64
" 0x%zx\n", addr
, size
);
1211 args
= qtest_rsp_args(s
, 2);
1213 g_base64_decode_inplace(args
[1], &len
);
1215 fprintf(stderr
, "bufread: asked for %zu bytes but decoded %zu\n",
1217 len
= MIN(len
, size
);
1220 memcpy(data
, args
[1], len
);
1224 void qtest_memwrite(QTestState
*s
, uint64_t addr
, const void *data
, size_t size
)
1226 const uint8_t *ptr
= data
;
1234 enc
= g_malloc(2 * size
+ 1);
1236 for (i
= 0; i
< size
; i
++) {
1237 sprintf(&enc
[i
* 2], "%02x", ptr
[i
]);
1240 qtest_sendf(s
, "write 0x%" PRIx64
" 0x%zx 0x%s\n", addr
, size
, enc
);
1245 void qtest_memset(QTestState
*s
, uint64_t addr
, uint8_t pattern
, size_t size
)
1247 qtest_sendf(s
, "memset 0x%" PRIx64
" 0x%zx 0x%02x\n", addr
, size
, pattern
);
1251 QDict
*qtest_vqmp_assert_success_ref(QTestState
*qts
,
1252 const char *fmt
, va_list args
)
1257 response
= qtest_vqmp(qts
, fmt
, args
);
1260 if (!qdict_haskey(response
, "return")) {
1261 g_autoptr(GString
) s
= qobject_to_json_pretty(QOBJECT(response
), true);
1262 g_test_message("%s", s
->str
);
1264 g_assert(qdict_haskey(response
, "return"));
1265 ret
= qdict_get_qdict(response
, "return");
1267 qobject_unref(response
);
1272 void qtest_vqmp_assert_success(QTestState
*qts
,
1273 const char *fmt
, va_list args
)
1277 response
= qtest_vqmp_assert_success_ref(qts
, fmt
, args
);
1279 qobject_unref(response
);
1283 QDict
*qtest_vqmp_fds_assert_success_ref(QTestState
*qts
, int *fds
, size_t nfds
,
1284 const char *fmt
, va_list args
)
1289 response
= qtest_vqmp_fds(qts
, fds
, nfds
, fmt
, args
);
1292 if (!qdict_haskey(response
, "return")) {
1293 g_autoptr(GString
) s
= qobject_to_json_pretty(QOBJECT(response
), true);
1294 g_test_message("%s", s
->str
);
1296 g_assert(qdict_haskey(response
, "return"));
1297 ret
= qdict_get_qdict(response
, "return");
1299 qobject_unref(response
);
1304 void qtest_vqmp_fds_assert_success(QTestState
*qts
, int *fds
, size_t nfds
,
1305 const char *fmt
, va_list args
)
1308 response
= qtest_vqmp_fds_assert_success_ref(qts
, fds
, nfds
, fmt
, args
);
1309 qobject_unref(response
);
1311 #endif /* !_WIN32 */
1313 QDict
*qtest_qmp_assert_success_ref(QTestState
*qts
, const char *fmt
, ...)
1318 response
= qtest_vqmp_assert_success_ref(qts
, fmt
, ap
);
1323 void qtest_qmp_assert_success(QTestState
*qts
, const char *fmt
, ...)
1327 qtest_vqmp_assert_success(qts
, fmt
, ap
);
1332 QDict
*qtest_qmp_fds_assert_success_ref(QTestState
*qts
, int *fds
, size_t nfds
,
1333 const char *fmt
, ...)
1338 response
= qtest_vqmp_fds_assert_success_ref(qts
, fds
, nfds
, fmt
, ap
);
1343 void qtest_qmp_fds_assert_success(QTestState
*qts
, int *fds
, size_t nfds
,
1344 const char *fmt
, ...)
1348 qtest_vqmp_fds_assert_success(qts
, fds
, nfds
, fmt
, ap
);
1351 #endif /* !_WIN32 */
1353 bool qtest_big_endian(QTestState
*s
)
1355 return s
->big_endian
;
1358 static bool qtest_check_machine_version(const char *mname
, const char *basename
,
1359 int major
, int minor
)
1364 newname
= g_strdup_printf("%s-%i.%i", basename
, major
, minor
);
1365 is_equal
= g_str_equal(mname
, newname
);
1371 static bool qtest_is_old_versioned_machine(const char *mname
)
1373 const char *dash
= strrchr(mname
, '-');
1374 const char *dot
= strrchr(mname
, '.');
1377 const int major
= QEMU_VERSION_MAJOR
;
1378 const int minor
= QEMU_VERSION_MINOR
;
1381 if (dash
&& dot
&& dot
> dash
) {
1382 for (chr
= dash
+ 1; *chr
; chr
++) {
1383 if (!qemu_isdigit(*chr
) && *chr
!= '.') {
1388 * Now check if it is one of the latest versions. Check major + 1
1389 * and minor + 1 versions as well, since they might already exist
1390 * in the development branch.
1392 bname
= g_strdup(mname
);
1393 bname
[dash
- mname
] = 0;
1394 res
= !qtest_check_machine_version(mname
, bname
, major
+ 1, 0) &&
1395 !qtest_check_machine_version(mname
, bname
, major
, minor
+ 1) &&
1396 !qtest_check_machine_version(mname
, bname
, major
, minor
);
1409 * Returns an array with pointers to the available machine names.
1410 * The terminating entry has the name set to NULL.
1412 static struct MachInfo
*qtest_get_machines(void)
1414 static struct MachInfo
*machines
;
1415 QDict
*response
, *minfo
;
1417 const QListEntry
*p
;
1427 qts
= qtest_init("-machine none");
1428 response
= qtest_qmp(qts
, "{ 'execute': 'query-machines' }");
1430 list
= qdict_get_qlist(response
, "return");
1433 machines
= g_new(struct MachInfo
, qlist_size(list
) + 1);
1435 for (p
= qlist_first(list
), idx
= 0; p
; p
= qlist_next(p
), idx
++) {
1436 minfo
= qobject_to(QDict
, qlist_entry_obj(p
));
1439 qobj
= qdict_get(minfo
, "name");
1441 qstr
= qobject_to(QString
, qobj
);
1443 machines
[idx
].name
= g_strdup(qstring_get_str(qstr
));
1445 qobj
= qdict_get(minfo
, "alias");
1446 if (qobj
) { /* The alias is optional */
1447 qstr
= qobject_to(QString
, qobj
);
1449 machines
[idx
].alias
= g_strdup(qstring_get_str(qstr
));
1451 machines
[idx
].alias
= NULL
;
1456 qobject_unref(response
);
1458 memset(&machines
[idx
], 0, sizeof(struct MachInfo
)); /* Terminating entry */
1462 void qtest_cb_for_every_machine(void (*cb
)(const char *machine
),
1463 bool skip_old_versioned
)
1465 struct MachInfo
*machines
;
1468 machines
= qtest_get_machines();
1470 for (i
= 0; machines
[i
].name
!= NULL
; i
++) {
1471 /* Ignore machines that cannot be used for qtests */
1472 if (!strncmp("xenfv", machines
[i
].name
, 5) ||
1473 g_str_equal("xenpv", machines
[i
].name
) ||
1474 g_str_equal("xenpvh", machines
[i
].name
)) {
1477 if (!skip_old_versioned
||
1478 !qtest_is_old_versioned_machine(machines
[i
].name
)) {
1479 cb(machines
[i
].name
);
1484 bool qtest_has_machine(const char *machine
)
1486 struct MachInfo
*machines
;
1489 machines
= qtest_get_machines();
1491 for (i
= 0; machines
[i
].name
!= NULL
; i
++) {
1492 if (g_str_equal(machine
, machines
[i
].name
) ||
1493 (machines
[i
].alias
&& g_str_equal(machine
, machines
[i
].alias
))) {
1501 bool qtest_has_device(const char *device
)
1504 const QListEntry
*p
;
1513 QTestState
*qts
= qtest_init("-machine none");
1516 qdict_put_bool(args
, "abstract", false);
1517 qdict_put_str(args
, "implements", "device");
1519 resp
= qtest_qmp(qts
, "{'execute': 'qom-list-types', 'arguments': %p }",
1521 g_assert(qdict_haskey(resp
, "return"));
1522 list
= qdict_get_qlist(resp
, "return");
1524 qobject_unref(resp
);
1529 for (p
= qlist_first(list
), idx
= 0; p
; p
= qlist_next(p
), idx
++) {
1530 devinfo
= qobject_to(QDict
, qlist_entry_obj(p
));
1533 qobj
= qdict_get(devinfo
, "name");
1535 qstr
= qobject_to(QString
, qobj
);
1537 if (g_str_equal(qstring_get_str(qstr
), device
)) {
1546 * Generic hot-plugging test via the device_add QMP commands.
1548 void qtest_qmp_device_add_qdict(QTestState
*qts
, const char *drv
,
1549 const QDict
*arguments
)
1552 QDict
*args
= arguments
? qdict_clone_shallow(arguments
) : qdict_new();
1554 g_assert(!qdict_haskey(args
, "driver"));
1555 qdict_put_str(args
, "driver", drv
);
1556 resp
= qtest_qmp(qts
, "{'execute': 'device_add', 'arguments': %p}", args
);
1558 g_assert(!qdict_haskey(resp
, "event")); /* We don't expect any events */
1559 if (qdict_haskey(resp
, "error")) {
1560 fprintf(stderr
, "error: %s\n",
1561 qdict_get_str(qdict_get_qdict(resp
, "error"), "desc"));
1563 g_assert(!qdict_haskey(resp
, "error"));
1564 qobject_unref(resp
);
1567 void qtest_qmp_device_add(QTestState
*qts
, const char *driver
, const char *id
,
1568 const char *fmt
, ...)
1574 args
= qdict_from_vjsonf_nofail(fmt
, ap
);
1577 g_assert(!qdict_haskey(args
, "id"));
1578 qdict_put_str(args
, "id", id
);
1580 qtest_qmp_device_add_qdict(qts
, driver
, args
);
1581 qobject_unref(args
);
1584 void qtest_qmp_add_client(QTestState
*qts
, const char *protocol
, int fd
)
1589 WSAPROTOCOL_INFOW info
;
1590 g_autofree
char *info64
= NULL
;
1593 assert(fd_is_socket(fd
));
1594 s
= _get_osfhandle(fd
);
1595 if (WSADuplicateSocketW(s
, GetProcessId((HANDLE
)qts
->qemu_pid
), &info
) == SOCKET_ERROR
) {
1596 g_autofree
char *emsg
= g_win32_error_message(WSAGetLastError());
1597 g_error("WSADuplicateSocketW failed: %s", emsg
);
1599 info64
= g_base64_encode((guchar
*)&info
, sizeof(info
));
1600 resp
= qtest_qmp(qts
, "{'execute': 'get-win32-socket',"
1601 "'arguments': {'fdname': 'fdname', 'info': %s}}", info64
);
1603 resp
= qtest_qmp_fds(qts
, &fd
, 1, "{'execute': 'getfd',"
1604 "'arguments': {'fdname': 'fdname'}}");
1607 g_assert(!qdict_haskey(resp
, "event")); /* We don't expect any events */
1608 g_assert(!qdict_haskey(resp
, "error"));
1609 qobject_unref(resp
);
1612 qts
, "{'execute': 'add_client',"
1613 "'arguments': {'protocol': %s, 'fdname': 'fdname'}}", protocol
);
1615 g_assert(!qdict_haskey(resp
, "event")); /* We don't expect any events */
1616 g_assert(!qdict_haskey(resp
, "error"));
1617 qobject_unref(resp
);
1621 * Generic hot-unplugging test via the device_del QMP command.
1622 * Device deletion will get one response and one event. For example:
1624 * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1626 * will get this one:
1628 * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1629 * "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1630 * "path": "/machine/peripheral/scsi-hd"}}
1636 void qtest_qmp_device_del_send(QTestState
*qts
, const char *id
)
1638 QDict
*rsp
= qtest_qmp(qts
, "{'execute': 'device_del', "
1639 "'arguments': {'id': %s}}", id
);
1641 g_assert(qdict_haskey(rsp
, "return"));
1642 g_assert(!qdict_haskey(rsp
, "error"));
1646 void qtest_qmp_device_del(QTestState
*qts
, const char *id
)
1648 qtest_qmp_device_del_send(qts
, id
);
1649 qtest_qmp_eventwait(qts
, "DEVICE_DELETED");
1652 static void qtest_client_set_tx_handler(QTestState
*s
,
1657 static void qtest_client_set_rx_handler(QTestState
*s
, QTestRecvFn recv
)
1659 s
->ops
.recv_line
= recv
;
1661 /* A type-safe wrapper for s->send() */
1662 static void send_wrapper(QTestState
*s
, const char *buf
)
1664 s
->ops
.external_send(s
, buf
);
1667 static GString
*qtest_client_inproc_recv_line(QTestState
*s
)
1673 eol
= strchr(s
->rx
->str
, '\n');
1674 offset
= eol
- s
->rx
->str
;
1675 line
= g_string_new_len(s
->rx
->str
, offset
);
1676 g_string_erase(s
->rx
, 0, offset
+ 1);
1680 QTestState
*qtest_inproc_init(QTestState
**s
, bool log
, const char* arch
,
1681 void (*send
)(void*, const char*))
1684 qts
= g_new0(QTestState
, 1);
1685 qts
->pending_events
= NULL
;
1686 *s
= qts
; /* Expose qts early on, since the query endianness relies on it */
1688 for (int i
= 0; i
< MAX_IRQ
; i
++) {
1689 qts
->irq_level
[i
] = false;
1692 qtest_client_set_rx_handler(qts
, qtest_client_inproc_recv_line
);
1694 /* send() may not have a matching protoype, so use a type-safe wrapper */
1695 qts
->ops
.external_send
= send
;
1696 qtest_client_set_tx_handler(qts
, send_wrapper
);
1698 qts
->big_endian
= qtest_query_target_endianness(qts
);
1701 * Set a dummy path for QTEST_QEMU_BINARY. Doesn't need to exist, but this
1702 * way, qtest_get_arch works for inproc qtest.
1704 gchar
*bin_path
= g_strconcat("/qemu-system-", arch
, NULL
);
1705 g_setenv("QTEST_QEMU_BINARY", bin_path
, 0);
1711 void qtest_client_inproc_recv(void *opaque
, const char *str
)
1713 QTestState
*qts
= *(QTestState
**)opaque
;
1716 qts
->rx
= g_string_new(NULL
);
1718 g_string_append(qts
->rx
, str
);
1722 void qtest_qom_set_bool(QTestState
*s
, const char *path
, const char *property
,
1727 r
= qtest_qmp(s
, "{ 'execute': 'qom-set', 'arguments': "
1728 "{ 'path': %s, 'property': %s, 'value': %i } }",
1729 path
, property
, value
);
1733 bool qtest_qom_get_bool(QTestState
*s
, const char *path
, const char *property
)
1738 r
= qtest_qmp(s
, "{ 'execute': 'qom-get', 'arguments': "
1739 "{ 'path': %s, 'property': %s } }", path
, property
);
1740 b
= qdict_get_bool(r
, "return");
1746 bool have_qemu_img(void)
1749 const char *path
= getenv("QTEST_QEMU_IMG");
1754 rpath
= realpath(path
, NULL
);
1763 bool mkimg(const char *file
, const char *fmt
, unsigned size_mb
)
1769 char *qemu_img_path
;
1771 char *qemu_img_abs_path
;
1773 qemu_img_path
= getenv("QTEST_QEMU_IMG");
1774 if (!qemu_img_path
) {
1777 qemu_img_abs_path
= realpath(qemu_img_path
, NULL
);
1778 if (!qemu_img_abs_path
) {
1782 cli
= g_strdup_printf("%s create -f %s %s %uM", qemu_img_abs_path
,
1783 fmt
, file
, size_mb
);
1784 ret
= g_spawn_command_line_sync(cli
, &out
, &out2
, &rc
, &err
);
1785 if (err
|| !g_spawn_check_exit_status(rc
, &err
)) {
1786 fprintf(stderr
, "%s\n", err
->message
);
1793 free(qemu_img_abs_path
);