iotests: 169: add cases for source vm resuming
[qemu/ar7.git] / tests / libqtest.c
blob44ce118cfcb86f831fa6a89009903d4acabb73b0
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>
23 #include "libqtest.h"
24 #include "qemu-common.h"
25 #include "qemu/cutils.h"
26 #include "qapi/error.h"
27 #include "qapi/qmp/json-parser.h"
28 #include "qapi/qmp/qdict.h"
29 #include "qapi/qmp/qjson.h"
30 #include "qapi/qmp/qlist.h"
31 #include "qapi/qmp/qstring.h"
33 #define MAX_IRQ 256
34 #define SOCKET_TIMEOUT 50
36 QTestState *global_qtest;
38 struct QTestState
40 int fd;
41 int qmp_fd;
42 bool irq_level[MAX_IRQ];
43 GString *rx;
44 pid_t qemu_pid; /* our child QEMU process */
45 bool big_endian;
48 static GHookList abrt_hooks;
49 static struct sigaction sigact_old;
51 static int qtest_query_target_endianness(QTestState *s);
53 static int init_socket(const char *socket_path)
55 struct sockaddr_un addr;
56 int sock;
57 int ret;
59 sock = socket(PF_UNIX, SOCK_STREAM, 0);
60 g_assert_cmpint(sock, !=, -1);
62 addr.sun_family = AF_UNIX;
63 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
64 qemu_set_cloexec(sock);
66 do {
67 ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
68 } while (ret == -1 && errno == EINTR);
69 g_assert_cmpint(ret, !=, -1);
70 ret = listen(sock, 1);
71 g_assert_cmpint(ret, !=, -1);
73 return sock;
76 static int socket_accept(int sock)
78 struct sockaddr_un addr;
79 socklen_t addrlen;
80 int ret;
81 struct timeval timeout = { .tv_sec = SOCKET_TIMEOUT,
82 .tv_usec = 0 };
84 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *)&timeout,
85 sizeof(timeout));
87 do {
88 addrlen = sizeof(addr);
89 ret = accept(sock, (struct sockaddr *)&addr, &addrlen);
90 } while (ret == -1 && errno == EINTR);
91 if (ret == -1) {
92 fprintf(stderr, "%s failed: %s\n", __func__, strerror(errno));
94 close(sock);
96 return ret;
99 static void kill_qemu(QTestState *s)
101 if (s->qemu_pid != -1) {
102 int wstatus = 0;
103 pid_t pid;
105 kill(s->qemu_pid, SIGTERM);
106 TFR(pid = waitpid(s->qemu_pid, &wstatus, 0));
108 assert(pid == s->qemu_pid);
110 * We expect qemu to exit with status 0; anything else is
111 * fishy and should be logged with as much detail as possible.
113 if (wstatus) {
114 if (WIFEXITED(wstatus)) {
115 fprintf(stderr, "%s:%d: kill_qemu() tried to terminate QEMU "
116 "process but encountered exit status %d\n",
117 __FILE__, __LINE__, WEXITSTATUS(wstatus));
118 } else if (WIFSIGNALED(wstatus)) {
119 int sig = WTERMSIG(wstatus);
120 const char *signame = strsignal(sig) ?: "unknown ???";
121 const char *dump = WCOREDUMP(wstatus) ? " (core dumped)" : "";
123 fprintf(stderr, "%s:%d: kill_qemu() detected QEMU death "
124 "from signal %d (%s)%s\n",
125 __FILE__, __LINE__, sig, signame, dump);
127 abort();
132 static void kill_qemu_hook_func(void *s)
134 kill_qemu(s);
137 static void sigabrt_handler(int signo)
139 g_hook_list_invoke(&abrt_hooks, FALSE);
142 static void setup_sigabrt_handler(void)
144 struct sigaction sigact;
146 /* Catch SIGABRT to clean up on g_assert() failure */
147 sigact = (struct sigaction){
148 .sa_handler = sigabrt_handler,
149 .sa_flags = SA_RESETHAND,
151 sigemptyset(&sigact.sa_mask);
152 sigaction(SIGABRT, &sigact, &sigact_old);
155 static void cleanup_sigabrt_handler(void)
157 sigaction(SIGABRT, &sigact_old, NULL);
160 void qtest_add_abrt_handler(GHookFunc fn, const void *data)
162 GHook *hook;
164 /* Only install SIGABRT handler once */
165 if (!abrt_hooks.is_setup) {
166 g_hook_list_init(&abrt_hooks, sizeof(GHook));
168 setup_sigabrt_handler();
170 hook = g_hook_alloc(&abrt_hooks);
171 hook->func = fn;
172 hook->data = (void *)data;
174 g_hook_prepend(&abrt_hooks, hook);
177 static const char *qtest_qemu_binary(void)
179 const char *qemu_bin;
181 qemu_bin = getenv("QTEST_QEMU_BINARY");
182 if (!qemu_bin) {
183 fprintf(stderr, "Environment variable QTEST_QEMU_BINARY required\n");
184 exit(1);
187 return qemu_bin;
190 QTestState *qtest_init_without_qmp_handshake(bool use_oob,
191 const char *extra_args)
193 QTestState *s;
194 int sock, qmpsock, i;
195 gchar *socket_path;
196 gchar *qmp_socket_path;
197 gchar *command;
198 const char *qemu_binary = qtest_qemu_binary();
200 s = g_new(QTestState, 1);
202 socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
203 qmp_socket_path = g_strdup_printf("/tmp/qtest-%d.qmp", getpid());
205 /* It's possible that if an earlier test run crashed it might
206 * have left a stale unix socket lying around. Delete any
207 * stale old socket to avoid spurious test failures with
208 * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1)
210 unlink(socket_path);
211 unlink(qmp_socket_path);
213 sock = init_socket(socket_path);
214 qmpsock = init_socket(qmp_socket_path);
216 qtest_add_abrt_handler(kill_qemu_hook_func, s);
218 s->qemu_pid = fork();
219 if (s->qemu_pid == 0) {
220 setenv("QEMU_AUDIO_DRV", "none", true);
221 command = g_strdup_printf("exec %s "
222 "-qtest unix:%s,nowait "
223 "-qtest-log %s "
224 "-chardev socket,path=%s,nowait,id=char0 "
225 "-mon chardev=char0,mode=control%s "
226 "-machine accel=qtest "
227 "-display none "
228 "%s", qemu_binary, socket_path,
229 getenv("QTEST_LOG") ? "/dev/fd/2" : "/dev/null",
230 qmp_socket_path, use_oob ? ",x-oob=on" : "",
231 extra_args ?: "");
232 execlp("/bin/sh", "sh", "-c", command, NULL);
233 exit(1);
236 s->fd = socket_accept(sock);
237 if (s->fd >= 0) {
238 s->qmp_fd = socket_accept(qmpsock);
240 unlink(socket_path);
241 unlink(qmp_socket_path);
242 g_free(socket_path);
243 g_free(qmp_socket_path);
245 g_assert(s->fd >= 0 && s->qmp_fd >= 0);
247 s->rx = g_string_new("");
248 for (i = 0; i < MAX_IRQ; i++) {
249 s->irq_level[i] = false;
252 if (getenv("QTEST_STOP")) {
253 kill(s->qemu_pid, SIGSTOP);
256 /* ask endianness of the target */
258 s->big_endian = qtest_query_target_endianness(s);
260 return s;
263 QTestState *qtest_init(const char *extra_args)
265 QTestState *s = qtest_init_without_qmp_handshake(false, extra_args);
266 QDict *greeting;
268 /* Read the QMP greeting and then do the handshake */
269 greeting = qtest_qmp_receive(s);
270 qobject_unref(greeting);
271 qobject_unref(qtest_qmp(s, "{ 'execute': 'qmp_capabilities' }"));
273 return s;
276 QTestState *qtest_vinitf(const char *fmt, va_list ap)
278 char *args = g_strdup_vprintf(fmt, ap);
279 QTestState *s;
281 s = qtest_init(args);
282 g_free(args);
283 return s;
286 QTestState *qtest_initf(const char *fmt, ...)
288 va_list ap;
289 QTestState *s;
291 va_start(ap, fmt);
292 s = qtest_vinitf(fmt, ap);
293 va_end(ap);
294 return s;
297 void qtest_quit(QTestState *s)
299 g_hook_destroy_link(&abrt_hooks, g_hook_find_data(&abrt_hooks, TRUE, s));
301 /* Uninstall SIGABRT handler on last instance */
302 cleanup_sigabrt_handler();
304 kill_qemu(s);
305 close(s->fd);
306 close(s->qmp_fd);
307 g_string_free(s->rx, true);
308 g_free(s);
311 static void socket_send(int fd, const char *buf, size_t size)
313 size_t offset;
315 offset = 0;
316 while (offset < size) {
317 ssize_t len;
319 len = write(fd, buf + offset, size - offset);
320 if (len == -1 && errno == EINTR) {
321 continue;
324 g_assert_cmpint(len, >, 0);
326 offset += len;
330 static void socket_sendf(int fd, const char *fmt, va_list ap)
332 gchar *str = g_strdup_vprintf(fmt, ap);
333 size_t size = strlen(str);
335 socket_send(fd, str, size);
336 g_free(str);
339 static void GCC_FMT_ATTR(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...)
341 va_list ap;
343 va_start(ap, fmt);
344 socket_sendf(s->fd, fmt, ap);
345 va_end(ap);
348 static GString *qtest_recv_line(QTestState *s)
350 GString *line;
351 size_t offset;
352 char *eol;
354 while ((eol = strchr(s->rx->str, '\n')) == NULL) {
355 ssize_t len;
356 char buffer[1024];
358 len = read(s->fd, buffer, sizeof(buffer));
359 if (len == -1 && errno == EINTR) {
360 continue;
363 if (len == -1 || len == 0) {
364 fprintf(stderr, "Broken pipe\n");
365 abort();
368 g_string_append_len(s->rx, buffer, len);
371 offset = eol - s->rx->str;
372 line = g_string_new_len(s->rx->str, offset);
373 g_string_erase(s->rx, 0, offset + 1);
375 return line;
378 static gchar **qtest_rsp(QTestState *s, int expected_args)
380 GString *line;
381 gchar **words;
382 int i;
384 redo:
385 line = qtest_recv_line(s);
386 words = g_strsplit(line->str, " ", 0);
387 g_string_free(line, TRUE);
389 if (strcmp(words[0], "IRQ") == 0) {
390 long irq;
391 int ret;
393 g_assert(words[1] != NULL);
394 g_assert(words[2] != NULL);
396 ret = qemu_strtol(words[2], NULL, 0, &irq);
397 g_assert(!ret);
398 g_assert_cmpint(irq, >=, 0);
399 g_assert_cmpint(irq, <, MAX_IRQ);
401 if (strcmp(words[1], "raise") == 0) {
402 s->irq_level[irq] = true;
403 } else {
404 s->irq_level[irq] = false;
407 g_strfreev(words);
408 goto redo;
411 g_assert(words[0] != NULL);
412 g_assert_cmpstr(words[0], ==, "OK");
414 if (expected_args) {
415 for (i = 0; i < expected_args; i++) {
416 g_assert(words[i] != NULL);
418 } else {
419 g_strfreev(words);
422 return words;
425 static int qtest_query_target_endianness(QTestState *s)
427 gchar **args;
428 int big_endian;
430 qtest_sendf(s, "endianness\n");
431 args = qtest_rsp(s, 1);
432 g_assert(strcmp(args[1], "big") == 0 || strcmp(args[1], "little") == 0);
433 big_endian = strcmp(args[1], "big") == 0;
434 g_strfreev(args);
436 return big_endian;
439 typedef struct {
440 JSONMessageParser parser;
441 QDict *response;
442 } QMPResponseParser;
444 static void qmp_response(void *opaque, QObject *obj, Error *err)
446 QMPResponseParser *qmp = opaque;
448 assert(!obj != !err);
450 if (err) {
451 error_prepend(&err, "QMP JSON response parsing failed: ");
452 error_report_err(err);
453 abort();
456 g_assert(!qmp->response);
457 qmp->response = qobject_to(QDict, obj);
458 g_assert(qmp->response);
461 QDict *qmp_fd_receive(int fd)
463 QMPResponseParser qmp;
464 bool log = getenv("QTEST_LOG") != NULL;
466 qmp.response = NULL;
467 json_message_parser_init(&qmp.parser, qmp_response, &qmp, NULL);
468 while (!qmp.response) {
469 ssize_t len;
470 char c;
472 len = read(fd, &c, 1);
473 if (len == -1 && errno == EINTR) {
474 continue;
477 if (len == -1 || len == 0) {
478 fprintf(stderr, "Broken pipe\n");
479 abort();
482 if (log) {
483 len = write(2, &c, 1);
485 json_message_parser_feed(&qmp.parser, &c, 1);
487 json_message_parser_destroy(&qmp.parser);
489 return qmp.response;
492 QDict *qtest_qmp_receive(QTestState *s)
494 return qmp_fd_receive(s->qmp_fd);
498 * Allow users to send a message without waiting for the reply,
499 * in the case that they choose to discard all replies up until
500 * a particular EVENT is received.
502 void qmp_fd_vsend(int fd, const char *fmt, va_list ap)
504 QObject *qobj;
506 /* Going through qobject ensures we escape strings properly */
507 qobj = qobject_from_vjsonf_nofail(fmt, ap);
509 /* No need to send anything for an empty QObject. */
510 if (qobj) {
511 int log = getenv("QTEST_LOG") != NULL;
512 QString *qstr = qobject_to_json(qobj);
513 const char *str;
516 * BUG: QMP doesn't react to input until it sees a newline, an
517 * object, or an array. Work-around: give it a newline.
519 qstring_append_chr(qstr, '\n');
520 str = qstring_get_str(qstr);
522 if (log) {
523 fprintf(stderr, "%s", str);
525 /* Send QMP request */
526 socket_send(fd, str, qstring_get_length(qstr));
528 qobject_unref(qstr);
529 qobject_unref(qobj);
533 void qtest_qmp_vsend(QTestState *s, const char *fmt, va_list ap)
535 qmp_fd_vsend(s->qmp_fd, fmt, ap);
538 QDict *qmp_fdv(int fd, const char *fmt, va_list ap)
540 qmp_fd_vsend(fd, fmt, ap);
542 return qmp_fd_receive(fd);
545 QDict *qtest_vqmp(QTestState *s, const char *fmt, va_list ap)
547 qtest_qmp_vsend(s, fmt, ap);
549 /* Receive reply */
550 return qtest_qmp_receive(s);
553 QDict *qmp_fd(int fd, const char *fmt, ...)
555 va_list ap;
556 QDict *response;
558 va_start(ap, fmt);
559 response = qmp_fdv(fd, fmt, ap);
560 va_end(ap);
561 return response;
564 void qmp_fd_send(int fd, const char *fmt, ...)
566 va_list ap;
568 va_start(ap, fmt);
569 qmp_fd_vsend(fd, fmt, ap);
570 va_end(ap);
573 QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
575 va_list ap;
576 QDict *response;
578 va_start(ap, fmt);
579 response = qtest_vqmp(s, fmt, ap);
580 va_end(ap);
581 return response;
584 void qtest_qmp_send(QTestState *s, const char *fmt, ...)
586 va_list ap;
588 va_start(ap, fmt);
589 qtest_qmp_vsend(s, fmt, ap);
590 va_end(ap);
593 void qmp_fd_vsend_raw(int fd, const char *fmt, va_list ap)
595 bool log = getenv("QTEST_LOG") != NULL;
596 char *str = g_strdup_vprintf(fmt, ap);
598 if (log) {
599 fprintf(stderr, "%s", str);
601 socket_send(fd, str, strlen(str));
602 g_free(str);
605 void qmp_fd_send_raw(int fd, const char *fmt, ...)
607 va_list ap;
609 va_start(ap, fmt);
610 qmp_fd_vsend_raw(fd, fmt, ap);
611 va_end(ap);
614 void qtest_qmp_send_raw(QTestState *s, const char *fmt, ...)
616 va_list ap;
618 va_start(ap, fmt);
619 qmp_fd_vsend_raw(s->qmp_fd, fmt, ap);
620 va_end(ap);
623 QDict *qtest_qmp_eventwait_ref(QTestState *s, const char *event)
625 QDict *response;
627 for (;;) {
628 response = qtest_qmp_receive(s);
629 if ((qdict_haskey(response, "event")) &&
630 (strcmp(qdict_get_str(response, "event"), event) == 0)) {
631 return response;
633 qobject_unref(response);
637 void qtest_qmp_eventwait(QTestState *s, const char *event)
639 QDict *response;
641 response = qtest_qmp_eventwait_ref(s, event);
642 qobject_unref(response);
645 char *qtest_vhmp(QTestState *s, const char *fmt, va_list ap)
647 char *cmd;
648 QDict *resp;
649 char *ret;
651 cmd = g_strdup_vprintf(fmt, ap);
652 resp = qtest_qmp(s, "{'execute': 'human-monitor-command',"
653 " 'arguments': {'command-line': %s}}",
654 cmd);
655 ret = g_strdup(qdict_get_try_str(resp, "return"));
656 while (ret == NULL && qdict_get_try_str(resp, "event")) {
657 /* Ignore asynchronous QMP events */
658 qobject_unref(resp);
659 resp = qtest_qmp_receive(s);
660 ret = g_strdup(qdict_get_try_str(resp, "return"));
662 g_assert(ret);
663 qobject_unref(resp);
664 g_free(cmd);
665 return ret;
668 char *qtest_hmp(QTestState *s, const char *fmt, ...)
670 va_list ap;
671 char *ret;
673 va_start(ap, fmt);
674 ret = qtest_vhmp(s, fmt, ap);
675 va_end(ap);
676 return ret;
679 const char *qtest_get_arch(void)
681 const char *qemu = qtest_qemu_binary();
682 const char *end = strrchr(qemu, '/');
684 return end + strlen("/qemu-system-");
687 bool qtest_get_irq(QTestState *s, int num)
689 /* dummy operation in order to make sure irq is up to date */
690 qtest_inb(s, 0);
692 return s->irq_level[num];
695 static int64_t qtest_clock_rsp(QTestState *s)
697 gchar **words;
698 int64_t clock;
699 words = qtest_rsp(s, 2);
700 clock = g_ascii_strtoll(words[1], NULL, 0);
701 g_strfreev(words);
702 return clock;
705 int64_t qtest_clock_step_next(QTestState *s)
707 qtest_sendf(s, "clock_step\n");
708 return qtest_clock_rsp(s);
711 int64_t qtest_clock_step(QTestState *s, int64_t step)
713 qtest_sendf(s, "clock_step %"PRIi64"\n", step);
714 return qtest_clock_rsp(s);
717 int64_t qtest_clock_set(QTestState *s, int64_t val)
719 qtest_sendf(s, "clock_set %"PRIi64"\n", val);
720 return qtest_clock_rsp(s);
723 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
725 qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
726 qtest_rsp(s, 0);
729 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
731 qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
732 qtest_rsp(s, 0);
735 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
737 qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
738 qtest_rsp(s, 0);
741 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
743 qtest_out(s, "outb", addr, value);
746 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
748 qtest_out(s, "outw", addr, value);
751 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
753 qtest_out(s, "outl", addr, value);
756 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
758 gchar **args;
759 int ret;
760 unsigned long value;
762 qtest_sendf(s, "%s 0x%x\n", cmd, addr);
763 args = qtest_rsp(s, 2);
764 ret = qemu_strtoul(args[1], NULL, 0, &value);
765 g_assert(!ret && value <= UINT32_MAX);
766 g_strfreev(args);
768 return value;
771 uint8_t qtest_inb(QTestState *s, uint16_t addr)
773 return qtest_in(s, "inb", addr);
776 uint16_t qtest_inw(QTestState *s, uint16_t addr)
778 return qtest_in(s, "inw", addr);
781 uint32_t qtest_inl(QTestState *s, uint16_t addr)
783 return qtest_in(s, "inl", addr);
786 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
787 uint64_t value)
789 qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
790 qtest_rsp(s, 0);
793 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
795 qtest_write(s, "writeb", addr, value);
798 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
800 qtest_write(s, "writew", addr, value);
803 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
805 qtest_write(s, "writel", addr, value);
808 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
810 qtest_write(s, "writeq", addr, value);
813 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
815 gchar **args;
816 int ret;
817 uint64_t value;
819 qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
820 args = qtest_rsp(s, 2);
821 ret = qemu_strtou64(args[1], NULL, 0, &value);
822 g_assert(!ret);
823 g_strfreev(args);
825 return value;
828 uint8_t qtest_readb(QTestState *s, uint64_t addr)
830 return qtest_read(s, "readb", addr);
833 uint16_t qtest_readw(QTestState *s, uint64_t addr)
835 return qtest_read(s, "readw", addr);
838 uint32_t qtest_readl(QTestState *s, uint64_t addr)
840 return qtest_read(s, "readl", addr);
843 uint64_t qtest_readq(QTestState *s, uint64_t addr)
845 return qtest_read(s, "readq", addr);
848 static int hex2nib(char ch)
850 if (ch >= '0' && ch <= '9') {
851 return ch - '0';
852 } else if (ch >= 'a' && ch <= 'f') {
853 return 10 + (ch - 'a');
854 } else if (ch >= 'A' && ch <= 'F') {
855 return 10 + (ch - 'a');
856 } else {
857 return -1;
861 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
863 uint8_t *ptr = data;
864 gchar **args;
865 size_t i;
867 if (!size) {
868 return;
871 qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
872 args = qtest_rsp(s, 2);
874 for (i = 0; i < size; i++) {
875 ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
876 ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
879 g_strfreev(args);
882 uint64_t qtest_rtas_call(QTestState *s, const char *name,
883 uint32_t nargs, uint64_t args,
884 uint32_t nret, uint64_t ret)
886 qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n",
887 name, nargs, args, nret, ret);
888 qtest_rsp(s, 0);
889 return 0;
892 void qtest_add_func(const char *str, void (*fn)(void))
894 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
895 g_test_add_func(path, fn);
896 g_free(path);
899 void qtest_add_data_func_full(const char *str, void *data,
900 void (*fn)(const void *),
901 GDestroyNotify data_free_func)
903 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
904 g_test_add_data_func_full(path, data, fn, data_free_func);
905 g_free(path);
908 void qtest_add_data_func(const char *str, const void *data,
909 void (*fn)(const void *))
911 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
912 g_test_add_data_func(path, data, fn);
913 g_free(path);
916 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
918 gchar *bdata;
920 bdata = g_base64_encode(data, size);
921 qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
922 socket_send(s->fd, bdata, strlen(bdata));
923 socket_send(s->fd, "\n", 1);
924 qtest_rsp(s, 0);
925 g_free(bdata);
928 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
930 gchar **args;
931 size_t len;
933 qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
934 args = qtest_rsp(s, 2);
936 g_base64_decode_inplace(args[1], &len);
937 if (size != len) {
938 fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
939 size, len);
940 len = MIN(len, size);
943 memcpy(data, args[1], len);
944 g_strfreev(args);
947 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
949 const uint8_t *ptr = data;
950 size_t i;
951 char *enc;
953 if (!size) {
954 return;
957 enc = g_malloc(2 * size + 1);
959 for (i = 0; i < size; i++) {
960 sprintf(&enc[i * 2], "%02x", ptr[i]);
963 qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
964 qtest_rsp(s, 0);
965 g_free(enc);
968 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
970 qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
971 qtest_rsp(s, 0);
974 QDict *qmp(const char *fmt, ...)
976 va_list ap;
977 QDict *response;
979 va_start(ap, fmt);
980 response = qtest_vqmp(global_qtest, fmt, ap);
981 va_end(ap);
982 return response;
985 void qmp_send(const char *fmt, ...)
987 va_list ap;
989 va_start(ap, fmt);
990 qtest_qmp_vsend(global_qtest, fmt, ap);
991 va_end(ap);
994 char *hmp(const char *fmt, ...)
996 va_list ap;
997 char *ret;
999 va_start(ap, fmt);
1000 ret = qtest_vhmp(global_qtest, fmt, ap);
1001 va_end(ap);
1002 return ret;
1005 bool qtest_big_endian(QTestState *s)
1007 return s->big_endian;
1010 static bool qtest_check_machine_version(const char *mname, const char *basename,
1011 int major, int minor)
1013 char *newname;
1014 bool is_equal;
1016 newname = g_strdup_printf("%s-%i.%i", basename, major, minor);
1017 is_equal = g_str_equal(mname, newname);
1018 g_free(newname);
1020 return is_equal;
1023 static bool qtest_is_old_versioned_machine(const char *mname)
1025 const char *dash = strrchr(mname, '-');
1026 const char *dot = strrchr(mname, '.');
1027 const char *chr;
1028 char *bname;
1029 const int major = QEMU_VERSION_MAJOR;
1030 const int minor = QEMU_VERSION_MINOR;
1031 bool res = false;
1033 if (dash && dot && dot > dash) {
1034 for (chr = dash + 1; *chr; chr++) {
1035 if (!qemu_isdigit(*chr) && *chr != '.') {
1036 return false;
1040 * Now check if it is one of the latest versions. Check major + 1
1041 * and minor + 1 versions as well, since they might already exist
1042 * in the development branch.
1044 bname = g_strdup(mname);
1045 bname[dash - mname] = 0;
1046 res = !qtest_check_machine_version(mname, bname, major + 1, 0) &&
1047 !qtest_check_machine_version(mname, bname, major, minor + 1) &&
1048 !qtest_check_machine_version(mname, bname, major, minor);
1049 g_free(bname);
1052 return res;
1055 void qtest_cb_for_every_machine(void (*cb)(const char *machine),
1056 bool skip_old_versioned)
1058 QDict *response, *minfo;
1059 QList *list;
1060 const QListEntry *p;
1061 QObject *qobj;
1062 QString *qstr;
1063 const char *mname;
1065 qtest_start("-machine none");
1066 response = qmp("{ 'execute': 'query-machines' }");
1067 g_assert(response);
1068 list = qdict_get_qlist(response, "return");
1069 g_assert(list);
1071 for (p = qlist_first(list); p; p = qlist_next(p)) {
1072 minfo = qobject_to(QDict, qlist_entry_obj(p));
1073 g_assert(minfo);
1074 qobj = qdict_get(minfo, "name");
1075 g_assert(qobj);
1076 qstr = qobject_to(QString, qobj);
1077 g_assert(qstr);
1078 mname = qstring_get_str(qstr);
1079 if (!skip_old_versioned || !qtest_is_old_versioned_machine(mname)) {
1080 cb(mname);
1084 qtest_end();
1085 qobject_unref(response);
1088 QDict *qtest_qmp_receive_success(QTestState *s,
1089 void (*event_cb)(void *opaque,
1090 const char *event,
1091 QDict *data),
1092 void *opaque)
1094 QDict *response, *ret, *data;
1095 const char *event;
1097 for (;;) {
1098 response = qtest_qmp_receive(s);
1099 g_assert(!qdict_haskey(response, "error"));
1100 ret = qdict_get_qdict(response, "return");
1101 if (ret) {
1102 break;
1104 event = qdict_get_str(response, "event");
1105 data = qdict_get_qdict(response, "data");
1106 if (event_cb) {
1107 event_cb(opaque, event, data);
1109 qobject_unref(response);
1112 qobject_ref(ret);
1113 qobject_unref(response);
1114 return ret;
1118 * Generic hot-plugging test via the device_add QMP command.
1120 void qtest_qmp_device_add(const char *driver, const char *id,
1121 const char *fmt, ...)
1123 QDict *args, *response;
1124 va_list ap;
1126 va_start(ap, fmt);
1127 args = qdict_from_vjsonf_nofail(fmt, ap);
1128 va_end(ap);
1130 g_assert(!qdict_haskey(args, "driver") && !qdict_haskey(args, "id"));
1131 qdict_put_str(args, "driver", driver);
1132 qdict_put_str(args, "id", id);
1134 response = qmp("{'execute': 'device_add', 'arguments': %p}", args);
1135 g_assert(response);
1136 g_assert(!qdict_haskey(response, "event")); /* We don't expect any events */
1137 g_assert(!qdict_haskey(response, "error"));
1138 qobject_unref(response);
1141 static void device_deleted_cb(void *opaque, const char *name, QDict *data)
1143 bool *got_event = opaque;
1145 g_assert_cmpstr(name, ==, "DEVICE_DELETED");
1146 *got_event = true;
1150 * Generic hot-unplugging test via the device_del QMP command.
1151 * Device deletion will get one response and one event. For example:
1153 * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1155 * will get this one:
1157 * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1158 * "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1159 * "path": "/machine/peripheral/scsi-hd"}}
1161 * and this one:
1163 * {"return": {}}
1165 * But the order of arrival may vary - so we've got to detect both.
1167 void qtest_qmp_device_del(const char *id)
1169 bool got_event = false;
1170 QDict *rsp;
1172 qtest_qmp_send(global_qtest,
1173 "{'execute': 'device_del', 'arguments': {'id': %s}}",
1174 id);
1175 rsp = qtest_qmp_receive_success(global_qtest, device_deleted_cb,
1176 &got_event);
1177 qobject_unref(rsp);
1178 if (!got_event) {
1179 rsp = qmp_receive();
1180 g_assert_cmpstr(qdict_get_try_str(rsp, "event"),
1181 ==, "DEVICE_DELETED");
1182 qobject_unref(rsp);
1186 bool qmp_rsp_is_err(QDict *rsp)
1188 QDict *error = qdict_get_qdict(rsp, "error");
1189 qobject_unref(rsp);
1190 return !!error;
1193 void qmp_assert_error_class(QDict *rsp, const char *class)
1195 QDict *error = qdict_get_qdict(rsp, "error");
1197 g_assert_cmpstr(qdict_get_try_str(error, "class"), ==, class);
1198 g_assert_nonnull(qdict_get_try_str(error, "desc"));
1199 g_assert(!qdict_haskey(rsp, "return"));
1201 qobject_unref(rsp);