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
;
87 static GHookList abrt_hooks
;
88 static void (*sighandler_old
)(int);
90 static int qtest_query_target_endianness(QTestState
*s
);
92 static void qtest_client_socket_send(QTestState
*, const char *buf
);
93 static void socket_send(int fd
, const char *buf
, size_t size
);
95 static GString
*qtest_client_socket_recv_line(QTestState
*);
97 static void qtest_client_set_tx_handler(QTestState
*s
, QTestSendFn send
);
98 static void qtest_client_set_rx_handler(QTestState
*s
, QTestRecvFn recv
);
100 static int init_socket(const char *socket_path
)
102 int sock
= qtest_socket_server(socket_path
);
103 qemu_set_cloexec(sock
);
107 static int socket_accept(int sock
)
109 struct sockaddr_un addr
;
113 * timeout unit of blocking receive calls is different among platfoms.
114 * It's in seconds on non-Windows platforms but milliseconds on Windows.
117 struct timeval timeout
= { .tv_sec
= SOCKET_TIMEOUT
,
120 DWORD timeout
= SOCKET_TIMEOUT
;
123 if (setsockopt(sock
, SOL_SOCKET
, SO_RCVTIMEO
,
124 (void *)&timeout
, sizeof(timeout
))) {
125 fprintf(stderr
, "%s failed to set SO_RCVTIMEO: %s\n",
126 __func__
, strerror(errno
));
132 addrlen
= sizeof(addr
);
133 ret
= accept(sock
, (struct sockaddr
*)&addr
, &addrlen
);
134 } while (ret
== -1 && errno
== EINTR
);
136 fprintf(stderr
, "%s failed: %s\n", __func__
, strerror(errno
));
143 bool qtest_probe_child(QTestState
*s
)
145 pid_t pid
= s
->qemu_pid
;
149 pid
= waitpid(pid
, &s
->wstatus
, WNOHANG
);
154 GetExitCodeProcess((HANDLE
)pid
, &s
->exit_code
);
155 if (s
->exit_code
== STILL_ACTIVE
) {
158 CloseHandle((HANDLE
)pid
);
165 void qtest_set_expected_status(QTestState
*s
, int status
)
167 s
->expected_status
= status
;
170 static void qtest_check_status(QTestState
*s
)
173 * Check whether qemu exited with expected exit status; anything else is
174 * fishy and should be logged with as much detail as possible.
177 int wstatus
= s
->wstatus
;
178 if (WIFEXITED(wstatus
) && WEXITSTATUS(wstatus
) != s
->expected_status
) {
179 fprintf(stderr
, "%s:%d: kill_qemu() tried to terminate QEMU "
180 "process but encountered exit status %d (expected %d)\n",
181 __FILE__
, __LINE__
, WEXITSTATUS(wstatus
), s
->expected_status
);
183 } else if (WIFSIGNALED(wstatus
)) {
184 int sig
= WTERMSIG(wstatus
);
185 const char *signame
= strsignal(sig
) ?: "unknown ???";
186 const char *dump
= WCOREDUMP(wstatus
) ? " (core dumped)" : "";
188 fprintf(stderr
, "%s:%d: kill_qemu() detected QEMU death "
189 "from signal %d (%s)%s\n",
190 __FILE__
, __LINE__
, sig
, signame
, dump
);
194 if (s
->exit_code
!= s
->expected_status
) {
195 fprintf(stderr
, "%s:%d: kill_qemu() tried to terminate QEMU "
196 "process but encountered exit status %ld (expected %d)\n",
197 __FILE__
, __LINE__
, s
->exit_code
, s
->expected_status
);
203 void qtest_wait_qemu(QTestState
*s
)
209 /* poll for a while until sending SIGKILL */
210 end
= g_get_monotonic_time() + WAITPID_TIMEOUT
* G_TIME_SPAN_SECOND
;
213 pid
= waitpid(s
->qemu_pid
, &s
->wstatus
, WNOHANG
);
217 g_usleep(100 * 1000);
218 } while (g_get_monotonic_time() < end
);
221 kill(s
->qemu_pid
, SIGKILL
);
222 pid
= RETRY_ON_EINTR(waitpid(s
->qemu_pid
, &s
->wstatus
, 0));
225 assert(pid
== s
->qemu_pid
);
229 ret
= WaitForSingleObject((HANDLE
)s
->qemu_pid
, INFINITE
);
230 assert(ret
== WAIT_OBJECT_0
);
231 GetExitCodeProcess((HANDLE
)s
->qemu_pid
, &s
->exit_code
);
232 CloseHandle((HANDLE
)s
->qemu_pid
);
235 qtest_check_status(s
);
238 void qtest_kill_qemu(QTestState
*s
)
240 /* Skip wait if qtest_probe_child() already reaped */
241 if (s
->qemu_pid
!= -1) {
243 kill(s
->qemu_pid
, SIGTERM
);
245 TerminateProcess((HANDLE
)s
->qemu_pid
, s
->expected_status
);
252 qtest_check_status(s
);
255 static void kill_qemu_hook_func(void *s
)
260 static void sigabrt_handler(int signo
)
262 g_hook_list_invoke(&abrt_hooks
, FALSE
);
265 static void setup_sigabrt_handler(void)
267 sighandler_old
= signal(SIGABRT
, sigabrt_handler
);
270 static void cleanup_sigabrt_handler(void)
272 signal(SIGABRT
, sighandler_old
);
275 static bool hook_list_is_empty(GHookList
*hook_list
)
277 GHook
*hook
= g_hook_first_valid(hook_list
, TRUE
);
283 g_hook_unref(hook_list
, hook
);
287 void qtest_add_abrt_handler(GHookFunc fn
, const void *data
)
291 if (!abrt_hooks
.is_setup
) {
292 g_hook_list_init(&abrt_hooks
, sizeof(GHook
));
295 /* Only install SIGABRT handler once */
296 if (hook_list_is_empty(&abrt_hooks
)) {
297 setup_sigabrt_handler();
300 hook
= g_hook_alloc(&abrt_hooks
);
302 hook
->data
= (void *)data
;
304 g_hook_prepend(&abrt_hooks
, hook
);
307 void qtest_remove_abrt_handler(void *data
)
309 GHook
*hook
= g_hook_find_data(&abrt_hooks
, TRUE
, data
);
310 g_hook_destroy_link(&abrt_hooks
, hook
);
312 /* Uninstall SIGABRT handler on last instance */
313 if (hook_list_is_empty(&abrt_hooks
)) {
314 cleanup_sigabrt_handler();
318 static const char *qtest_qemu_binary(void)
320 const char *qemu_bin
;
322 qemu_bin
= getenv("QTEST_QEMU_BINARY");
324 fprintf(stderr
, "Environment variable QTEST_QEMU_BINARY required\n");
332 static pid_t
qtest_create_process(char *cmd
)
335 PROCESS_INFORMATION pi
;
338 ZeroMemory(&si
, sizeof(si
));
340 ZeroMemory(&pi
, sizeof(pi
));
342 ret
= CreateProcess(NULL
, /* module name */
343 cmd
, /* command line */
344 NULL
, /* process handle not inheritable */
345 NULL
, /* thread handle not inheritable */
346 FALSE
, /* set handle inheritance to FALSE */
347 0, /* No creation flags */
348 NULL
, /* use parent's environment block */
349 NULL
, /* use parent's starting directory */
350 &si
, /* pointer to STARTUPINFO structure */
351 &pi
/* pointer to PROCESS_INFORMATION structure */
354 fprintf(stderr
, "%s:%d: unable to create a new process (%s)\n",
355 __FILE__
, __LINE__
, strerror(GetLastError()));
359 return (pid_t
)pi
.hProcess
;
363 QTestState
*qtest_init_without_qmp_handshake(const char *extra_args
)
366 int sock
, qmpsock
, i
;
368 gchar
*qmp_socket_path
;
370 const char *qemu_binary
= qtest_qemu_binary();
371 const char *trace
= g_getenv("QTEST_TRACE");
372 g_autofree
char *tracearg
= trace
?
373 g_strdup_printf("-trace %s ", trace
) : g_strdup("");
375 s
= g_new(QTestState
, 1);
377 socket_path
= g_strdup_printf("%s/qtest-%d.sock",
378 g_get_tmp_dir(), getpid());
379 qmp_socket_path
= g_strdup_printf("%s/qtest-%d.qmp",
380 g_get_tmp_dir(), getpid());
382 /* It's possible that if an earlier test run crashed it might
383 * have left a stale unix socket lying around. Delete any
384 * stale old socket to avoid spurious test failures with
385 * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1)
388 unlink(qmp_socket_path
);
391 sock
= init_socket(socket_path
);
392 qmpsock
= init_socket(qmp_socket_path
);
394 qtest_client_set_rx_handler(s
, qtest_client_socket_recv_line
);
395 qtest_client_set_tx_handler(s
, qtest_client_socket_send
);
397 qtest_add_abrt_handler(kill_qemu_hook_func
, s
);
399 command
= g_strdup_printf(CMD_EXEC
"%s %s"
402 "-chardev socket,path=%s,id=char0 "
403 "-mon chardev=char0,mode=control "
407 qemu_binary
, tracearg
, socket_path
,
408 getenv("QTEST_LOG") ? DEV_STDERR
: DEV_NULL
,
412 g_test_message("starting QEMU: %s", command
);
414 s
->pending_events
= NULL
;
416 s
->expected_status
= 0;
418 s
->qemu_pid
= fork();
419 if (s
->qemu_pid
== 0) {
422 * Although we register a ABRT handler to kill off QEMU
423 * when g_assert() triggers, we want an extra safety
424 * net. The QEMU process might be non-functional and
425 * thus not have responded to SIGTERM. The test script
426 * might also have crashed with SEGV, in which case the
427 * cleanup handlers won't ever run.
429 * This PR_SET_PDEATHSIG setup will ensure any remaining
430 * QEMU will get terminated with SIGKILL in these cases.
432 prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0);
433 #endif /* __linux__ */
434 if (!g_setenv("QEMU_AUDIO_DRV", "none", true)) {
437 execlp("/bin/sh", "sh", "-c", command
, NULL
);
441 s
->qemu_pid
= qtest_create_process(command
);
445 s
->fd
= socket_accept(sock
);
447 s
->qmp_fd
= socket_accept(qmpsock
);
450 unlink(qmp_socket_path
);
452 g_free(qmp_socket_path
);
454 g_assert(s
->fd
>= 0 && s
->qmp_fd
>= 0);
456 s
->rx
= g_string_new("");
457 for (i
= 0; i
< MAX_IRQ
; i
++) {
458 s
->irq_level
[i
] = false;
462 * Stopping QEMU for debugging is not supported on Windows.
464 * Using DebugActiveProcess() API can suspend the QEMU process,
465 * but gdb cannot attach to the process. Using the undocumented
466 * NtSuspendProcess() can suspend the QEMU process and gdb can
467 * attach to the process, but gdb cannot resume it.
470 if (getenv("QTEST_STOP")) {
471 kill(s
->qemu_pid
, SIGSTOP
);
475 /* ask endianness of the target */
477 s
->big_endian
= qtest_query_target_endianness(s
);
482 QTestState
*qtest_init(const char *extra_args
)
484 QTestState
*s
= qtest_init_without_qmp_handshake(extra_args
);
487 /* Read the QMP greeting and then do the handshake */
488 greeting
= qtest_qmp_receive(s
);
489 qobject_unref(greeting
);
490 qobject_unref(qtest_qmp(s
, "{ 'execute': 'qmp_capabilities' }"));
495 QTestState
*qtest_vinitf(const char *fmt
, va_list ap
)
497 char *args
= g_strdup_vprintf(fmt
, ap
);
500 s
= qtest_init(args
);
505 QTestState
*qtest_initf(const char *fmt
, ...)
511 s
= qtest_vinitf(fmt
, ap
);
516 QTestState
*qtest_init_with_serial(const char *extra_args
, int *sock_fd
)
519 g_autofree
char *sock_dir
= NULL
;
523 sock_dir
= g_dir_make_tmp("qtest-serial-XXXXXX", NULL
);
524 g_assert_true(sock_dir
!= NULL
);
525 sock_path
= g_strdup_printf("%s/sock", sock_dir
);
528 sock_fd_init
= init_socket(sock_path
);
530 qts
= qtest_initf("-chardev socket,id=s0,path=%s -serial chardev:s0 %s",
531 sock_path
, extra_args
);
533 *sock_fd
= socket_accept(sock_fd_init
);
539 g_assert_true(*sock_fd
>= 0);
544 void qtest_quit(QTestState
*s
)
546 qtest_remove_abrt_handler(s
);
550 closesocket(s
->qmp_fd
);
551 g_string_free(s
->rx
, true);
553 for (GList
*it
= s
->pending_events
; it
!= NULL
; it
= it
->next
) {
554 qobject_unref((QDict
*)it
->data
);
557 g_list_free(s
->pending_events
);
562 static void socket_send(int fd
, const char *buf
, size_t size
)
564 ssize_t res
= qemu_send_full(fd
, buf
, size
);
569 static void qtest_client_socket_send(QTestState
*s
, const char *buf
)
571 socket_send(s
->fd
, buf
, strlen(buf
));
574 static void G_GNUC_PRINTF(2, 3) qtest_sendf(QTestState
*s
, const char *fmt
, ...)
579 gchar
*str
= g_strdup_vprintf(fmt
, ap
);
586 static GString
*qtest_client_socket_recv_line(QTestState
*s
)
592 while ((eol
= strchr(s
->rx
->str
, '\n')) == NULL
) {
596 len
= recv(s
->fd
, buffer
, sizeof(buffer
), 0);
597 if (len
== -1 && errno
== EINTR
) {
601 if (len
== -1 || len
== 0) {
602 fprintf(stderr
, "Broken pipe\n");
606 g_string_append_len(s
->rx
, buffer
, len
);
609 offset
= eol
- s
->rx
->str
;
610 line
= g_string_new_len(s
->rx
->str
, offset
);
611 g_string_erase(s
->rx
, 0, offset
+ 1);
616 static gchar
**qtest_rsp_args(QTestState
*s
, int expected_args
)
623 line
= s
->ops
.recv_line(s
);
624 words
= g_strsplit(line
->str
, " ", 0);
625 g_string_free(line
, TRUE
);
627 if (strcmp(words
[0], "IRQ") == 0) {
631 g_assert(words
[1] != NULL
);
632 g_assert(words
[2] != NULL
);
634 ret
= qemu_strtol(words
[2], NULL
, 0, &irq
);
636 g_assert_cmpint(irq
, >=, 0);
637 g_assert_cmpint(irq
, <, MAX_IRQ
);
639 if (strcmp(words
[1], "raise") == 0) {
640 s
->irq_level
[irq
] = true;
642 s
->irq_level
[irq
] = false;
649 g_assert(words
[0] != NULL
);
650 g_assert_cmpstr(words
[0], ==, "OK");
652 for (i
= 0; i
< expected_args
; i
++) {
653 g_assert(words
[i
] != NULL
);
659 static void qtest_rsp(QTestState
*s
)
661 gchar
**words
= qtest_rsp_args(s
, 0);
666 static int qtest_query_target_endianness(QTestState
*s
)
671 qtest_sendf(s
, "endianness\n");
672 args
= qtest_rsp_args(s
, 1);
673 g_assert(strcmp(args
[1], "big") == 0 || strcmp(args
[1], "little") == 0);
674 big_endian
= strcmp(args
[1], "big") == 0;
680 QDict
*qtest_qmp_receive(QTestState
*s
)
683 QDict
*response
= qtest_qmp_receive_dict(s
);
685 if (!qdict_get_try_str(response
, "event")) {
688 /* Stash the event for a later consumption */
689 s
->pending_events
= g_list_append(s
->pending_events
, response
);
693 QDict
*qtest_qmp_receive_dict(QTestState
*s
)
695 return qmp_fd_receive(s
->qmp_fd
);
698 int qtest_socket_server(const char *socket_path
)
700 struct sockaddr_un addr
;
704 sock
= socket(PF_UNIX
, SOCK_STREAM
, 0);
705 g_assert_cmpint(sock
, !=, -1);
707 addr
.sun_family
= AF_UNIX
;
708 snprintf(addr
.sun_path
, sizeof(addr
.sun_path
), "%s", socket_path
);
710 ret
= RETRY_ON_EINTR(bind(sock
, (struct sockaddr
*)&addr
, sizeof(addr
)));
711 g_assert_cmpint(ret
, !=, -1);
712 ret
= listen(sock
, 1);
713 g_assert_cmpint(ret
, !=, -1);
719 void qtest_qmp_vsend_fds(QTestState
*s
, int *fds
, size_t fds_num
,
720 const char *fmt
, va_list ap
)
722 qmp_fd_vsend_fds(s
->qmp_fd
, fds
, fds_num
, fmt
, ap
);
726 void qtest_qmp_vsend(QTestState
*s
, const char *fmt
, va_list ap
)
728 qmp_fd_vsend(s
->qmp_fd
, fmt
, ap
);
732 QDict
*qtest_vqmp_fds(QTestState
*s
, int *fds
, size_t fds_num
,
733 const char *fmt
, va_list ap
)
735 qtest_qmp_vsend_fds(s
, fds
, fds_num
, fmt
, ap
);
738 return qtest_qmp_receive(s
);
742 QDict
*qtest_vqmp(QTestState
*s
, const char *fmt
, va_list ap
)
744 qtest_qmp_vsend(s
, fmt
, ap
);
747 return qtest_qmp_receive(s
);
751 QDict
*qtest_qmp_fds(QTestState
*s
, int *fds
, size_t fds_num
,
752 const char *fmt
, ...)
758 response
= qtest_vqmp_fds(s
, fds
, fds_num
, fmt
, ap
);
764 QDict
*qtest_qmp(QTestState
*s
, const char *fmt
, ...)
770 response
= qtest_vqmp(s
, fmt
, ap
);
775 void qtest_qmp_send(QTestState
*s
, const char *fmt
, ...)
780 qtest_qmp_vsend(s
, fmt
, ap
);
784 void qtest_qmp_send_raw(QTestState
*s
, const char *fmt
, ...)
789 qmp_fd_vsend_raw(s
->qmp_fd
, fmt
, ap
);
793 QDict
*qtest_qmp_event_ref(QTestState
*s
, const char *event
)
795 while (s
->pending_events
) {
797 GList
*first
= s
->pending_events
;
798 QDict
*response
= (QDict
*)first
->data
;
800 s
->pending_events
= g_list_delete_link(s
->pending_events
, first
);
802 if (!strcmp(qdict_get_str(response
, "event"), event
)) {
805 qobject_unref(response
);
810 QDict
*qtest_qmp_eventwait_ref(QTestState
*s
, const char *event
)
812 QDict
*response
= qtest_qmp_event_ref(s
, event
);
819 response
= qtest_qmp_receive_dict(s
);
820 if ((qdict_haskey(response
, "event")) &&
821 (strcmp(qdict_get_str(response
, "event"), event
) == 0)) {
824 qobject_unref(response
);
828 void qtest_qmp_eventwait(QTestState
*s
, const char *event
)
832 response
= qtest_qmp_eventwait_ref(s
, event
);
833 qobject_unref(response
);
836 char *qtest_vhmp(QTestState
*s
, const char *fmt
, va_list ap
)
842 cmd
= g_strdup_vprintf(fmt
, ap
);
843 resp
= qtest_qmp(s
, "{'execute': 'human-monitor-command',"
844 " 'arguments': {'command-line': %s}}",
846 ret
= g_strdup(qdict_get_try_str(resp
, "return"));
853 char *qtest_hmp(QTestState
*s
, const char *fmt
, ...)
859 ret
= qtest_vhmp(s
, fmt
, ap
);
864 const char *qtest_get_arch(void)
866 const char *qemu
= qtest_qemu_binary();
867 const char *end
= strrchr(qemu
, '-');
870 fprintf(stderr
, "Can't determine architecture from binary name.\n");
874 if (!strstr(qemu
, "-system-")) {
875 fprintf(stderr
, "QTEST_QEMU_BINARY must end with *-system-<arch> "
876 "where 'arch' is the target\narchitecture (x86_64, aarch64, "
884 bool qtest_has_accel(const char *accel_name
)
886 if (g_str_equal(accel_name
, "tcg")) {
887 #if defined(CONFIG_TCG)
892 } else if (g_str_equal(accel_name
, "kvm")) {
894 const char *arch
= qtest_get_arch();
895 const char *targets
[] = { CONFIG_KVM_TARGETS
};
897 for (i
= 0; i
< ARRAY_SIZE(targets
); i
++) {
898 if (!strncmp(targets
[i
], arch
, strlen(arch
))) {
899 if (!access("/dev/kvm", R_OK
| W_OK
)) {
905 /* not implemented */
906 g_assert_not_reached();
911 bool qtest_get_irq(QTestState
*s
, int num
)
913 /* dummy operation in order to make sure irq is up to date */
916 return s
->irq_level
[num
];
919 void qtest_module_load(QTestState
*s
, const char *prefix
, const char *libname
)
921 qtest_sendf(s
, "module_load %s %s\n", prefix
, libname
);
925 static int64_t qtest_clock_rsp(QTestState
*s
)
929 words
= qtest_rsp_args(s
, 2);
930 clock
= g_ascii_strtoll(words
[1], NULL
, 0);
935 int64_t qtest_clock_step_next(QTestState
*s
)
937 qtest_sendf(s
, "clock_step\n");
938 return qtest_clock_rsp(s
);
941 int64_t qtest_clock_step(QTestState
*s
, int64_t step
)
943 qtest_sendf(s
, "clock_step %"PRIi64
"\n", step
);
944 return qtest_clock_rsp(s
);
947 int64_t qtest_clock_set(QTestState
*s
, int64_t val
)
949 qtest_sendf(s
, "clock_set %"PRIi64
"\n", val
);
950 return qtest_clock_rsp(s
);
953 void qtest_irq_intercept_out(QTestState
*s
, const char *qom_path
)
955 qtest_sendf(s
, "irq_intercept_out %s\n", qom_path
);
959 void qtest_irq_intercept_in(QTestState
*s
, const char *qom_path
)
961 qtest_sendf(s
, "irq_intercept_in %s\n", qom_path
);
965 void qtest_set_irq_in(QTestState
*s
, const char *qom_path
, const char *name
,
969 name
= "unnamed-gpio-in";
971 qtest_sendf(s
, "set_irq_in %s %s %d %d\n", qom_path
, name
, num
, level
);
975 static void qtest_out(QTestState
*s
, const char *cmd
, uint16_t addr
, uint32_t value
)
977 qtest_sendf(s
, "%s 0x%x 0x%x\n", cmd
, addr
, value
);
981 void qtest_outb(QTestState
*s
, uint16_t addr
, uint8_t value
)
983 qtest_out(s
, "outb", addr
, value
);
986 void qtest_outw(QTestState
*s
, uint16_t addr
, uint16_t value
)
988 qtest_out(s
, "outw", addr
, value
);
991 void qtest_outl(QTestState
*s
, uint16_t addr
, uint32_t value
)
993 qtest_out(s
, "outl", addr
, value
);
996 static uint32_t qtest_in(QTestState
*s
, const char *cmd
, uint16_t addr
)
1000 unsigned long value
;
1002 qtest_sendf(s
, "%s 0x%x\n", cmd
, addr
);
1003 args
= qtest_rsp_args(s
, 2);
1004 ret
= qemu_strtoul(args
[1], NULL
, 0, &value
);
1005 g_assert(!ret
&& value
<= UINT32_MAX
);
1011 uint8_t qtest_inb(QTestState
*s
, uint16_t addr
)
1013 return qtest_in(s
, "inb", addr
);
1016 uint16_t qtest_inw(QTestState
*s
, uint16_t addr
)
1018 return qtest_in(s
, "inw", addr
);
1021 uint32_t qtest_inl(QTestState
*s
, uint16_t addr
)
1023 return qtest_in(s
, "inl", addr
);
1026 static void qtest_write(QTestState
*s
, const char *cmd
, uint64_t addr
,
1029 qtest_sendf(s
, "%s 0x%" PRIx64
" 0x%" PRIx64
"\n", cmd
, addr
, value
);
1033 void qtest_writeb(QTestState
*s
, uint64_t addr
, uint8_t value
)
1035 qtest_write(s
, "writeb", addr
, value
);
1038 void qtest_writew(QTestState
*s
, uint64_t addr
, uint16_t value
)
1040 qtest_write(s
, "writew", addr
, value
);
1043 void qtest_writel(QTestState
*s
, uint64_t addr
, uint32_t value
)
1045 qtest_write(s
, "writel", addr
, value
);
1048 void qtest_writeq(QTestState
*s
, uint64_t addr
, uint64_t value
)
1050 qtest_write(s
, "writeq", addr
, value
);
1053 static uint64_t qtest_read(QTestState
*s
, const char *cmd
, uint64_t addr
)
1059 qtest_sendf(s
, "%s 0x%" PRIx64
"\n", cmd
, addr
);
1060 args
= qtest_rsp_args(s
, 2);
1061 ret
= qemu_strtou64(args
[1], NULL
, 0, &value
);
1068 uint8_t qtest_readb(QTestState
*s
, uint64_t addr
)
1070 return qtest_read(s
, "readb", addr
);
1073 uint16_t qtest_readw(QTestState
*s
, uint64_t addr
)
1075 return qtest_read(s
, "readw", addr
);
1078 uint32_t qtest_readl(QTestState
*s
, uint64_t addr
)
1080 return qtest_read(s
, "readl", addr
);
1083 uint64_t qtest_readq(QTestState
*s
, uint64_t addr
)
1085 return qtest_read(s
, "readq", addr
);
1088 static int hex2nib(char ch
)
1090 if (ch
>= '0' && ch
<= '9') {
1092 } else if (ch
>= 'a' && ch
<= 'f') {
1093 return 10 + (ch
- 'a');
1094 } else if (ch
>= 'A' && ch
<= 'F') {
1095 return 10 + (ch
- 'a');
1101 void qtest_memread(QTestState
*s
, uint64_t addr
, void *data
, size_t size
)
1103 uint8_t *ptr
= data
;
1111 qtest_sendf(s
, "read 0x%" PRIx64
" 0x%zx\n", addr
, size
);
1112 args
= qtest_rsp_args(s
, 2);
1114 for (i
= 0; i
< size
; i
++) {
1115 ptr
[i
] = hex2nib(args
[1][2 + (i
* 2)]) << 4;
1116 ptr
[i
] |= hex2nib(args
[1][2 + (i
* 2) + 1]);
1122 uint64_t qtest_rtas_call(QTestState
*s
, const char *name
,
1123 uint32_t nargs
, uint64_t args
,
1124 uint32_t nret
, uint64_t ret
)
1126 qtest_sendf(s
, "rtas %s %u 0x%"PRIx64
" %u 0x%"PRIx64
"\n",
1127 name
, nargs
, args
, nret
, ret
);
1132 void qtest_add_func(const char *str
, void (*fn
)(void))
1134 gchar
*path
= g_strdup_printf("/%s/%s", qtest_get_arch(), str
);
1135 g_test_add_func(path
, fn
);
1139 void qtest_add_data_func_full(const char *str
, void *data
,
1140 void (*fn
)(const void *),
1141 GDestroyNotify data_free_func
)
1143 gchar
*path
= g_strdup_printf("/%s/%s", qtest_get_arch(), str
);
1144 g_test_add_data_func_full(path
, data
, fn
, data_free_func
);
1148 void qtest_add_data_func(const char *str
, const void *data
,
1149 void (*fn
)(const void *))
1151 gchar
*path
= g_strdup_printf("/%s/%s", qtest_get_arch(), str
);
1152 g_test_add_data_func(path
, data
, fn
);
1156 void qtest_bufwrite(QTestState
*s
, uint64_t addr
, const void *data
, size_t size
)
1160 bdata
= g_base64_encode(data
, size
);
1161 qtest_sendf(s
, "b64write 0x%" PRIx64
" 0x%zx ", addr
, size
);
1162 s
->ops
.send(s
, bdata
);
1163 s
->ops
.send(s
, "\n");
1168 void qtest_bufread(QTestState
*s
, uint64_t addr
, void *data
, size_t size
)
1173 qtest_sendf(s
, "b64read 0x%" PRIx64
" 0x%zx\n", addr
, size
);
1174 args
= qtest_rsp_args(s
, 2);
1176 g_base64_decode_inplace(args
[1], &len
);
1178 fprintf(stderr
, "bufread: asked for %zu bytes but decoded %zu\n",
1180 len
= MIN(len
, size
);
1183 memcpy(data
, args
[1], len
);
1187 void qtest_memwrite(QTestState
*s
, uint64_t addr
, const void *data
, size_t size
)
1189 const uint8_t *ptr
= data
;
1197 enc
= g_malloc(2 * size
+ 1);
1199 for (i
= 0; i
< size
; i
++) {
1200 sprintf(&enc
[i
* 2], "%02x", ptr
[i
]);
1203 qtest_sendf(s
, "write 0x%" PRIx64
" 0x%zx 0x%s\n", addr
, size
, enc
);
1208 void qtest_memset(QTestState
*s
, uint64_t addr
, uint8_t pattern
, size_t size
)
1210 qtest_sendf(s
, "memset 0x%" PRIx64
" 0x%zx 0x%02x\n", addr
, size
, pattern
);
1214 void qtest_qmp_assert_success(QTestState
*qts
, const char *fmt
, ...)
1220 response
= qtest_vqmp(qts
, fmt
, ap
);
1224 if (!qdict_haskey(response
, "return")) {
1225 GString
*s
= qobject_to_json_pretty(QOBJECT(response
), true);
1226 g_test_message("%s", s
->str
);
1227 g_string_free(s
, true);
1229 g_assert(qdict_haskey(response
, "return"));
1230 qobject_unref(response
);
1233 bool qtest_big_endian(QTestState
*s
)
1235 return s
->big_endian
;
1238 static bool qtest_check_machine_version(const char *mname
, const char *basename
,
1239 int major
, int minor
)
1244 newname
= g_strdup_printf("%s-%i.%i", basename
, major
, minor
);
1245 is_equal
= g_str_equal(mname
, newname
);
1251 static bool qtest_is_old_versioned_machine(const char *mname
)
1253 const char *dash
= strrchr(mname
, '-');
1254 const char *dot
= strrchr(mname
, '.');
1257 const int major
= QEMU_VERSION_MAJOR
;
1258 const int minor
= QEMU_VERSION_MINOR
;
1261 if (dash
&& dot
&& dot
> dash
) {
1262 for (chr
= dash
+ 1; *chr
; chr
++) {
1263 if (!qemu_isdigit(*chr
) && *chr
!= '.') {
1268 * Now check if it is one of the latest versions. Check major + 1
1269 * and minor + 1 versions as well, since they might already exist
1270 * in the development branch.
1272 bname
= g_strdup(mname
);
1273 bname
[dash
- mname
] = 0;
1274 res
= !qtest_check_machine_version(mname
, bname
, major
+ 1, 0) &&
1275 !qtest_check_machine_version(mname
, bname
, major
, minor
+ 1) &&
1276 !qtest_check_machine_version(mname
, bname
, major
, minor
);
1289 * Returns an array with pointers to the available machine names.
1290 * The terminating entry has the name set to NULL.
1292 static struct MachInfo
*qtest_get_machines(void)
1294 static struct MachInfo
*machines
;
1295 QDict
*response
, *minfo
;
1297 const QListEntry
*p
;
1307 qts
= qtest_init("-machine none");
1308 response
= qtest_qmp(qts
, "{ 'execute': 'query-machines' }");
1310 list
= qdict_get_qlist(response
, "return");
1313 machines
= g_new(struct MachInfo
, qlist_size(list
) + 1);
1315 for (p
= qlist_first(list
), idx
= 0; p
; p
= qlist_next(p
), idx
++) {
1316 minfo
= qobject_to(QDict
, qlist_entry_obj(p
));
1319 qobj
= qdict_get(minfo
, "name");
1321 qstr
= qobject_to(QString
, qobj
);
1323 machines
[idx
].name
= g_strdup(qstring_get_str(qstr
));
1325 qobj
= qdict_get(minfo
, "alias");
1326 if (qobj
) { /* The alias is optional */
1327 qstr
= qobject_to(QString
, qobj
);
1329 machines
[idx
].alias
= g_strdup(qstring_get_str(qstr
));
1331 machines
[idx
].alias
= NULL
;
1336 qobject_unref(response
);
1338 memset(&machines
[idx
], 0, sizeof(struct MachInfo
)); /* Terminating entry */
1342 void qtest_cb_for_every_machine(void (*cb
)(const char *machine
),
1343 bool skip_old_versioned
)
1345 struct MachInfo
*machines
;
1348 machines
= qtest_get_machines();
1350 for (i
= 0; machines
[i
].name
!= NULL
; i
++) {
1351 /* Ignore machines that cannot be used for qtests */
1352 if (!strncmp("xenfv", machines
[i
].name
, 5) ||
1353 g_str_equal("xenpv", machines
[i
].name
)) {
1356 if (!skip_old_versioned
||
1357 !qtest_is_old_versioned_machine(machines
[i
].name
)) {
1358 cb(machines
[i
].name
);
1363 bool qtest_has_machine(const char *machine
)
1365 struct MachInfo
*machines
;
1368 machines
= qtest_get_machines();
1370 for (i
= 0; machines
[i
].name
!= NULL
; i
++) {
1371 if (g_str_equal(machine
, machines
[i
].name
) ||
1372 (machines
[i
].alias
&& g_str_equal(machine
, machines
[i
].alias
))) {
1380 bool qtest_has_device(const char *device
)
1383 const QListEntry
*p
;
1392 QTestState
*qts
= qtest_init("-machine none");
1395 qdict_put_bool(args
, "abstract", false);
1396 qdict_put_str(args
, "implements", "device");
1398 resp
= qtest_qmp(qts
, "{'execute': 'qom-list-types', 'arguments': %p }",
1400 g_assert(qdict_haskey(resp
, "return"));
1401 list
= qdict_get_qlist(resp
, "return");
1403 qobject_unref(resp
);
1408 for (p
= qlist_first(list
), idx
= 0; p
; p
= qlist_next(p
), idx
++) {
1409 devinfo
= qobject_to(QDict
, qlist_entry_obj(p
));
1412 qobj
= qdict_get(devinfo
, "name");
1414 qstr
= qobject_to(QString
, qobj
);
1416 if (g_str_equal(qstring_get_str(qstr
), device
)) {
1425 * Generic hot-plugging test via the device_add QMP commands.
1427 void qtest_qmp_device_add_qdict(QTestState
*qts
, const char *drv
,
1428 const QDict
*arguments
)
1431 QDict
*args
= arguments
? qdict_clone_shallow(arguments
) : qdict_new();
1433 g_assert(!qdict_haskey(args
, "driver"));
1434 qdict_put_str(args
, "driver", drv
);
1435 resp
= qtest_qmp(qts
, "{'execute': 'device_add', 'arguments': %p}", args
);
1437 g_assert(!qdict_haskey(resp
, "event")); /* We don't expect any events */
1438 if (qdict_haskey(resp
, "error")) {
1439 fprintf(stderr
, "error: %s\n",
1440 qdict_get_str(qdict_get_qdict(resp
, "error"), "desc"));
1442 g_assert(!qdict_haskey(resp
, "error"));
1443 qobject_unref(resp
);
1446 void qtest_qmp_device_add(QTestState
*qts
, const char *driver
, const char *id
,
1447 const char *fmt
, ...)
1453 args
= qdict_from_vjsonf_nofail(fmt
, ap
);
1456 g_assert(!qdict_haskey(args
, "id"));
1457 qdict_put_str(args
, "id", id
);
1459 qtest_qmp_device_add_qdict(qts
, driver
, args
);
1460 qobject_unref(args
);
1464 void qtest_qmp_add_client(QTestState
*qts
, const char *protocol
, int fd
)
1468 resp
= qtest_qmp_fds(qts
, &fd
, 1, "{'execute': 'getfd',"
1469 "'arguments': {'fdname': 'fdname'}}");
1471 g_assert(!qdict_haskey(resp
, "event")); /* We don't expect any events */
1472 g_assert(!qdict_haskey(resp
, "error"));
1473 qobject_unref(resp
);
1476 qts
, "{'execute': 'add_client',"
1477 "'arguments': {'protocol': %s, 'fdname': 'fdname'}}", protocol
);
1479 g_assert(!qdict_haskey(resp
, "event")); /* We don't expect any events */
1480 g_assert(!qdict_haskey(resp
, "error"));
1481 qobject_unref(resp
);
1486 * Generic hot-unplugging test via the device_del QMP command.
1487 * Device deletion will get one response and one event. For example:
1489 * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1491 * will get this one:
1493 * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1494 * "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1495 * "path": "/machine/peripheral/scsi-hd"}}
1501 void qtest_qmp_device_del_send(QTestState
*qts
, const char *id
)
1503 QDict
*rsp
= qtest_qmp(qts
, "{'execute': 'device_del', "
1504 "'arguments': {'id': %s}}", id
);
1506 g_assert(qdict_haskey(rsp
, "return"));
1507 g_assert(!qdict_haskey(rsp
, "error"));
1511 void qtest_qmp_device_del(QTestState
*qts
, const char *id
)
1513 qtest_qmp_device_del_send(qts
, id
);
1514 qtest_qmp_eventwait(qts
, "DEVICE_DELETED");
1517 static void qtest_client_set_tx_handler(QTestState
*s
,
1522 static void qtest_client_set_rx_handler(QTestState
*s
, QTestRecvFn recv
)
1524 s
->ops
.recv_line
= recv
;
1526 /* A type-safe wrapper for s->send() */
1527 static void send_wrapper(QTestState
*s
, const char *buf
)
1529 s
->ops
.external_send(s
, buf
);
1532 static GString
*qtest_client_inproc_recv_line(QTestState
*s
)
1538 eol
= strchr(s
->rx
->str
, '\n');
1539 offset
= eol
- s
->rx
->str
;
1540 line
= g_string_new_len(s
->rx
->str
, offset
);
1541 g_string_erase(s
->rx
, 0, offset
+ 1);
1545 QTestState
*qtest_inproc_init(QTestState
**s
, bool log
, const char* arch
,
1546 void (*send
)(void*, const char*))
1549 qts
= g_new0(QTestState
, 1);
1550 qts
->pending_events
= NULL
;
1551 *s
= qts
; /* Expose qts early on, since the query endianness relies on it */
1553 for (int i
= 0; i
< MAX_IRQ
; i
++) {
1554 qts
->irq_level
[i
] = false;
1557 qtest_client_set_rx_handler(qts
, qtest_client_inproc_recv_line
);
1559 /* send() may not have a matching protoype, so use a type-safe wrapper */
1560 qts
->ops
.external_send
= send
;
1561 qtest_client_set_tx_handler(qts
, send_wrapper
);
1563 qts
->big_endian
= qtest_query_target_endianness(qts
);
1566 * Set a dummy path for QTEST_QEMU_BINARY. Doesn't need to exist, but this
1567 * way, qtest_get_arch works for inproc qtest.
1569 gchar
*bin_path
= g_strconcat("/qemu-system-", arch
, NULL
);
1570 g_setenv("QTEST_QEMU_BINARY", bin_path
, 0);
1576 void qtest_client_inproc_recv(void *opaque
, const char *str
)
1578 QTestState
*qts
= *(QTestState
**)opaque
;
1581 qts
->rx
= g_string_new(NULL
);
1583 g_string_append(qts
->rx
, str
);
1587 void qtest_qom_set_bool(QTestState
*s
, const char *path
, const char *property
,
1592 r
= qtest_qmp(s
, "{ 'execute': 'qom-set', 'arguments': "
1593 "{ 'path': %s, 'property': %s, 'value': %i } }",
1594 path
, property
, value
);
1598 bool qtest_qom_get_bool(QTestState
*s
, const char *path
, const char *property
)
1603 r
= qtest_qmp(s
, "{ 'execute': 'qom-get', 'arguments': "
1604 "{ 'path': %s, 'property': %s } }", path
, property
);
1605 b
= qdict_get_bool(r
, "return");