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 typedef void (*QTestSendFn
)(QTestState
*s
, const char *buf
);
53 typedef void (*ExternalSendFn
)(void *s
, const char *buf
);
54 typedef GString
* (*QTestRecvFn
)(QTestState
*);
56 typedef struct QTestClientTransportOps
{
57 QTestSendFn send
; /* for sending qtest commands */
60 * use external_send to send qtest command strings through functions which
61 * do not accept a QTestState as the first parameter.
63 ExternalSendFn external_send
;
65 QTestRecvFn recv_line
; /* for receiving qtest command responses */
72 pid_t qemu_pid
; /* our child QEMU process */
79 bool irq_level
[MAX_IRQ
];
81 QTestTransportOps ops
;
82 GList
*pending_events
;
85 static GHookList abrt_hooks
;
86 static void (*sighandler_old
)(int);
88 static int qtest_query_target_endianness(QTestState
*s
);
90 static void qtest_client_socket_send(QTestState
*, const char *buf
);
91 static void socket_send(int fd
, const char *buf
, size_t size
);
93 static GString
*qtest_client_socket_recv_line(QTestState
*);
95 static void qtest_client_set_tx_handler(QTestState
*s
, QTestSendFn send
);
96 static void qtest_client_set_rx_handler(QTestState
*s
, QTestRecvFn recv
);
98 static int init_socket(const char *socket_path
)
100 int sock
= qtest_socket_server(socket_path
);
101 qemu_set_cloexec(sock
);
105 static int socket_accept(int sock
)
107 struct sockaddr_un addr
;
111 * timeout unit of blocking receive calls is different among platfoms.
112 * It's in seconds on non-Windows platforms but milliseconds on Windows.
115 struct timeval timeout
= { .tv_sec
= SOCKET_TIMEOUT
,
118 DWORD timeout
= SOCKET_TIMEOUT
;
121 if (setsockopt(sock
, SOL_SOCKET
, SO_RCVTIMEO
,
122 (void *)&timeout
, sizeof(timeout
))) {
123 fprintf(stderr
, "%s failed to set SO_RCVTIMEO: %s\n",
124 __func__
, strerror(errno
));
130 addrlen
= sizeof(addr
);
131 ret
= accept(sock
, (struct sockaddr
*)&addr
, &addrlen
);
132 } while (ret
== -1 && errno
== EINTR
);
134 fprintf(stderr
, "%s failed: %s\n", __func__
, strerror(errno
));
141 bool qtest_probe_child(QTestState
*s
)
143 pid_t pid
= s
->qemu_pid
;
147 pid
= waitpid(pid
, &s
->wstatus
, WNOHANG
);
152 GetExitCodeProcess((HANDLE
)pid
, &s
->exit_code
);
153 if (s
->exit_code
== STILL_ACTIVE
) {
156 CloseHandle((HANDLE
)pid
);
163 void qtest_set_expected_status(QTestState
*s
, int status
)
165 s
->expected_status
= status
;
168 static void qtest_check_status(QTestState
*s
)
171 * Check whether qemu exited with expected exit status; anything else is
172 * fishy and should be logged with as much detail as possible.
175 int wstatus
= s
->wstatus
;
176 if (WIFEXITED(wstatus
) && WEXITSTATUS(wstatus
) != s
->expected_status
) {
177 fprintf(stderr
, "%s:%d: kill_qemu() tried to terminate QEMU "
178 "process but encountered exit status %d (expected %d)\n",
179 __FILE__
, __LINE__
, WEXITSTATUS(wstatus
), s
->expected_status
);
181 } else if (WIFSIGNALED(wstatus
)) {
182 int sig
= WTERMSIG(wstatus
);
183 const char *signame
= strsignal(sig
) ?: "unknown ???";
184 const char *dump
= WCOREDUMP(wstatus
) ? " (core dumped)" : "";
186 fprintf(stderr
, "%s:%d: kill_qemu() detected QEMU death "
187 "from signal %d (%s)%s\n",
188 __FILE__
, __LINE__
, sig
, signame
, dump
);
192 if (s
->exit_code
!= s
->expected_status
) {
193 fprintf(stderr
, "%s:%d: kill_qemu() tried to terminate QEMU "
194 "process but encountered exit status %ld (expected %d)\n",
195 __FILE__
, __LINE__
, s
->exit_code
, s
->expected_status
);
201 void qtest_wait_qemu(QTestState
*s
)
206 TFR(pid
= waitpid(s
->qemu_pid
, &s
->wstatus
, 0));
207 assert(pid
== s
->qemu_pid
);
211 ret
= WaitForSingleObject((HANDLE
)s
->qemu_pid
, INFINITE
);
212 assert(ret
== WAIT_OBJECT_0
);
213 GetExitCodeProcess((HANDLE
)s
->qemu_pid
, &s
->exit_code
);
214 CloseHandle((HANDLE
)s
->qemu_pid
);
217 qtest_check_status(s
);
220 void qtest_kill_qemu(QTestState
*s
)
222 /* Skip wait if qtest_probe_child() already reaped */
223 if (s
->qemu_pid
!= -1) {
225 kill(s
->qemu_pid
, SIGTERM
);
227 TerminateProcess((HANDLE
)s
->qemu_pid
, s
->expected_status
);
234 qtest_check_status(s
);
237 static void kill_qemu_hook_func(void *s
)
242 static void sigabrt_handler(int signo
)
244 g_hook_list_invoke(&abrt_hooks
, FALSE
);
247 static void setup_sigabrt_handler(void)
249 sighandler_old
= signal(SIGABRT
, sigabrt_handler
);
252 static void cleanup_sigabrt_handler(void)
254 signal(SIGABRT
, sighandler_old
);
257 static bool hook_list_is_empty(GHookList
*hook_list
)
259 GHook
*hook
= g_hook_first_valid(hook_list
, TRUE
);
265 g_hook_unref(hook_list
, hook
);
269 void qtest_add_abrt_handler(GHookFunc fn
, const void *data
)
273 if (!abrt_hooks
.is_setup
) {
274 g_hook_list_init(&abrt_hooks
, sizeof(GHook
));
277 /* Only install SIGABRT handler once */
278 if (hook_list_is_empty(&abrt_hooks
)) {
279 setup_sigabrt_handler();
282 hook
= g_hook_alloc(&abrt_hooks
);
284 hook
->data
= (void *)data
;
286 g_hook_prepend(&abrt_hooks
, hook
);
289 void qtest_remove_abrt_handler(void *data
)
291 GHook
*hook
= g_hook_find_data(&abrt_hooks
, TRUE
, data
);
292 g_hook_destroy_link(&abrt_hooks
, hook
);
294 /* Uninstall SIGABRT handler on last instance */
295 if (hook_list_is_empty(&abrt_hooks
)) {
296 cleanup_sigabrt_handler();
300 static const char *qtest_qemu_binary(void)
302 const char *qemu_bin
;
304 qemu_bin
= getenv("QTEST_QEMU_BINARY");
306 fprintf(stderr
, "Environment variable QTEST_QEMU_BINARY required\n");
314 static pid_t
qtest_create_process(char *cmd
)
317 PROCESS_INFORMATION pi
;
320 ZeroMemory(&si
, sizeof(si
));
322 ZeroMemory(&pi
, sizeof(pi
));
324 ret
= CreateProcess(NULL
, /* module name */
325 cmd
, /* command line */
326 NULL
, /* process handle not inheritable */
327 NULL
, /* thread handle not inheritable */
328 FALSE
, /* set handle inheritance to FALSE */
329 0, /* No creation flags */
330 NULL
, /* use parent's environment block */
331 NULL
, /* use parent's starting directory */
332 &si
, /* pointer to STARTUPINFO structure */
333 &pi
/* pointer to PROCESS_INFORMATION structure */
336 fprintf(stderr
, "%s:%d: unable to create a new process (%s)\n",
337 __FILE__
, __LINE__
, strerror(GetLastError()));
341 return (pid_t
)pi
.hProcess
;
345 QTestState
*qtest_init_without_qmp_handshake(const char *extra_args
)
348 int sock
, qmpsock
, i
;
350 gchar
*qmp_socket_path
;
352 const char *qemu_binary
= qtest_qemu_binary();
353 const char *trace
= g_getenv("QTEST_TRACE");
354 g_autofree
char *tracearg
= trace
?
355 g_strdup_printf("-trace %s ", trace
) : g_strdup("");
357 s
= g_new(QTestState
, 1);
359 socket_path
= g_strdup_printf("%s/qtest-%d.sock",
360 g_get_tmp_dir(), getpid());
361 qmp_socket_path
= g_strdup_printf("%s/qtest-%d.qmp",
362 g_get_tmp_dir(), getpid());
364 /* It's possible that if an earlier test run crashed it might
365 * have left a stale unix socket lying around. Delete any
366 * stale old socket to avoid spurious test failures with
367 * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1)
370 unlink(qmp_socket_path
);
373 sock
= init_socket(socket_path
);
374 qmpsock
= init_socket(qmp_socket_path
);
376 qtest_client_set_rx_handler(s
, qtest_client_socket_recv_line
);
377 qtest_client_set_tx_handler(s
, qtest_client_socket_send
);
379 qtest_add_abrt_handler(kill_qemu_hook_func
, s
);
381 command
= g_strdup_printf(CMD_EXEC
"%s %s"
384 "-chardev socket,path=%s,id=char0 "
385 "-mon chardev=char0,mode=control "
389 qemu_binary
, tracearg
, socket_path
,
390 getenv("QTEST_LOG") ? DEV_STDERR
: DEV_NULL
,
394 g_test_message("starting QEMU: %s", command
);
396 s
->pending_events
= NULL
;
398 s
->expected_status
= 0;
400 s
->qemu_pid
= fork();
401 if (s
->qemu_pid
== 0) {
404 * Although we register a ABRT handler to kill off QEMU
405 * when g_assert() triggers, we want an extra safety
406 * net. The QEMU process might be non-functional and
407 * thus not have responded to SIGTERM. The test script
408 * might also have crashed with SEGV, in which case the
409 * cleanup handlers won't ever run.
411 * This PR_SET_PDEATHSIG setup will ensure any remaining
412 * QEMU will get terminated with SIGKILL in these cases.
414 prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0);
415 #endif /* __linux__ */
416 if (!g_setenv("QEMU_AUDIO_DRV", "none", true)) {
419 execlp("/bin/sh", "sh", "-c", command
, NULL
);
423 s
->qemu_pid
= qtest_create_process(command
);
427 s
->fd
= socket_accept(sock
);
429 s
->qmp_fd
= socket_accept(qmpsock
);
432 unlink(qmp_socket_path
);
434 g_free(qmp_socket_path
);
436 g_assert(s
->fd
>= 0 && s
->qmp_fd
>= 0);
438 s
->rx
= g_string_new("");
439 for (i
= 0; i
< MAX_IRQ
; i
++) {
440 s
->irq_level
[i
] = false;
444 * Stopping QEMU for debugging is not supported on Windows.
446 * Using DebugActiveProcess() API can suspend the QEMU process,
447 * but gdb cannot attach to the process. Using the undocumented
448 * NtSuspendProcess() can suspend the QEMU process and gdb can
449 * attach to the process, but gdb cannot resume it.
452 if (getenv("QTEST_STOP")) {
453 kill(s
->qemu_pid
, SIGSTOP
);
457 /* ask endianness of the target */
459 s
->big_endian
= qtest_query_target_endianness(s
);
464 QTestState
*qtest_init(const char *extra_args
)
466 QTestState
*s
= qtest_init_without_qmp_handshake(extra_args
);
469 /* Read the QMP greeting and then do the handshake */
470 greeting
= qtest_qmp_receive(s
);
471 qobject_unref(greeting
);
472 qobject_unref(qtest_qmp(s
, "{ 'execute': 'qmp_capabilities' }"));
477 QTestState
*qtest_vinitf(const char *fmt
, va_list ap
)
479 char *args
= g_strdup_vprintf(fmt
, ap
);
482 s
= qtest_init(args
);
487 QTestState
*qtest_initf(const char *fmt
, ...)
493 s
= qtest_vinitf(fmt
, ap
);
498 QTestState
*qtest_init_with_serial(const char *extra_args
, int *sock_fd
)
501 g_autofree
char *sock_dir
= NULL
;
505 sock_dir
= g_dir_make_tmp("qtest-serial-XXXXXX", NULL
);
506 g_assert_true(sock_dir
!= NULL
);
507 sock_path
= g_strdup_printf("%s/sock", sock_dir
);
510 sock_fd_init
= init_socket(sock_path
);
512 qts
= qtest_initf("-chardev socket,id=s0,path=%s -serial chardev:s0 %s",
513 sock_path
, extra_args
);
515 *sock_fd
= socket_accept(sock_fd_init
);
521 g_assert_true(*sock_fd
>= 0);
526 void qtest_quit(QTestState
*s
)
528 qtest_remove_abrt_handler(s
);
532 closesocket(s
->qmp_fd
);
533 g_string_free(s
->rx
, true);
535 for (GList
*it
= s
->pending_events
; it
!= NULL
; it
= it
->next
) {
536 qobject_unref((QDict
*)it
->data
);
539 g_list_free(s
->pending_events
);
544 static void socket_send(int fd
, const char *buf
, size_t size
)
546 ssize_t res
= qemu_send_full(fd
, buf
, size
);
551 static void qtest_client_socket_send(QTestState
*s
, const char *buf
)
553 socket_send(s
->fd
, buf
, strlen(buf
));
556 static void G_GNUC_PRINTF(2, 3) qtest_sendf(QTestState
*s
, const char *fmt
, ...)
561 gchar
*str
= g_strdup_vprintf(fmt
, ap
);
568 static GString
*qtest_client_socket_recv_line(QTestState
*s
)
574 while ((eol
= strchr(s
->rx
->str
, '\n')) == NULL
) {
578 len
= recv(s
->fd
, buffer
, sizeof(buffer
), 0);
579 if (len
== -1 && errno
== EINTR
) {
583 if (len
== -1 || len
== 0) {
584 fprintf(stderr
, "Broken pipe\n");
588 g_string_append_len(s
->rx
, buffer
, len
);
591 offset
= eol
- s
->rx
->str
;
592 line
= g_string_new_len(s
->rx
->str
, offset
);
593 g_string_erase(s
->rx
, 0, offset
+ 1);
598 static gchar
**qtest_rsp_args(QTestState
*s
, int expected_args
)
605 line
= s
->ops
.recv_line(s
);
606 words
= g_strsplit(line
->str
, " ", 0);
607 g_string_free(line
, TRUE
);
609 if (strcmp(words
[0], "IRQ") == 0) {
613 g_assert(words
[1] != NULL
);
614 g_assert(words
[2] != NULL
);
616 ret
= qemu_strtol(words
[2], NULL
, 0, &irq
);
618 g_assert_cmpint(irq
, >=, 0);
619 g_assert_cmpint(irq
, <, MAX_IRQ
);
621 if (strcmp(words
[1], "raise") == 0) {
622 s
->irq_level
[irq
] = true;
624 s
->irq_level
[irq
] = false;
631 g_assert(words
[0] != NULL
);
632 g_assert_cmpstr(words
[0], ==, "OK");
634 for (i
= 0; i
< expected_args
; i
++) {
635 g_assert(words
[i
] != NULL
);
641 static void qtest_rsp(QTestState
*s
)
643 gchar
**words
= qtest_rsp_args(s
, 0);
648 static int qtest_query_target_endianness(QTestState
*s
)
653 qtest_sendf(s
, "endianness\n");
654 args
= qtest_rsp_args(s
, 1);
655 g_assert(strcmp(args
[1], "big") == 0 || strcmp(args
[1], "little") == 0);
656 big_endian
= strcmp(args
[1], "big") == 0;
662 QDict
*qtest_qmp_receive(QTestState
*s
)
665 QDict
*response
= qtest_qmp_receive_dict(s
);
667 if (!qdict_get_try_str(response
, "event")) {
670 /* Stash the event for a later consumption */
671 s
->pending_events
= g_list_append(s
->pending_events
, response
);
675 QDict
*qtest_qmp_receive_dict(QTestState
*s
)
677 return qmp_fd_receive(s
->qmp_fd
);
680 int qtest_socket_server(const char *socket_path
)
682 struct sockaddr_un addr
;
686 sock
= socket(PF_UNIX
, SOCK_STREAM
, 0);
687 g_assert_cmpint(sock
, !=, -1);
689 addr
.sun_family
= AF_UNIX
;
690 snprintf(addr
.sun_path
, sizeof(addr
.sun_path
), "%s", socket_path
);
693 ret
= bind(sock
, (struct sockaddr
*)&addr
, sizeof(addr
));
694 } while (ret
== -1 && errno
== EINTR
);
695 g_assert_cmpint(ret
, !=, -1);
696 ret
= listen(sock
, 1);
697 g_assert_cmpint(ret
, !=, -1);
703 void qtest_qmp_vsend_fds(QTestState
*s
, int *fds
, size_t fds_num
,
704 const char *fmt
, va_list ap
)
706 qmp_fd_vsend_fds(s
->qmp_fd
, fds
, fds_num
, fmt
, ap
);
710 void qtest_qmp_vsend(QTestState
*s
, const char *fmt
, va_list ap
)
712 qmp_fd_vsend(s
->qmp_fd
, fmt
, ap
);
716 QDict
*qtest_vqmp_fds(QTestState
*s
, int *fds
, size_t fds_num
,
717 const char *fmt
, va_list ap
)
719 qtest_qmp_vsend_fds(s
, fds
, fds_num
, fmt
, ap
);
722 return qtest_qmp_receive(s
);
726 QDict
*qtest_vqmp(QTestState
*s
, const char *fmt
, va_list ap
)
728 qtest_qmp_vsend(s
, fmt
, ap
);
731 return qtest_qmp_receive(s
);
735 QDict
*qtest_qmp_fds(QTestState
*s
, int *fds
, size_t fds_num
,
736 const char *fmt
, ...)
742 response
= qtest_vqmp_fds(s
, fds
, fds_num
, fmt
, ap
);
748 QDict
*qtest_qmp(QTestState
*s
, const char *fmt
, ...)
754 response
= qtest_vqmp(s
, fmt
, ap
);
759 void qtest_qmp_send(QTestState
*s
, const char *fmt
, ...)
764 qtest_qmp_vsend(s
, fmt
, ap
);
768 void qtest_qmp_send_raw(QTestState
*s
, const char *fmt
, ...)
773 qmp_fd_vsend_raw(s
->qmp_fd
, fmt
, ap
);
777 QDict
*qtest_qmp_event_ref(QTestState
*s
, const char *event
)
779 while (s
->pending_events
) {
781 GList
*first
= s
->pending_events
;
782 QDict
*response
= (QDict
*)first
->data
;
784 s
->pending_events
= g_list_delete_link(s
->pending_events
, first
);
786 if (!strcmp(qdict_get_str(response
, "event"), event
)) {
789 qobject_unref(response
);
794 QDict
*qtest_qmp_eventwait_ref(QTestState
*s
, const char *event
)
796 QDict
*response
= qtest_qmp_event_ref(s
, event
);
803 response
= qtest_qmp_receive_dict(s
);
804 if ((qdict_haskey(response
, "event")) &&
805 (strcmp(qdict_get_str(response
, "event"), event
) == 0)) {
808 qobject_unref(response
);
812 void qtest_qmp_eventwait(QTestState
*s
, const char *event
)
816 response
= qtest_qmp_eventwait_ref(s
, event
);
817 qobject_unref(response
);
820 char *qtest_vhmp(QTestState
*s
, const char *fmt
, va_list ap
)
826 cmd
= g_strdup_vprintf(fmt
, ap
);
827 resp
= qtest_qmp(s
, "{'execute': 'human-monitor-command',"
828 " 'arguments': {'command-line': %s}}",
830 ret
= g_strdup(qdict_get_try_str(resp
, "return"));
837 char *qtest_hmp(QTestState
*s
, const char *fmt
, ...)
843 ret
= qtest_vhmp(s
, fmt
, ap
);
848 const char *qtest_get_arch(void)
850 const char *qemu
= qtest_qemu_binary();
851 const char *end
= strrchr(qemu
, '-');
854 fprintf(stderr
, "Can't determine architecture from binary name.\n");
858 if (!strstr(qemu
, "-system-")) {
859 fprintf(stderr
, "QTEST_QEMU_BINARY must end with *-system-<arch> "
860 "where 'arch' is the target\narchitecture (x86_64, aarch64, "
868 bool qtest_has_accel(const char *accel_name
)
870 if (g_str_equal(accel_name
, "tcg")) {
871 #if defined(CONFIG_TCG)
876 } else if (g_str_equal(accel_name
, "kvm")) {
878 const char *arch
= qtest_get_arch();
879 const char *targets
[] = { CONFIG_KVM_TARGETS
};
881 for (i
= 0; i
< ARRAY_SIZE(targets
); i
++) {
882 if (!strncmp(targets
[i
], arch
, strlen(arch
))) {
883 if (!access("/dev/kvm", R_OK
| W_OK
)) {
889 /* not implemented */
890 g_assert_not_reached();
895 bool qtest_get_irq(QTestState
*s
, int num
)
897 /* dummy operation in order to make sure irq is up to date */
900 return s
->irq_level
[num
];
903 void qtest_module_load(QTestState
*s
, const char *prefix
, const char *libname
)
905 qtest_sendf(s
, "module_load %s %s\n", prefix
, libname
);
909 static int64_t qtest_clock_rsp(QTestState
*s
)
913 words
= qtest_rsp_args(s
, 2);
914 clock
= g_ascii_strtoll(words
[1], NULL
, 0);
919 int64_t qtest_clock_step_next(QTestState
*s
)
921 qtest_sendf(s
, "clock_step\n");
922 return qtest_clock_rsp(s
);
925 int64_t qtest_clock_step(QTestState
*s
, int64_t step
)
927 qtest_sendf(s
, "clock_step %"PRIi64
"\n", step
);
928 return qtest_clock_rsp(s
);
931 int64_t qtest_clock_set(QTestState
*s
, int64_t val
)
933 qtest_sendf(s
, "clock_set %"PRIi64
"\n", val
);
934 return qtest_clock_rsp(s
);
937 void qtest_irq_intercept_out(QTestState
*s
, const char *qom_path
)
939 qtest_sendf(s
, "irq_intercept_out %s\n", qom_path
);
943 void qtest_irq_intercept_in(QTestState
*s
, const char *qom_path
)
945 qtest_sendf(s
, "irq_intercept_in %s\n", qom_path
);
949 void qtest_set_irq_in(QTestState
*s
, const char *qom_path
, const char *name
,
953 name
= "unnamed-gpio-in";
955 qtest_sendf(s
, "set_irq_in %s %s %d %d\n", qom_path
, name
, num
, level
);
959 static void qtest_out(QTestState
*s
, const char *cmd
, uint16_t addr
, uint32_t value
)
961 qtest_sendf(s
, "%s 0x%x 0x%x\n", cmd
, addr
, value
);
965 void qtest_outb(QTestState
*s
, uint16_t addr
, uint8_t value
)
967 qtest_out(s
, "outb", addr
, value
);
970 void qtest_outw(QTestState
*s
, uint16_t addr
, uint16_t value
)
972 qtest_out(s
, "outw", addr
, value
);
975 void qtest_outl(QTestState
*s
, uint16_t addr
, uint32_t value
)
977 qtest_out(s
, "outl", addr
, value
);
980 static uint32_t qtest_in(QTestState
*s
, const char *cmd
, uint16_t addr
)
986 qtest_sendf(s
, "%s 0x%x\n", cmd
, addr
);
987 args
= qtest_rsp_args(s
, 2);
988 ret
= qemu_strtoul(args
[1], NULL
, 0, &value
);
989 g_assert(!ret
&& value
<= UINT32_MAX
);
995 uint8_t qtest_inb(QTestState
*s
, uint16_t addr
)
997 return qtest_in(s
, "inb", addr
);
1000 uint16_t qtest_inw(QTestState
*s
, uint16_t addr
)
1002 return qtest_in(s
, "inw", addr
);
1005 uint32_t qtest_inl(QTestState
*s
, uint16_t addr
)
1007 return qtest_in(s
, "inl", addr
);
1010 static void qtest_write(QTestState
*s
, const char *cmd
, uint64_t addr
,
1013 qtest_sendf(s
, "%s 0x%" PRIx64
" 0x%" PRIx64
"\n", cmd
, addr
, value
);
1017 void qtest_writeb(QTestState
*s
, uint64_t addr
, uint8_t value
)
1019 qtest_write(s
, "writeb", addr
, value
);
1022 void qtest_writew(QTestState
*s
, uint64_t addr
, uint16_t value
)
1024 qtest_write(s
, "writew", addr
, value
);
1027 void qtest_writel(QTestState
*s
, uint64_t addr
, uint32_t value
)
1029 qtest_write(s
, "writel", addr
, value
);
1032 void qtest_writeq(QTestState
*s
, uint64_t addr
, uint64_t value
)
1034 qtest_write(s
, "writeq", addr
, value
);
1037 static uint64_t qtest_read(QTestState
*s
, const char *cmd
, uint64_t addr
)
1043 qtest_sendf(s
, "%s 0x%" PRIx64
"\n", cmd
, addr
);
1044 args
= qtest_rsp_args(s
, 2);
1045 ret
= qemu_strtou64(args
[1], NULL
, 0, &value
);
1052 uint8_t qtest_readb(QTestState
*s
, uint64_t addr
)
1054 return qtest_read(s
, "readb", addr
);
1057 uint16_t qtest_readw(QTestState
*s
, uint64_t addr
)
1059 return qtest_read(s
, "readw", addr
);
1062 uint32_t qtest_readl(QTestState
*s
, uint64_t addr
)
1064 return qtest_read(s
, "readl", addr
);
1067 uint64_t qtest_readq(QTestState
*s
, uint64_t addr
)
1069 return qtest_read(s
, "readq", addr
);
1072 static int hex2nib(char ch
)
1074 if (ch
>= '0' && ch
<= '9') {
1076 } else if (ch
>= 'a' && ch
<= 'f') {
1077 return 10 + (ch
- 'a');
1078 } else if (ch
>= 'A' && ch
<= 'F') {
1079 return 10 + (ch
- 'a');
1085 void qtest_memread(QTestState
*s
, uint64_t addr
, void *data
, size_t size
)
1087 uint8_t *ptr
= data
;
1095 qtest_sendf(s
, "read 0x%" PRIx64
" 0x%zx\n", addr
, size
);
1096 args
= qtest_rsp_args(s
, 2);
1098 for (i
= 0; i
< size
; i
++) {
1099 ptr
[i
] = hex2nib(args
[1][2 + (i
* 2)]) << 4;
1100 ptr
[i
] |= hex2nib(args
[1][2 + (i
* 2) + 1]);
1106 uint64_t qtest_rtas_call(QTestState
*s
, const char *name
,
1107 uint32_t nargs
, uint64_t args
,
1108 uint32_t nret
, uint64_t ret
)
1110 qtest_sendf(s
, "rtas %s %u 0x%"PRIx64
" %u 0x%"PRIx64
"\n",
1111 name
, nargs
, args
, nret
, ret
);
1116 void qtest_add_func(const char *str
, void (*fn
)(void))
1118 gchar
*path
= g_strdup_printf("/%s/%s", qtest_get_arch(), str
);
1119 g_test_add_func(path
, fn
);
1123 void qtest_add_data_func_full(const char *str
, void *data
,
1124 void (*fn
)(const void *),
1125 GDestroyNotify data_free_func
)
1127 gchar
*path
= g_strdup_printf("/%s/%s", qtest_get_arch(), str
);
1128 g_test_add_data_func_full(path
, data
, fn
, data_free_func
);
1132 void qtest_add_data_func(const char *str
, const void *data
,
1133 void (*fn
)(const void *))
1135 gchar
*path
= g_strdup_printf("/%s/%s", qtest_get_arch(), str
);
1136 g_test_add_data_func(path
, data
, fn
);
1140 void qtest_bufwrite(QTestState
*s
, uint64_t addr
, const void *data
, size_t size
)
1144 bdata
= g_base64_encode(data
, size
);
1145 qtest_sendf(s
, "b64write 0x%" PRIx64
" 0x%zx ", addr
, size
);
1146 s
->ops
.send(s
, bdata
);
1147 s
->ops
.send(s
, "\n");
1152 void qtest_bufread(QTestState
*s
, uint64_t addr
, void *data
, size_t size
)
1157 qtest_sendf(s
, "b64read 0x%" PRIx64
" 0x%zx\n", addr
, size
);
1158 args
= qtest_rsp_args(s
, 2);
1160 g_base64_decode_inplace(args
[1], &len
);
1162 fprintf(stderr
, "bufread: asked for %zu bytes but decoded %zu\n",
1164 len
= MIN(len
, size
);
1167 memcpy(data
, args
[1], len
);
1171 void qtest_memwrite(QTestState
*s
, uint64_t addr
, const void *data
, size_t size
)
1173 const uint8_t *ptr
= data
;
1181 enc
= g_malloc(2 * size
+ 1);
1183 for (i
= 0; i
< size
; i
++) {
1184 sprintf(&enc
[i
* 2], "%02x", ptr
[i
]);
1187 qtest_sendf(s
, "write 0x%" PRIx64
" 0x%zx 0x%s\n", addr
, size
, enc
);
1192 void qtest_memset(QTestState
*s
, uint64_t addr
, uint8_t pattern
, size_t size
)
1194 qtest_sendf(s
, "memset 0x%" PRIx64
" 0x%zx 0x%02x\n", addr
, size
, pattern
);
1198 void qtest_qmp_assert_success(QTestState
*qts
, const char *fmt
, ...)
1204 response
= qtest_vqmp(qts
, fmt
, ap
);
1208 if (!qdict_haskey(response
, "return")) {
1209 GString
*s
= qobject_to_json_pretty(QOBJECT(response
), true);
1210 g_test_message("%s", s
->str
);
1211 g_string_free(s
, true);
1213 g_assert(qdict_haskey(response
, "return"));
1214 qobject_unref(response
);
1217 bool qtest_big_endian(QTestState
*s
)
1219 return s
->big_endian
;
1222 static bool qtest_check_machine_version(const char *mname
, const char *basename
,
1223 int major
, int minor
)
1228 newname
= g_strdup_printf("%s-%i.%i", basename
, major
, minor
);
1229 is_equal
= g_str_equal(mname
, newname
);
1235 static bool qtest_is_old_versioned_machine(const char *mname
)
1237 const char *dash
= strrchr(mname
, '-');
1238 const char *dot
= strrchr(mname
, '.');
1241 const int major
= QEMU_VERSION_MAJOR
;
1242 const int minor
= QEMU_VERSION_MINOR
;
1245 if (dash
&& dot
&& dot
> dash
) {
1246 for (chr
= dash
+ 1; *chr
; chr
++) {
1247 if (!qemu_isdigit(*chr
) && *chr
!= '.') {
1252 * Now check if it is one of the latest versions. Check major + 1
1253 * and minor + 1 versions as well, since they might already exist
1254 * in the development branch.
1256 bname
= g_strdup(mname
);
1257 bname
[dash
- mname
] = 0;
1258 res
= !qtest_check_machine_version(mname
, bname
, major
+ 1, 0) &&
1259 !qtest_check_machine_version(mname
, bname
, major
, minor
+ 1) &&
1260 !qtest_check_machine_version(mname
, bname
, major
, minor
);
1273 * Returns an array with pointers to the available machine names.
1274 * The terminating entry has the name set to NULL.
1276 static struct MachInfo
*qtest_get_machines(void)
1278 static struct MachInfo
*machines
;
1279 QDict
*response
, *minfo
;
1281 const QListEntry
*p
;
1291 qts
= qtest_init("-machine none");
1292 response
= qtest_qmp(qts
, "{ 'execute': 'query-machines' }");
1294 list
= qdict_get_qlist(response
, "return");
1297 machines
= g_new(struct MachInfo
, qlist_size(list
) + 1);
1299 for (p
= qlist_first(list
), idx
= 0; p
; p
= qlist_next(p
), idx
++) {
1300 minfo
= qobject_to(QDict
, qlist_entry_obj(p
));
1303 qobj
= qdict_get(minfo
, "name");
1305 qstr
= qobject_to(QString
, qobj
);
1307 machines
[idx
].name
= g_strdup(qstring_get_str(qstr
));
1309 qobj
= qdict_get(minfo
, "alias");
1310 if (qobj
) { /* The alias is optional */
1311 qstr
= qobject_to(QString
, qobj
);
1313 machines
[idx
].alias
= g_strdup(qstring_get_str(qstr
));
1315 machines
[idx
].alias
= NULL
;
1320 qobject_unref(response
);
1322 memset(&machines
[idx
], 0, sizeof(struct MachInfo
)); /* Terminating entry */
1326 void qtest_cb_for_every_machine(void (*cb
)(const char *machine
),
1327 bool skip_old_versioned
)
1329 struct MachInfo
*machines
;
1332 machines
= qtest_get_machines();
1334 for (i
= 0; machines
[i
].name
!= NULL
; i
++) {
1335 /* Ignore machines that cannot be used for qtests */
1336 if (!strncmp("xenfv", machines
[i
].name
, 5) ||
1337 g_str_equal("xenpv", machines
[i
].name
)) {
1340 if (!skip_old_versioned
||
1341 !qtest_is_old_versioned_machine(machines
[i
].name
)) {
1342 cb(machines
[i
].name
);
1347 bool qtest_has_machine(const char *machine
)
1349 struct MachInfo
*machines
;
1352 machines
= qtest_get_machines();
1354 for (i
= 0; machines
[i
].name
!= NULL
; i
++) {
1355 if (g_str_equal(machine
, machines
[i
].name
) ||
1356 (machines
[i
].alias
&& g_str_equal(machine
, machines
[i
].alias
))) {
1364 bool qtest_has_device(const char *device
)
1367 const QListEntry
*p
;
1376 QTestState
*qts
= qtest_init("-machine none");
1379 qdict_put_bool(args
, "abstract", false);
1380 qdict_put_str(args
, "implements", "device");
1382 resp
= qtest_qmp(qts
, "{'execute': 'qom-list-types', 'arguments': %p }",
1384 g_assert(qdict_haskey(resp
, "return"));
1385 list
= qdict_get_qlist(resp
, "return");
1387 qobject_unref(resp
);
1392 for (p
= qlist_first(list
), idx
= 0; p
; p
= qlist_next(p
), idx
++) {
1393 devinfo
= qobject_to(QDict
, qlist_entry_obj(p
));
1396 qobj
= qdict_get(devinfo
, "name");
1398 qstr
= qobject_to(QString
, qobj
);
1400 if (g_str_equal(qstring_get_str(qstr
), device
)) {
1409 * Generic hot-plugging test via the device_add QMP commands.
1411 void qtest_qmp_device_add_qdict(QTestState
*qts
, const char *drv
,
1412 const QDict
*arguments
)
1415 QDict
*args
= arguments
? qdict_clone_shallow(arguments
) : qdict_new();
1417 g_assert(!qdict_haskey(args
, "driver"));
1418 qdict_put_str(args
, "driver", drv
);
1419 resp
= qtest_qmp(qts
, "{'execute': 'device_add', 'arguments': %p}", args
);
1421 g_assert(!qdict_haskey(resp
, "event")); /* We don't expect any events */
1422 g_assert(!qdict_haskey(resp
, "error"));
1423 qobject_unref(resp
);
1426 void qtest_qmp_device_add(QTestState
*qts
, const char *driver
, const char *id
,
1427 const char *fmt
, ...)
1433 args
= qdict_from_vjsonf_nofail(fmt
, ap
);
1436 g_assert(!qdict_haskey(args
, "id"));
1437 qdict_put_str(args
, "id", id
);
1439 qtest_qmp_device_add_qdict(qts
, driver
, args
);
1440 qobject_unref(args
);
1444 void qtest_qmp_add_client(QTestState
*qts
, const char *protocol
, int fd
)
1448 resp
= qtest_qmp_fds(qts
, &fd
, 1, "{'execute': 'getfd',"
1449 "'arguments': {'fdname': 'fdname'}}");
1451 g_assert(!qdict_haskey(resp
, "event")); /* We don't expect any events */
1452 g_assert(!qdict_haskey(resp
, "error"));
1453 qobject_unref(resp
);
1456 qts
, "{'execute': 'add_client',"
1457 "'arguments': {'protocol': %s, 'fdname': 'fdname'}}", protocol
);
1459 g_assert(!qdict_haskey(resp
, "event")); /* We don't expect any events */
1460 g_assert(!qdict_haskey(resp
, "error"));
1461 qobject_unref(resp
);
1466 * Generic hot-unplugging test via the device_del QMP command.
1467 * Device deletion will get one response and one event. For example:
1469 * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1471 * will get this one:
1473 * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1474 * "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1475 * "path": "/machine/peripheral/scsi-hd"}}
1481 void qtest_qmp_device_del_send(QTestState
*qts
, const char *id
)
1483 QDict
*rsp
= qtest_qmp(qts
, "{'execute': 'device_del', "
1484 "'arguments': {'id': %s}}", id
);
1486 g_assert(qdict_haskey(rsp
, "return"));
1487 g_assert(!qdict_haskey(rsp
, "error"));
1491 void qtest_qmp_device_del(QTestState
*qts
, const char *id
)
1493 qtest_qmp_device_del_send(qts
, id
);
1494 qtest_qmp_eventwait(qts
, "DEVICE_DELETED");
1497 static void qtest_client_set_tx_handler(QTestState
*s
,
1502 static void qtest_client_set_rx_handler(QTestState
*s
, QTestRecvFn recv
)
1504 s
->ops
.recv_line
= recv
;
1506 /* A type-safe wrapper for s->send() */
1507 static void send_wrapper(QTestState
*s
, const char *buf
)
1509 s
->ops
.external_send(s
, buf
);
1512 static GString
*qtest_client_inproc_recv_line(QTestState
*s
)
1518 eol
= strchr(s
->rx
->str
, '\n');
1519 offset
= eol
- s
->rx
->str
;
1520 line
= g_string_new_len(s
->rx
->str
, offset
);
1521 g_string_erase(s
->rx
, 0, offset
+ 1);
1525 QTestState
*qtest_inproc_init(QTestState
**s
, bool log
, const char* arch
,
1526 void (*send
)(void*, const char*))
1529 qts
= g_new0(QTestState
, 1);
1530 qts
->pending_events
= NULL
;
1531 *s
= qts
; /* Expose qts early on, since the query endianness relies on it */
1533 for (int i
= 0; i
< MAX_IRQ
; i
++) {
1534 qts
->irq_level
[i
] = false;
1537 qtest_client_set_rx_handler(qts
, qtest_client_inproc_recv_line
);
1539 /* send() may not have a matching protoype, so use a type-safe wrapper */
1540 qts
->ops
.external_send
= send
;
1541 qtest_client_set_tx_handler(qts
, send_wrapper
);
1543 qts
->big_endian
= qtest_query_target_endianness(qts
);
1546 * Set a dummy path for QTEST_QEMU_BINARY. Doesn't need to exist, but this
1547 * way, qtest_get_arch works for inproc qtest.
1549 gchar
*bin_path
= g_strconcat("/qemu-system-", arch
, NULL
);
1550 g_setenv("QTEST_QEMU_BINARY", bin_path
, 0);
1556 void qtest_client_inproc_recv(void *opaque
, const char *str
)
1558 QTestState
*qts
= *(QTestState
**)opaque
;
1561 qts
->rx
= g_string_new(NULL
);
1563 g_string_append(qts
->rx
, str
);
1567 void qtest_qom_set_bool(QTestState
*s
, const char *path
, const char *property
,
1572 r
= qtest_qmp(s
, "{ 'execute': 'qom-set', 'arguments': "
1573 "{ 'path': %s, 'property': %s, 'value': %i } }",
1574 path
, property
, value
);
1578 bool qtest_qom_get_bool(QTestState
*s
, const char *path
, const char *property
)
1583 r
= qtest_qmp(s
, "{ 'execute': 'qom-get', 'arguments': "
1584 "{ 'path': %s, 'property': %s } }", path
, property
);
1585 b
= qdict_get_bool(r
, "return");