target/i386: reimplement 0x0f 0x50-0x5f, add AVX
[qemu.git] / tests / qtest / libqtest.c
blobb23eb3edc362e94a7b6fc46ea7e305d4df9ed320
1 /*
2 * QTest
4 * Copyright IBM, Corp. 2012
5 * Copyright Red Hat, Inc. 2012
6 * Copyright SUSE LINUX Products GmbH 2013
8 * Authors:
9 * Anthony Liguori <aliguori@us.ibm.com>
10 * Paolo Bonzini <pbonzini@redhat.com>
11 * Andreas Färber <afaerber@suse.de>
13 * This work is licensed under the terms of the GNU GPL, version 2 or later.
14 * See the COPYING file in the top-level directory.
17 #include "qemu/osdep.h"
19 #include <sys/socket.h>
20 #include <sys/wait.h>
21 #include <sys/un.h>
22 #ifdef __linux__
23 #include <sys/prctl.h>
24 #endif /* __linux__ */
26 #include "libqtest.h"
27 #include "libqmp.h"
28 #include "qemu/ctype.h"
29 #include "qemu/cutils.h"
30 #include "qapi/qmp/qdict.h"
31 #include "qapi/qmp/qjson.h"
32 #include "qapi/qmp/qlist.h"
33 #include "qapi/qmp/qstring.h"
35 #define MAX_IRQ 256
36 #define SOCKET_TIMEOUT 50
38 typedef void (*QTestSendFn)(QTestState *s, const char *buf);
39 typedef void (*ExternalSendFn)(void *s, const char *buf);
40 typedef GString* (*QTestRecvFn)(QTestState *);
42 typedef struct QTestClientTransportOps {
43 QTestSendFn send; /* for sending qtest commands */
46 * use external_send to send qtest command strings through functions which
47 * do not accept a QTestState as the first parameter.
49 ExternalSendFn external_send;
51 QTestRecvFn recv_line; /* for receiving qtest command responses */
52 } QTestTransportOps;
54 struct QTestState
56 int fd;
57 int qmp_fd;
58 pid_t qemu_pid; /* our child QEMU process */
59 int wstatus;
60 int expected_status;
61 bool big_endian;
62 bool irq_level[MAX_IRQ];
63 GString *rx;
64 QTestTransportOps ops;
65 GList *pending_events;
68 static GHookList abrt_hooks;
69 static void (*sighandler_old)(int);
71 static int qtest_query_target_endianness(QTestState *s);
73 static void qtest_client_socket_send(QTestState*, const char *buf);
74 static void socket_send(int fd, const char *buf, size_t size);
76 static GString *qtest_client_socket_recv_line(QTestState *);
78 static void qtest_client_set_tx_handler(QTestState *s, QTestSendFn send);
79 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv);
81 static int init_socket(const char *socket_path)
83 int sock = qtest_socket_server(socket_path);
84 qemu_set_cloexec(sock);
85 return sock;
88 static int socket_accept(int sock)
90 struct sockaddr_un addr;
91 socklen_t addrlen;
92 int ret;
93 struct timeval timeout = { .tv_sec = SOCKET_TIMEOUT,
94 .tv_usec = 0 };
96 if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
97 (void *)&timeout, sizeof(timeout))) {
98 fprintf(stderr, "%s failed to set SO_RCVTIMEO: %s\n",
99 __func__, strerror(errno));
100 closesocket(sock);
101 return -1;
104 do {
105 addrlen = sizeof(addr);
106 ret = accept(sock, (struct sockaddr *)&addr, &addrlen);
107 } while (ret == -1 && errno == EINTR);
108 if (ret == -1) {
109 fprintf(stderr, "%s failed: %s\n", __func__, strerror(errno));
111 closesocket(sock);
113 return ret;
116 bool qtest_probe_child(QTestState *s)
118 pid_t pid = s->qemu_pid;
120 if (pid != -1) {
121 pid = waitpid(pid, &s->wstatus, WNOHANG);
122 if (pid == 0) {
123 return true;
125 s->qemu_pid = -1;
127 return false;
130 void qtest_set_expected_status(QTestState *s, int status)
132 s->expected_status = status;
135 void qtest_kill_qemu(QTestState *s)
137 pid_t pid = s->qemu_pid;
138 int wstatus;
140 /* Skip wait if qtest_probe_child already reaped. */
141 if (pid != -1) {
142 kill(pid, SIGTERM);
143 TFR(pid = waitpid(s->qemu_pid, &s->wstatus, 0));
144 assert(pid == s->qemu_pid);
145 s->qemu_pid = -1;
149 * Check whether qemu exited with expected exit status; anything else is
150 * fishy and should be logged with as much detail as possible.
152 wstatus = s->wstatus;
153 if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != s->expected_status) {
154 fprintf(stderr, "%s:%d: kill_qemu() tried to terminate QEMU "
155 "process but encountered exit status %d (expected %d)\n",
156 __FILE__, __LINE__, WEXITSTATUS(wstatus), s->expected_status);
157 abort();
158 } else if (WIFSIGNALED(wstatus)) {
159 int sig = WTERMSIG(wstatus);
160 const char *signame = strsignal(sig) ?: "unknown ???";
161 const char *dump = WCOREDUMP(wstatus) ? " (core dumped)" : "";
163 fprintf(stderr, "%s:%d: kill_qemu() detected QEMU death "
164 "from signal %d (%s)%s\n",
165 __FILE__, __LINE__, sig, signame, dump);
166 abort();
170 static void kill_qemu_hook_func(void *s)
172 qtest_kill_qemu(s);
175 static void sigabrt_handler(int signo)
177 g_hook_list_invoke(&abrt_hooks, FALSE);
180 static void setup_sigabrt_handler(void)
182 sighandler_old = signal(SIGABRT, sigabrt_handler);
185 static void cleanup_sigabrt_handler(void)
187 signal(SIGABRT, sighandler_old);
190 static bool hook_list_is_empty(GHookList *hook_list)
192 GHook *hook = g_hook_first_valid(hook_list, TRUE);
194 if (!hook) {
195 return true;
198 g_hook_unref(hook_list, hook);
199 return false;
202 void qtest_add_abrt_handler(GHookFunc fn, const void *data)
204 GHook *hook;
206 if (!abrt_hooks.is_setup) {
207 g_hook_list_init(&abrt_hooks, sizeof(GHook));
210 /* Only install SIGABRT handler once */
211 if (hook_list_is_empty(&abrt_hooks)) {
212 setup_sigabrt_handler();
215 hook = g_hook_alloc(&abrt_hooks);
216 hook->func = fn;
217 hook->data = (void *)data;
219 g_hook_prepend(&abrt_hooks, hook);
222 void qtest_remove_abrt_handler(void *data)
224 GHook *hook = g_hook_find_data(&abrt_hooks, TRUE, data);
225 g_hook_destroy_link(&abrt_hooks, hook);
227 /* Uninstall SIGABRT handler on last instance */
228 if (hook_list_is_empty(&abrt_hooks)) {
229 cleanup_sigabrt_handler();
233 static const char *qtest_qemu_binary(void)
235 const char *qemu_bin;
237 qemu_bin = getenv("QTEST_QEMU_BINARY");
238 if (!qemu_bin) {
239 fprintf(stderr, "Environment variable QTEST_QEMU_BINARY required\n");
240 exit(1);
243 return qemu_bin;
246 QTestState *qtest_init_without_qmp_handshake(const char *extra_args)
248 QTestState *s;
249 int sock, qmpsock, i;
250 gchar *socket_path;
251 gchar *qmp_socket_path;
252 gchar *command;
253 const char *qemu_binary = qtest_qemu_binary();
254 const char *trace = g_getenv("QTEST_TRACE");
255 g_autofree char *tracearg = trace ?
256 g_strdup_printf("-trace %s ", trace) : g_strdup("");
258 s = g_new(QTestState, 1);
260 socket_path = g_strdup_printf("%s/qtest-%d.sock",
261 g_get_tmp_dir(), getpid());
262 qmp_socket_path = g_strdup_printf("%s/qtest-%d.qmp",
263 g_get_tmp_dir(), getpid());
265 /* It's possible that if an earlier test run crashed it might
266 * have left a stale unix socket lying around. Delete any
267 * stale old socket to avoid spurious test failures with
268 * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1)
270 unlink(socket_path);
271 unlink(qmp_socket_path);
273 sock = init_socket(socket_path);
274 qmpsock = init_socket(qmp_socket_path);
276 qtest_client_set_rx_handler(s, qtest_client_socket_recv_line);
277 qtest_client_set_tx_handler(s, qtest_client_socket_send);
279 qtest_add_abrt_handler(kill_qemu_hook_func, s);
281 command = g_strdup_printf("exec %s %s"
282 "-qtest unix:%s "
283 "-qtest-log %s "
284 "-chardev socket,path=%s,id=char0 "
285 "-mon chardev=char0,mode=control "
286 "-display none "
287 "%s"
288 " -accel qtest",
289 qemu_binary, tracearg, socket_path,
290 getenv("QTEST_LOG") ? "/dev/fd/2" : "/dev/null",
291 qmp_socket_path,
292 extra_args ?: "");
294 g_test_message("starting QEMU: %s", command);
296 s->pending_events = NULL;
297 s->wstatus = 0;
298 s->expected_status = 0;
299 s->qemu_pid = fork();
300 if (s->qemu_pid == 0) {
301 #ifdef __linux__
303 * Although we register a ABRT handler to kill off QEMU
304 * when g_assert() triggers, we want an extra safety
305 * net. The QEMU process might be non-functional and
306 * thus not have responded to SIGTERM. The test script
307 * might also have crashed with SEGV, in which case the
308 * cleanup handlers won't ever run.
310 * This PR_SET_PDEATHSIG setup will ensure any remaining
311 * QEMU will get terminated with SIGKILL in these cases.
313 prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
314 #endif /* __linux__ */
315 if (!g_setenv("QEMU_AUDIO_DRV", "none", true)) {
316 exit(1);
318 execlp("/bin/sh", "sh", "-c", command, NULL);
319 exit(1);
322 g_free(command);
323 s->fd = socket_accept(sock);
324 if (s->fd >= 0) {
325 s->qmp_fd = socket_accept(qmpsock);
327 unlink(socket_path);
328 unlink(qmp_socket_path);
329 g_free(socket_path);
330 g_free(qmp_socket_path);
332 g_assert(s->fd >= 0 && s->qmp_fd >= 0);
334 s->rx = g_string_new("");
335 for (i = 0; i < MAX_IRQ; i++) {
336 s->irq_level[i] = false;
339 if (getenv("QTEST_STOP")) {
340 kill(s->qemu_pid, SIGSTOP);
343 /* ask endianness of the target */
345 s->big_endian = qtest_query_target_endianness(s);
347 return s;
350 QTestState *qtest_init(const char *extra_args)
352 QTestState *s = qtest_init_without_qmp_handshake(extra_args);
353 QDict *greeting;
355 /* Read the QMP greeting and then do the handshake */
356 greeting = qtest_qmp_receive(s);
357 qobject_unref(greeting);
358 qobject_unref(qtest_qmp(s, "{ 'execute': 'qmp_capabilities' }"));
360 return s;
363 QTestState *qtest_vinitf(const char *fmt, va_list ap)
365 char *args = g_strdup_vprintf(fmt, ap);
366 QTestState *s;
368 s = qtest_init(args);
369 g_free(args);
370 return s;
373 QTestState *qtest_initf(const char *fmt, ...)
375 va_list ap;
376 QTestState *s;
378 va_start(ap, fmt);
379 s = qtest_vinitf(fmt, ap);
380 va_end(ap);
381 return s;
384 QTestState *qtest_init_with_serial(const char *extra_args, int *sock_fd)
386 int sock_fd_init;
387 g_autofree char *sock_dir = NULL;
388 char *sock_path;
389 QTestState *qts;
391 sock_dir = g_dir_make_tmp("qtest-serial-XXXXXX", NULL);
392 g_assert_true(sock_dir != NULL);
393 sock_path = g_strdup_printf("%s/sock", sock_dir);
395 sock_fd_init = init_socket(sock_path);
397 qts = qtest_initf("-chardev socket,id=s0,path=%s -serial chardev:s0 %s",
398 sock_path, extra_args);
400 *sock_fd = socket_accept(sock_fd_init);
402 unlink(sock_path);
403 g_free(sock_path);
404 rmdir(sock_dir);
406 g_assert_true(*sock_fd >= 0);
408 return qts;
411 void qtest_quit(QTestState *s)
413 qtest_remove_abrt_handler(s);
415 qtest_kill_qemu(s);
416 closesocket(s->fd);
417 closesocket(s->qmp_fd);
418 g_string_free(s->rx, true);
420 for (GList *it = s->pending_events; it != NULL; it = it->next) {
421 qobject_unref((QDict *)it->data);
424 g_list_free(s->pending_events);
426 g_free(s);
429 static void socket_send(int fd, const char *buf, size_t size)
431 size_t res = qemu_write_full(fd, buf, size);
433 assert(res == size);
436 static void qtest_client_socket_send(QTestState *s, const char *buf)
438 socket_send(s->fd, buf, strlen(buf));
441 static void G_GNUC_PRINTF(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...)
443 va_list ap;
445 va_start(ap, fmt);
446 gchar *str = g_strdup_vprintf(fmt, ap);
447 va_end(ap);
449 s->ops.send(s, str);
450 g_free(str);
453 static GString *qtest_client_socket_recv_line(QTestState *s)
455 GString *line;
456 size_t offset;
457 char *eol;
459 while ((eol = strchr(s->rx->str, '\n')) == NULL) {
460 ssize_t len;
461 char buffer[1024];
463 len = read(s->fd, buffer, sizeof(buffer));
464 if (len == -1 && errno == EINTR) {
465 continue;
468 if (len == -1 || len == 0) {
469 fprintf(stderr, "Broken pipe\n");
470 abort();
473 g_string_append_len(s->rx, buffer, len);
476 offset = eol - s->rx->str;
477 line = g_string_new_len(s->rx->str, offset);
478 g_string_erase(s->rx, 0, offset + 1);
480 return line;
483 static gchar **qtest_rsp_args(QTestState *s, int expected_args)
485 GString *line;
486 gchar **words;
487 int i;
489 redo:
490 line = s->ops.recv_line(s);
491 words = g_strsplit(line->str, " ", 0);
492 g_string_free(line, TRUE);
494 if (strcmp(words[0], "IRQ") == 0) {
495 long irq;
496 int ret;
498 g_assert(words[1] != NULL);
499 g_assert(words[2] != NULL);
501 ret = qemu_strtol(words[2], NULL, 0, &irq);
502 g_assert(!ret);
503 g_assert_cmpint(irq, >=, 0);
504 g_assert_cmpint(irq, <, MAX_IRQ);
506 if (strcmp(words[1], "raise") == 0) {
507 s->irq_level[irq] = true;
508 } else {
509 s->irq_level[irq] = false;
512 g_strfreev(words);
513 goto redo;
516 g_assert(words[0] != NULL);
517 g_assert_cmpstr(words[0], ==, "OK");
519 for (i = 0; i < expected_args; i++) {
520 g_assert(words[i] != NULL);
523 return words;
526 static void qtest_rsp(QTestState *s)
528 gchar **words = qtest_rsp_args(s, 0);
530 g_strfreev(words);
533 static int qtest_query_target_endianness(QTestState *s)
535 gchar **args;
536 int big_endian;
538 qtest_sendf(s, "endianness\n");
539 args = qtest_rsp_args(s, 1);
540 g_assert(strcmp(args[1], "big") == 0 || strcmp(args[1], "little") == 0);
541 big_endian = strcmp(args[1], "big") == 0;
542 g_strfreev(args);
544 return big_endian;
547 QDict *qtest_qmp_receive(QTestState *s)
549 while (true) {
550 QDict *response = qtest_qmp_receive_dict(s);
552 if (!qdict_get_try_str(response, "event")) {
553 return response;
555 /* Stash the event for a later consumption */
556 s->pending_events = g_list_append(s->pending_events, response);
560 QDict *qtest_qmp_receive_dict(QTestState *s)
562 return qmp_fd_receive(s->qmp_fd);
565 int qtest_socket_server(const char *socket_path)
567 struct sockaddr_un addr;
568 int sock;
569 int ret;
571 sock = socket(PF_UNIX, SOCK_STREAM, 0);
572 g_assert_cmpint(sock, !=, -1);
574 addr.sun_family = AF_UNIX;
575 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
577 do {
578 ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
579 } while (ret == -1 && errno == EINTR);
580 g_assert_cmpint(ret, !=, -1);
581 ret = listen(sock, 1);
582 g_assert_cmpint(ret, !=, -1);
584 return sock;
587 #ifndef _WIN32
588 void qtest_qmp_vsend_fds(QTestState *s, int *fds, size_t fds_num,
589 const char *fmt, va_list ap)
591 qmp_fd_vsend_fds(s->qmp_fd, fds, fds_num, fmt, ap);
593 #endif
595 void qtest_qmp_vsend(QTestState *s, const char *fmt, va_list ap)
597 qmp_fd_vsend(s->qmp_fd, fmt, ap);
600 #ifndef _WIN32
601 QDict *qtest_vqmp_fds(QTestState *s, int *fds, size_t fds_num,
602 const char *fmt, va_list ap)
604 qtest_qmp_vsend_fds(s, fds, fds_num, fmt, ap);
606 /* Receive reply */
607 return qtest_qmp_receive(s);
609 #endif
611 QDict *qtest_vqmp(QTestState *s, const char *fmt, va_list ap)
613 qtest_qmp_vsend(s, fmt, ap);
615 /* Receive reply */
616 return qtest_qmp_receive(s);
619 #ifndef _WIN32
620 QDict *qtest_qmp_fds(QTestState *s, int *fds, size_t fds_num,
621 const char *fmt, ...)
623 va_list ap;
624 QDict *response;
626 va_start(ap, fmt);
627 response = qtest_vqmp_fds(s, fds, fds_num, fmt, ap);
628 va_end(ap);
629 return response;
631 #endif
633 QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
635 va_list ap;
636 QDict *response;
638 va_start(ap, fmt);
639 response = qtest_vqmp(s, fmt, ap);
640 va_end(ap);
641 return response;
644 void qtest_qmp_send(QTestState *s, const char *fmt, ...)
646 va_list ap;
648 va_start(ap, fmt);
649 qtest_qmp_vsend(s, fmt, ap);
650 va_end(ap);
653 void qtest_qmp_send_raw(QTestState *s, const char *fmt, ...)
655 va_list ap;
657 va_start(ap, fmt);
658 qmp_fd_vsend_raw(s->qmp_fd, fmt, ap);
659 va_end(ap);
662 QDict *qtest_qmp_event_ref(QTestState *s, const char *event)
664 while (s->pending_events) {
666 GList *first = s->pending_events;
667 QDict *response = (QDict *)first->data;
669 s->pending_events = g_list_delete_link(s->pending_events, first);
671 if (!strcmp(qdict_get_str(response, "event"), event)) {
672 return response;
674 qobject_unref(response);
676 return NULL;
679 QDict *qtest_qmp_eventwait_ref(QTestState *s, const char *event)
681 QDict *response = qtest_qmp_event_ref(s, event);
683 if (response) {
684 return response;
687 for (;;) {
688 response = qtest_qmp_receive_dict(s);
689 if ((qdict_haskey(response, "event")) &&
690 (strcmp(qdict_get_str(response, "event"), event) == 0)) {
691 return response;
693 qobject_unref(response);
697 void qtest_qmp_eventwait(QTestState *s, const char *event)
699 QDict *response;
701 response = qtest_qmp_eventwait_ref(s, event);
702 qobject_unref(response);
705 char *qtest_vhmp(QTestState *s, const char *fmt, va_list ap)
707 char *cmd;
708 QDict *resp;
709 char *ret;
711 cmd = g_strdup_vprintf(fmt, ap);
712 resp = qtest_qmp(s, "{'execute': 'human-monitor-command',"
713 " 'arguments': {'command-line': %s}}",
714 cmd);
715 ret = g_strdup(qdict_get_try_str(resp, "return"));
716 g_assert(ret);
717 qobject_unref(resp);
718 g_free(cmd);
719 return ret;
722 char *qtest_hmp(QTestState *s, const char *fmt, ...)
724 va_list ap;
725 char *ret;
727 va_start(ap, fmt);
728 ret = qtest_vhmp(s, fmt, ap);
729 va_end(ap);
730 return ret;
733 const char *qtest_get_arch(void)
735 const char *qemu = qtest_qemu_binary();
736 const char *end = strrchr(qemu, '-');
738 if (!end) {
739 fprintf(stderr, "Can't determine architecture from binary name.\n");
740 exit(1);
743 if (!strstr(qemu, "-system-")) {
744 fprintf(stderr, "QTEST_QEMU_BINARY must end with *-system-<arch> "
745 "where 'arch' is the target\narchitecture (x86_64, aarch64, "
746 "etc).\n");
747 exit(1);
750 return end + 1;
753 bool qtest_has_accel(const char *accel_name)
755 if (g_str_equal(accel_name, "tcg")) {
756 #if defined(CONFIG_TCG)
757 return true;
758 #else
759 return false;
760 #endif
761 } else if (g_str_equal(accel_name, "kvm")) {
762 int i;
763 const char *arch = qtest_get_arch();
764 const char *targets[] = { CONFIG_KVM_TARGETS };
766 for (i = 0; i < ARRAY_SIZE(targets); i++) {
767 if (!strncmp(targets[i], arch, strlen(arch))) {
768 if (!access("/dev/kvm", R_OK | W_OK)) {
769 return true;
773 } else {
774 /* not implemented */
775 g_assert_not_reached();
777 return false;
780 bool qtest_get_irq(QTestState *s, int num)
782 /* dummy operation in order to make sure irq is up to date */
783 qtest_inb(s, 0);
785 return s->irq_level[num];
788 void qtest_module_load(QTestState *s, const char *prefix, const char *libname)
790 qtest_sendf(s, "module_load %s %s\n", prefix, libname);
791 qtest_rsp(s);
794 static int64_t qtest_clock_rsp(QTestState *s)
796 gchar **words;
797 int64_t clock;
798 words = qtest_rsp_args(s, 2);
799 clock = g_ascii_strtoll(words[1], NULL, 0);
800 g_strfreev(words);
801 return clock;
804 int64_t qtest_clock_step_next(QTestState *s)
806 qtest_sendf(s, "clock_step\n");
807 return qtest_clock_rsp(s);
810 int64_t qtest_clock_step(QTestState *s, int64_t step)
812 qtest_sendf(s, "clock_step %"PRIi64"\n", step);
813 return qtest_clock_rsp(s);
816 int64_t qtest_clock_set(QTestState *s, int64_t val)
818 qtest_sendf(s, "clock_set %"PRIi64"\n", val);
819 return qtest_clock_rsp(s);
822 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
824 qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
825 qtest_rsp(s);
828 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
830 qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
831 qtest_rsp(s);
834 void qtest_set_irq_in(QTestState *s, const char *qom_path, const char *name,
835 int num, int level)
837 if (!name) {
838 name = "unnamed-gpio-in";
840 qtest_sendf(s, "set_irq_in %s %s %d %d\n", qom_path, name, num, level);
841 qtest_rsp(s);
844 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
846 qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
847 qtest_rsp(s);
850 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
852 qtest_out(s, "outb", addr, value);
855 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
857 qtest_out(s, "outw", addr, value);
860 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
862 qtest_out(s, "outl", addr, value);
865 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
867 gchar **args;
868 int ret;
869 unsigned long value;
871 qtest_sendf(s, "%s 0x%x\n", cmd, addr);
872 args = qtest_rsp_args(s, 2);
873 ret = qemu_strtoul(args[1], NULL, 0, &value);
874 g_assert(!ret && value <= UINT32_MAX);
875 g_strfreev(args);
877 return value;
880 uint8_t qtest_inb(QTestState *s, uint16_t addr)
882 return qtest_in(s, "inb", addr);
885 uint16_t qtest_inw(QTestState *s, uint16_t addr)
887 return qtest_in(s, "inw", addr);
890 uint32_t qtest_inl(QTestState *s, uint16_t addr)
892 return qtest_in(s, "inl", addr);
895 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
896 uint64_t value)
898 qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
899 qtest_rsp(s);
902 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
904 qtest_write(s, "writeb", addr, value);
907 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
909 qtest_write(s, "writew", addr, value);
912 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
914 qtest_write(s, "writel", addr, value);
917 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
919 qtest_write(s, "writeq", addr, value);
922 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
924 gchar **args;
925 int ret;
926 uint64_t value;
928 qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
929 args = qtest_rsp_args(s, 2);
930 ret = qemu_strtou64(args[1], NULL, 0, &value);
931 g_assert(!ret);
932 g_strfreev(args);
934 return value;
937 uint8_t qtest_readb(QTestState *s, uint64_t addr)
939 return qtest_read(s, "readb", addr);
942 uint16_t qtest_readw(QTestState *s, uint64_t addr)
944 return qtest_read(s, "readw", addr);
947 uint32_t qtest_readl(QTestState *s, uint64_t addr)
949 return qtest_read(s, "readl", addr);
952 uint64_t qtest_readq(QTestState *s, uint64_t addr)
954 return qtest_read(s, "readq", addr);
957 static int hex2nib(char ch)
959 if (ch >= '0' && ch <= '9') {
960 return ch - '0';
961 } else if (ch >= 'a' && ch <= 'f') {
962 return 10 + (ch - 'a');
963 } else if (ch >= 'A' && ch <= 'F') {
964 return 10 + (ch - 'a');
965 } else {
966 return -1;
970 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
972 uint8_t *ptr = data;
973 gchar **args;
974 size_t i;
976 if (!size) {
977 return;
980 qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
981 args = qtest_rsp_args(s, 2);
983 for (i = 0; i < size; i++) {
984 ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
985 ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
988 g_strfreev(args);
991 uint64_t qtest_rtas_call(QTestState *s, const char *name,
992 uint32_t nargs, uint64_t args,
993 uint32_t nret, uint64_t ret)
995 qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n",
996 name, nargs, args, nret, ret);
997 qtest_rsp(s);
998 return 0;
1001 void qtest_add_func(const char *str, void (*fn)(void))
1003 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1004 g_test_add_func(path, fn);
1005 g_free(path);
1008 void qtest_add_data_func_full(const char *str, void *data,
1009 void (*fn)(const void *),
1010 GDestroyNotify data_free_func)
1012 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1013 g_test_add_data_func_full(path, data, fn, data_free_func);
1014 g_free(path);
1017 void qtest_add_data_func(const char *str, const void *data,
1018 void (*fn)(const void *))
1020 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1021 g_test_add_data_func(path, data, fn);
1022 g_free(path);
1025 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1027 gchar *bdata;
1029 bdata = g_base64_encode(data, size);
1030 qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
1031 s->ops.send(s, bdata);
1032 s->ops.send(s, "\n");
1033 qtest_rsp(s);
1034 g_free(bdata);
1037 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
1039 gchar **args;
1040 size_t len;
1042 qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
1043 args = qtest_rsp_args(s, 2);
1045 g_base64_decode_inplace(args[1], &len);
1046 if (size != len) {
1047 fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
1048 size, len);
1049 len = MIN(len, size);
1052 memcpy(data, args[1], len);
1053 g_strfreev(args);
1056 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1058 const uint8_t *ptr = data;
1059 size_t i;
1060 char *enc;
1062 if (!size) {
1063 return;
1066 enc = g_malloc(2 * size + 1);
1068 for (i = 0; i < size; i++) {
1069 sprintf(&enc[i * 2], "%02x", ptr[i]);
1072 qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
1073 qtest_rsp(s);
1074 g_free(enc);
1077 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
1079 qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
1080 qtest_rsp(s);
1083 void qtest_qmp_assert_success(QTestState *qts, const char *fmt, ...)
1085 va_list ap;
1086 QDict *response;
1088 va_start(ap, fmt);
1089 response = qtest_vqmp(qts, fmt, ap);
1090 va_end(ap);
1092 g_assert(response);
1093 if (!qdict_haskey(response, "return")) {
1094 GString *s = qobject_to_json_pretty(QOBJECT(response), true);
1095 g_test_message("%s", s->str);
1096 g_string_free(s, true);
1098 g_assert(qdict_haskey(response, "return"));
1099 qobject_unref(response);
1102 bool qtest_big_endian(QTestState *s)
1104 return s->big_endian;
1107 static bool qtest_check_machine_version(const char *mname, const char *basename,
1108 int major, int minor)
1110 char *newname;
1111 bool is_equal;
1113 newname = g_strdup_printf("%s-%i.%i", basename, major, minor);
1114 is_equal = g_str_equal(mname, newname);
1115 g_free(newname);
1117 return is_equal;
1120 static bool qtest_is_old_versioned_machine(const char *mname)
1122 const char *dash = strrchr(mname, '-');
1123 const char *dot = strrchr(mname, '.');
1124 const char *chr;
1125 char *bname;
1126 const int major = QEMU_VERSION_MAJOR;
1127 const int minor = QEMU_VERSION_MINOR;
1128 bool res = false;
1130 if (dash && dot && dot > dash) {
1131 for (chr = dash + 1; *chr; chr++) {
1132 if (!qemu_isdigit(*chr) && *chr != '.') {
1133 return false;
1137 * Now check if it is one of the latest versions. Check major + 1
1138 * and minor + 1 versions as well, since they might already exist
1139 * in the development branch.
1141 bname = g_strdup(mname);
1142 bname[dash - mname] = 0;
1143 res = !qtest_check_machine_version(mname, bname, major + 1, 0) &&
1144 !qtest_check_machine_version(mname, bname, major, minor + 1) &&
1145 !qtest_check_machine_version(mname, bname, major, minor);
1146 g_free(bname);
1149 return res;
1152 struct MachInfo {
1153 char *name;
1154 char *alias;
1158 * Returns an array with pointers to the available machine names.
1159 * The terminating entry has the name set to NULL.
1161 static struct MachInfo *qtest_get_machines(void)
1163 static struct MachInfo *machines;
1164 QDict *response, *minfo;
1165 QList *list;
1166 const QListEntry *p;
1167 QObject *qobj;
1168 QString *qstr;
1169 QTestState *qts;
1170 int idx;
1172 if (machines) {
1173 return machines;
1176 qts = qtest_init("-machine none");
1177 response = qtest_qmp(qts, "{ 'execute': 'query-machines' }");
1178 g_assert(response);
1179 list = qdict_get_qlist(response, "return");
1180 g_assert(list);
1182 machines = g_new(struct MachInfo, qlist_size(list) + 1);
1184 for (p = qlist_first(list), idx = 0; p; p = qlist_next(p), idx++) {
1185 minfo = qobject_to(QDict, qlist_entry_obj(p));
1186 g_assert(minfo);
1188 qobj = qdict_get(minfo, "name");
1189 g_assert(qobj);
1190 qstr = qobject_to(QString, qobj);
1191 g_assert(qstr);
1192 machines[idx].name = g_strdup(qstring_get_str(qstr));
1194 qobj = qdict_get(minfo, "alias");
1195 if (qobj) { /* The alias is optional */
1196 qstr = qobject_to(QString, qobj);
1197 g_assert(qstr);
1198 machines[idx].alias = g_strdup(qstring_get_str(qstr));
1199 } else {
1200 machines[idx].alias = NULL;
1204 qtest_quit(qts);
1205 qobject_unref(response);
1207 memset(&machines[idx], 0, sizeof(struct MachInfo)); /* Terminating entry */
1208 return machines;
1211 void qtest_cb_for_every_machine(void (*cb)(const char *machine),
1212 bool skip_old_versioned)
1214 struct MachInfo *machines;
1215 int i;
1217 machines = qtest_get_machines();
1219 for (i = 0; machines[i].name != NULL; i++) {
1220 /* Ignore machines that cannot be used for qtests */
1221 if (!strncmp("xenfv", machines[i].name, 5) ||
1222 g_str_equal("xenpv", machines[i].name)) {
1223 continue;
1225 if (!skip_old_versioned ||
1226 !qtest_is_old_versioned_machine(machines[i].name)) {
1227 cb(machines[i].name);
1232 bool qtest_has_machine(const char *machine)
1234 struct MachInfo *machines;
1235 int i;
1237 machines = qtest_get_machines();
1239 for (i = 0; machines[i].name != NULL; i++) {
1240 if (g_str_equal(machine, machines[i].name) ||
1241 (machines[i].alias && g_str_equal(machine, machines[i].alias))) {
1242 return true;
1246 return false;
1249 bool qtest_has_device(const char *device)
1251 static QList *list;
1252 const QListEntry *p;
1253 QObject *qobj;
1254 QString *qstr;
1255 QDict *devinfo;
1256 int idx;
1258 if (!list) {
1259 QDict *resp;
1260 QDict *args;
1261 QTestState *qts = qtest_init("-machine none");
1263 args = qdict_new();
1264 qdict_put_bool(args, "abstract", false);
1265 qdict_put_str(args, "implements", "device");
1267 resp = qtest_qmp(qts, "{'execute': 'qom-list-types', 'arguments': %p }",
1268 args);
1269 g_assert(qdict_haskey(resp, "return"));
1270 list = qdict_get_qlist(resp, "return");
1271 qobject_ref(list);
1272 qobject_unref(resp);
1274 qtest_quit(qts);
1277 for (p = qlist_first(list), idx = 0; p; p = qlist_next(p), idx++) {
1278 devinfo = qobject_to(QDict, qlist_entry_obj(p));
1279 g_assert(devinfo);
1281 qobj = qdict_get(devinfo, "name");
1282 g_assert(qobj);
1283 qstr = qobject_to(QString, qobj);
1284 g_assert(qstr);
1285 if (g_str_equal(qstring_get_str(qstr), device)) {
1286 return true;
1290 return false;
1294 * Generic hot-plugging test via the device_add QMP commands.
1296 void qtest_qmp_device_add_qdict(QTestState *qts, const char *drv,
1297 const QDict *arguments)
1299 QDict *resp;
1300 QDict *args = arguments ? qdict_clone_shallow(arguments) : qdict_new();
1302 g_assert(!qdict_haskey(args, "driver"));
1303 qdict_put_str(args, "driver", drv);
1304 resp = qtest_qmp(qts, "{'execute': 'device_add', 'arguments': %p}", args);
1305 g_assert(resp);
1306 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1307 g_assert(!qdict_haskey(resp, "error"));
1308 qobject_unref(resp);
1311 void qtest_qmp_device_add(QTestState *qts, const char *driver, const char *id,
1312 const char *fmt, ...)
1314 QDict *args;
1315 va_list ap;
1317 va_start(ap, fmt);
1318 args = qdict_from_vjsonf_nofail(fmt, ap);
1319 va_end(ap);
1321 g_assert(!qdict_haskey(args, "id"));
1322 qdict_put_str(args, "id", id);
1324 qtest_qmp_device_add_qdict(qts, driver, args);
1325 qobject_unref(args);
1328 #ifndef _WIN32
1329 void qtest_qmp_add_client(QTestState *qts, const char *protocol, int fd)
1331 QDict *resp;
1333 resp = qtest_qmp_fds(qts, &fd, 1, "{'execute': 'getfd',"
1334 "'arguments': {'fdname': 'fdname'}}");
1335 g_assert(resp);
1336 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1337 g_assert(!qdict_haskey(resp, "error"));
1338 qobject_unref(resp);
1340 resp = qtest_qmp(
1341 qts, "{'execute': 'add_client',"
1342 "'arguments': {'protocol': %s, 'fdname': 'fdname'}}", protocol);
1343 g_assert(resp);
1344 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1345 g_assert(!qdict_haskey(resp, "error"));
1346 qobject_unref(resp);
1348 #endif
1351 * Generic hot-unplugging test via the device_del QMP command.
1352 * Device deletion will get one response and one event. For example:
1354 * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1356 * will get this one:
1358 * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1359 * "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1360 * "path": "/machine/peripheral/scsi-hd"}}
1362 * and this one:
1364 * {"return": {}}
1366 void qtest_qmp_device_del_send(QTestState *qts, const char *id)
1368 QDict *rsp = qtest_qmp(qts, "{'execute': 'device_del', "
1369 "'arguments': {'id': %s}}", id);
1370 g_assert(rsp);
1371 g_assert(qdict_haskey(rsp, "return"));
1372 g_assert(!qdict_haskey(rsp, "error"));
1373 qobject_unref(rsp);
1376 void qtest_qmp_device_del(QTestState *qts, const char *id)
1378 qtest_qmp_device_del_send(qts, id);
1379 qtest_qmp_eventwait(qts, "DEVICE_DELETED");
1382 static void qtest_client_set_tx_handler(QTestState *s,
1383 QTestSendFn send)
1385 s->ops.send = send;
1387 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv)
1389 s->ops.recv_line = recv;
1391 /* A type-safe wrapper for s->send() */
1392 static void send_wrapper(QTestState *s, const char *buf)
1394 s->ops.external_send(s, buf);
1397 static GString *qtest_client_inproc_recv_line(QTestState *s)
1399 GString *line;
1400 size_t offset;
1401 char *eol;
1403 eol = strchr(s->rx->str, '\n');
1404 offset = eol - s->rx->str;
1405 line = g_string_new_len(s->rx->str, offset);
1406 g_string_erase(s->rx, 0, offset + 1);
1407 return line;
1410 QTestState *qtest_inproc_init(QTestState **s, bool log, const char* arch,
1411 void (*send)(void*, const char*))
1413 QTestState *qts;
1414 qts = g_new0(QTestState, 1);
1415 qts->pending_events = NULL;
1416 *s = qts; /* Expose qts early on, since the query endianness relies on it */
1417 qts->wstatus = 0;
1418 for (int i = 0; i < MAX_IRQ; i++) {
1419 qts->irq_level[i] = false;
1422 qtest_client_set_rx_handler(qts, qtest_client_inproc_recv_line);
1424 /* send() may not have a matching protoype, so use a type-safe wrapper */
1425 qts->ops.external_send = send;
1426 qtest_client_set_tx_handler(qts, send_wrapper);
1428 qts->big_endian = qtest_query_target_endianness(qts);
1431 * Set a dummy path for QTEST_QEMU_BINARY. Doesn't need to exist, but this
1432 * way, qtest_get_arch works for inproc qtest.
1434 gchar *bin_path = g_strconcat("/qemu-system-", arch, NULL);
1435 g_setenv("QTEST_QEMU_BINARY", bin_path, 0);
1436 g_free(bin_path);
1438 return qts;
1441 void qtest_client_inproc_recv(void *opaque, const char *str)
1443 QTestState *qts = *(QTestState **)opaque;
1445 if (!qts->rx) {
1446 qts->rx = g_string_new(NULL);
1448 g_string_append(qts->rx, str);
1449 return;
1452 void qtest_qom_set_bool(QTestState *s, const char *path, const char *property,
1453 bool value)
1455 QDict *r;
1457 r = qtest_qmp(s, "{ 'execute': 'qom-set', 'arguments': "
1458 "{ 'path': %s, 'property': %s, 'value': %i } }",
1459 path, property, value);
1460 qobject_unref(r);
1463 bool qtest_qom_get_bool(QTestState *s, const char *path, const char *property)
1465 QDict *r;
1466 bool b;
1468 r = qtest_qmp(s, "{ 'execute': 'qom-get', 'arguments': "
1469 "{ 'path': %s, 'property': %s } }", path, property);
1470 b = qdict_get_bool(r, "return");
1471 qobject_unref(r);
1473 return b;