xen: duplicate xen_disk.c as basis of dataplane/xen-block.c
[qemu.git] / tests / libqtest.c
blob55750dd68de9b7eb91074fae69ad74287e9023fb
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 pid_t qemu_pid; /* our child QEMU process */
43 int wstatus;
44 bool big_endian;
45 bool irq_level[MAX_IRQ];
46 GString *rx;
49 static GHookList abrt_hooks;
50 static struct sigaction sigact_old;
52 static int qtest_query_target_endianness(QTestState *s);
54 static int init_socket(const char *socket_path)
56 struct sockaddr_un addr;
57 int sock;
58 int ret;
60 sock = socket(PF_UNIX, SOCK_STREAM, 0);
61 g_assert_cmpint(sock, !=, -1);
63 addr.sun_family = AF_UNIX;
64 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
65 qemu_set_cloexec(sock);
67 do {
68 ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
69 } while (ret == -1 && errno == EINTR);
70 g_assert_cmpint(ret, !=, -1);
71 ret = listen(sock, 1);
72 g_assert_cmpint(ret, !=, -1);
74 return sock;
77 static int socket_accept(int sock)
79 struct sockaddr_un addr;
80 socklen_t addrlen;
81 int ret;
82 struct timeval timeout = { .tv_sec = SOCKET_TIMEOUT,
83 .tv_usec = 0 };
85 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *)&timeout,
86 sizeof(timeout));
88 do {
89 addrlen = sizeof(addr);
90 ret = accept(sock, (struct sockaddr *)&addr, &addrlen);
91 } while (ret == -1 && errno == EINTR);
92 if (ret == -1) {
93 fprintf(stderr, "%s failed: %s\n", __func__, strerror(errno));
95 close(sock);
97 return ret;
100 bool qtest_probe_child(QTestState *s)
102 pid_t pid = s->qemu_pid;
104 if (pid != -1) {
105 pid = waitpid(pid, &s->wstatus, WNOHANG);
106 if (pid == 0) {
107 return true;
109 s->qemu_pid = -1;
111 return false;
114 static void kill_qemu(QTestState *s)
116 pid_t pid = s->qemu_pid;
117 int wstatus;
119 /* Skip wait if qtest_probe_child already reaped. */
120 if (pid != -1) {
121 kill(pid, SIGTERM);
122 TFR(pid = waitpid(s->qemu_pid, &s->wstatus, 0));
123 assert(pid == s->qemu_pid);
127 * We expect qemu to exit with status 0; anything else is
128 * fishy and should be logged with as much detail as possible.
130 wstatus = s->wstatus;
131 if (wstatus) {
132 if (WIFEXITED(wstatus)) {
133 fprintf(stderr, "%s:%d: kill_qemu() tried to terminate QEMU "
134 "process but encountered exit status %d\n",
135 __FILE__, __LINE__, WEXITSTATUS(wstatus));
136 } else if (WIFSIGNALED(wstatus)) {
137 int sig = WTERMSIG(wstatus);
138 const char *signame = strsignal(sig) ?: "unknown ???";
139 const char *dump = WCOREDUMP(wstatus) ? " (core dumped)" : "";
141 fprintf(stderr, "%s:%d: kill_qemu() detected QEMU death "
142 "from signal %d (%s)%s\n",
143 __FILE__, __LINE__, sig, signame, dump);
145 abort();
149 static void kill_qemu_hook_func(void *s)
151 kill_qemu(s);
154 static void sigabrt_handler(int signo)
156 g_hook_list_invoke(&abrt_hooks, FALSE);
159 static void setup_sigabrt_handler(void)
161 struct sigaction sigact;
163 /* Catch SIGABRT to clean up on g_assert() failure */
164 sigact = (struct sigaction){
165 .sa_handler = sigabrt_handler,
166 .sa_flags = SA_RESETHAND,
168 sigemptyset(&sigact.sa_mask);
169 sigaction(SIGABRT, &sigact, &sigact_old);
172 static void cleanup_sigabrt_handler(void)
174 sigaction(SIGABRT, &sigact_old, NULL);
177 void qtest_add_abrt_handler(GHookFunc fn, const void *data)
179 GHook *hook;
181 /* Only install SIGABRT handler once */
182 if (!abrt_hooks.is_setup) {
183 g_hook_list_init(&abrt_hooks, sizeof(GHook));
185 setup_sigabrt_handler();
187 hook = g_hook_alloc(&abrt_hooks);
188 hook->func = fn;
189 hook->data = (void *)data;
191 g_hook_prepend(&abrt_hooks, hook);
194 static const char *qtest_qemu_binary(void)
196 const char *qemu_bin;
198 qemu_bin = getenv("QTEST_QEMU_BINARY");
199 if (!qemu_bin) {
200 fprintf(stderr, "Environment variable QTEST_QEMU_BINARY required\n");
201 exit(1);
204 return qemu_bin;
207 QTestState *qtest_init_without_qmp_handshake(const char *extra_args)
209 QTestState *s;
210 int sock, qmpsock, i;
211 gchar *socket_path;
212 gchar *qmp_socket_path;
213 gchar *command;
214 const char *qemu_binary = qtest_qemu_binary();
216 s = g_new(QTestState, 1);
218 socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
219 qmp_socket_path = g_strdup_printf("/tmp/qtest-%d.qmp", getpid());
221 /* It's possible that if an earlier test run crashed it might
222 * have left a stale unix socket lying around. Delete any
223 * stale old socket to avoid spurious test failures with
224 * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1)
226 unlink(socket_path);
227 unlink(qmp_socket_path);
229 sock = init_socket(socket_path);
230 qmpsock = init_socket(qmp_socket_path);
232 qtest_add_abrt_handler(kill_qemu_hook_func, s);
234 command = g_strdup_printf("exec %s "
235 "-qtest unix:%s,nowait "
236 "-qtest-log %s "
237 "-chardev socket,path=%s,nowait,id=char0 "
238 "-mon chardev=char0,mode=control "
239 "-machine accel=qtest "
240 "-display none "
241 "%s", qemu_binary, socket_path,
242 getenv("QTEST_LOG") ? "/dev/fd/2" : "/dev/null",
243 qmp_socket_path,
244 extra_args ?: "");
246 g_test_message("starting QEMU: %s", command);
248 s->wstatus = 0;
249 s->qemu_pid = fork();
250 if (s->qemu_pid == 0) {
251 setenv("QEMU_AUDIO_DRV", "none", true);
252 execlp("/bin/sh", "sh", "-c", command, NULL);
253 exit(1);
256 g_free(command);
257 s->fd = socket_accept(sock);
258 if (s->fd >= 0) {
259 s->qmp_fd = socket_accept(qmpsock);
261 unlink(socket_path);
262 unlink(qmp_socket_path);
263 g_free(socket_path);
264 g_free(qmp_socket_path);
266 g_assert(s->fd >= 0 && s->qmp_fd >= 0);
268 s->rx = g_string_new("");
269 for (i = 0; i < MAX_IRQ; i++) {
270 s->irq_level[i] = false;
273 if (getenv("QTEST_STOP")) {
274 kill(s->qemu_pid, SIGSTOP);
277 /* ask endianness of the target */
279 s->big_endian = qtest_query_target_endianness(s);
281 return s;
284 QTestState *qtest_init(const char *extra_args)
286 QTestState *s = qtest_init_without_qmp_handshake(extra_args);
287 QDict *greeting;
289 /* Read the QMP greeting and then do the handshake */
290 greeting = qtest_qmp_receive(s);
291 qobject_unref(greeting);
292 qobject_unref(qtest_qmp(s, "{ 'execute': 'qmp_capabilities' }"));
294 return s;
297 QTestState *qtest_vinitf(const char *fmt, va_list ap)
299 char *args = g_strdup_vprintf(fmt, ap);
300 QTestState *s;
302 s = qtest_init(args);
303 g_free(args);
304 return s;
307 QTestState *qtest_initf(const char *fmt, ...)
309 va_list ap;
310 QTestState *s;
312 va_start(ap, fmt);
313 s = qtest_vinitf(fmt, ap);
314 va_end(ap);
315 return s;
318 void qtest_quit(QTestState *s)
320 g_hook_destroy_link(&abrt_hooks, g_hook_find_data(&abrt_hooks, TRUE, s));
322 /* Uninstall SIGABRT handler on last instance */
323 cleanup_sigabrt_handler();
325 kill_qemu(s);
326 close(s->fd);
327 close(s->qmp_fd);
328 g_string_free(s->rx, true);
329 g_free(s);
332 static void socket_send(int fd, const char *buf, size_t size)
334 size_t offset;
336 offset = 0;
337 while (offset < size) {
338 ssize_t len;
340 len = write(fd, buf + offset, size - offset);
341 if (len == -1 && errno == EINTR) {
342 continue;
345 g_assert_cmpint(len, >, 0);
347 offset += len;
351 static void socket_sendf(int fd, const char *fmt, va_list ap)
353 gchar *str = g_strdup_vprintf(fmt, ap);
354 size_t size = strlen(str);
356 socket_send(fd, str, size);
357 g_free(str);
360 static void GCC_FMT_ATTR(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...)
362 va_list ap;
364 va_start(ap, fmt);
365 socket_sendf(s->fd, fmt, ap);
366 va_end(ap);
369 static GString *qtest_recv_line(QTestState *s)
371 GString *line;
372 size_t offset;
373 char *eol;
375 while ((eol = strchr(s->rx->str, '\n')) == NULL) {
376 ssize_t len;
377 char buffer[1024];
379 len = read(s->fd, buffer, sizeof(buffer));
380 if (len == -1 && errno == EINTR) {
381 continue;
384 if (len == -1 || len == 0) {
385 fprintf(stderr, "Broken pipe\n");
386 abort();
389 g_string_append_len(s->rx, buffer, len);
392 offset = eol - s->rx->str;
393 line = g_string_new_len(s->rx->str, offset);
394 g_string_erase(s->rx, 0, offset + 1);
396 return line;
399 static gchar **qtest_rsp(QTestState *s, int expected_args)
401 GString *line;
402 gchar **words;
403 int i;
405 redo:
406 line = qtest_recv_line(s);
407 words = g_strsplit(line->str, " ", 0);
408 g_string_free(line, TRUE);
410 if (strcmp(words[0], "IRQ") == 0) {
411 long irq;
412 int ret;
414 g_assert(words[1] != NULL);
415 g_assert(words[2] != NULL);
417 ret = qemu_strtol(words[2], NULL, 0, &irq);
418 g_assert(!ret);
419 g_assert_cmpint(irq, >=, 0);
420 g_assert_cmpint(irq, <, MAX_IRQ);
422 if (strcmp(words[1], "raise") == 0) {
423 s->irq_level[irq] = true;
424 } else {
425 s->irq_level[irq] = false;
428 g_strfreev(words);
429 goto redo;
432 g_assert(words[0] != NULL);
433 g_assert_cmpstr(words[0], ==, "OK");
435 if (expected_args) {
436 for (i = 0; i < expected_args; i++) {
437 g_assert(words[i] != NULL);
439 } else {
440 g_strfreev(words);
443 return words;
446 static int qtest_query_target_endianness(QTestState *s)
448 gchar **args;
449 int big_endian;
451 qtest_sendf(s, "endianness\n");
452 args = qtest_rsp(s, 1);
453 g_assert(strcmp(args[1], "big") == 0 || strcmp(args[1], "little") == 0);
454 big_endian = strcmp(args[1], "big") == 0;
455 g_strfreev(args);
457 return big_endian;
460 typedef struct {
461 JSONMessageParser parser;
462 QDict *response;
463 } QMPResponseParser;
465 static void qmp_response(void *opaque, QObject *obj, Error *err)
467 QMPResponseParser *qmp = opaque;
469 assert(!obj != !err);
471 if (err) {
472 error_prepend(&err, "QMP JSON response parsing failed: ");
473 error_report_err(err);
474 abort();
477 g_assert(!qmp->response);
478 qmp->response = qobject_to(QDict, obj);
479 g_assert(qmp->response);
482 QDict *qmp_fd_receive(int fd)
484 QMPResponseParser qmp;
485 bool log = getenv("QTEST_LOG") != NULL;
487 qmp.response = NULL;
488 json_message_parser_init(&qmp.parser, qmp_response, &qmp, NULL);
489 while (!qmp.response) {
490 ssize_t len;
491 char c;
493 len = read(fd, &c, 1);
494 if (len == -1 && errno == EINTR) {
495 continue;
498 if (len == -1 || len == 0) {
499 fprintf(stderr, "Broken pipe\n");
500 abort();
503 if (log) {
504 len = write(2, &c, 1);
506 json_message_parser_feed(&qmp.parser, &c, 1);
508 json_message_parser_destroy(&qmp.parser);
510 return qmp.response;
513 QDict *qtest_qmp_receive(QTestState *s)
515 return qmp_fd_receive(s->qmp_fd);
519 * Allow users to send a message without waiting for the reply,
520 * in the case that they choose to discard all replies up until
521 * a particular EVENT is received.
523 void qmp_fd_vsend(int fd, const char *fmt, va_list ap)
525 QObject *qobj;
527 /* Going through qobject ensures we escape strings properly */
528 qobj = qobject_from_vjsonf_nofail(fmt, ap);
530 /* No need to send anything for an empty QObject. */
531 if (qobj) {
532 int log = getenv("QTEST_LOG") != NULL;
533 QString *qstr = qobject_to_json(qobj);
534 const char *str;
537 * BUG: QMP doesn't react to input until it sees a newline, an
538 * object, or an array. Work-around: give it a newline.
540 qstring_append_chr(qstr, '\n');
541 str = qstring_get_str(qstr);
543 if (log) {
544 fprintf(stderr, "%s", str);
546 /* Send QMP request */
547 socket_send(fd, str, qstring_get_length(qstr));
549 qobject_unref(qstr);
550 qobject_unref(qobj);
554 void qtest_qmp_vsend(QTestState *s, const char *fmt, va_list ap)
556 qmp_fd_vsend(s->qmp_fd, fmt, ap);
559 QDict *qmp_fdv(int fd, const char *fmt, va_list ap)
561 qmp_fd_vsend(fd, fmt, ap);
563 return qmp_fd_receive(fd);
566 QDict *qtest_vqmp(QTestState *s, const char *fmt, va_list ap)
568 qtest_qmp_vsend(s, fmt, ap);
570 /* Receive reply */
571 return qtest_qmp_receive(s);
574 QDict *qmp_fd(int fd, const char *fmt, ...)
576 va_list ap;
577 QDict *response;
579 va_start(ap, fmt);
580 response = qmp_fdv(fd, fmt, ap);
581 va_end(ap);
582 return response;
585 void qmp_fd_send(int fd, const char *fmt, ...)
587 va_list ap;
589 va_start(ap, fmt);
590 qmp_fd_vsend(fd, fmt, ap);
591 va_end(ap);
594 QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
596 va_list ap;
597 QDict *response;
599 va_start(ap, fmt);
600 response = qtest_vqmp(s, fmt, ap);
601 va_end(ap);
602 return response;
605 void qtest_qmp_send(QTestState *s, const char *fmt, ...)
607 va_list ap;
609 va_start(ap, fmt);
610 qtest_qmp_vsend(s, fmt, ap);
611 va_end(ap);
614 void qmp_fd_vsend_raw(int fd, const char *fmt, va_list ap)
616 bool log = getenv("QTEST_LOG") != NULL;
617 char *str = g_strdup_vprintf(fmt, ap);
619 if (log) {
620 fprintf(stderr, "%s", str);
622 socket_send(fd, str, strlen(str));
623 g_free(str);
626 void qmp_fd_send_raw(int fd, const char *fmt, ...)
628 va_list ap;
630 va_start(ap, fmt);
631 qmp_fd_vsend_raw(fd, fmt, ap);
632 va_end(ap);
635 void qtest_qmp_send_raw(QTestState *s, const char *fmt, ...)
637 va_list ap;
639 va_start(ap, fmt);
640 qmp_fd_vsend_raw(s->qmp_fd, fmt, ap);
641 va_end(ap);
644 QDict *qtest_qmp_eventwait_ref(QTestState *s, const char *event)
646 QDict *response;
648 for (;;) {
649 response = qtest_qmp_receive(s);
650 if ((qdict_haskey(response, "event")) &&
651 (strcmp(qdict_get_str(response, "event"), event) == 0)) {
652 return response;
654 qobject_unref(response);
658 void qtest_qmp_eventwait(QTestState *s, const char *event)
660 QDict *response;
662 response = qtest_qmp_eventwait_ref(s, event);
663 qobject_unref(response);
666 char *qtest_vhmp(QTestState *s, const char *fmt, va_list ap)
668 char *cmd;
669 QDict *resp;
670 char *ret;
672 cmd = g_strdup_vprintf(fmt, ap);
673 resp = qtest_qmp(s, "{'execute': 'human-monitor-command',"
674 " 'arguments': {'command-line': %s}}",
675 cmd);
676 ret = g_strdup(qdict_get_try_str(resp, "return"));
677 while (ret == NULL && qdict_get_try_str(resp, "event")) {
678 /* Ignore asynchronous QMP events */
679 qobject_unref(resp);
680 resp = qtest_qmp_receive(s);
681 ret = g_strdup(qdict_get_try_str(resp, "return"));
683 g_assert(ret);
684 qobject_unref(resp);
685 g_free(cmd);
686 return ret;
689 char *qtest_hmp(QTestState *s, const char *fmt, ...)
691 va_list ap;
692 char *ret;
694 va_start(ap, fmt);
695 ret = qtest_vhmp(s, fmt, ap);
696 va_end(ap);
697 return ret;
700 const char *qtest_get_arch(void)
702 const char *qemu = qtest_qemu_binary();
703 const char *end = strrchr(qemu, '/');
705 return end + strlen("/qemu-system-");
708 bool qtest_get_irq(QTestState *s, int num)
710 /* dummy operation in order to make sure irq is up to date */
711 qtest_inb(s, 0);
713 return s->irq_level[num];
716 static int64_t qtest_clock_rsp(QTestState *s)
718 gchar **words;
719 int64_t clock;
720 words = qtest_rsp(s, 2);
721 clock = g_ascii_strtoll(words[1], NULL, 0);
722 g_strfreev(words);
723 return clock;
726 int64_t qtest_clock_step_next(QTestState *s)
728 qtest_sendf(s, "clock_step\n");
729 return qtest_clock_rsp(s);
732 int64_t qtest_clock_step(QTestState *s, int64_t step)
734 qtest_sendf(s, "clock_step %"PRIi64"\n", step);
735 return qtest_clock_rsp(s);
738 int64_t qtest_clock_set(QTestState *s, int64_t val)
740 qtest_sendf(s, "clock_set %"PRIi64"\n", val);
741 return qtest_clock_rsp(s);
744 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
746 qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
747 qtest_rsp(s, 0);
750 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
752 qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
753 qtest_rsp(s, 0);
756 void qtest_set_irq_in(QTestState *s, const char *qom_path, const char *name,
757 int num, int level)
759 if (!name) {
760 name = "unnamed-gpio-in";
762 qtest_sendf(s, "set_irq_in %s %s %d %d\n", qom_path, name, num, level);
763 qtest_rsp(s, 0);
766 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
768 qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
769 qtest_rsp(s, 0);
772 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
774 qtest_out(s, "outb", addr, value);
777 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
779 qtest_out(s, "outw", addr, value);
782 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
784 qtest_out(s, "outl", addr, value);
787 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
789 gchar **args;
790 int ret;
791 unsigned long value;
793 qtest_sendf(s, "%s 0x%x\n", cmd, addr);
794 args = qtest_rsp(s, 2);
795 ret = qemu_strtoul(args[1], NULL, 0, &value);
796 g_assert(!ret && value <= UINT32_MAX);
797 g_strfreev(args);
799 return value;
802 uint8_t qtest_inb(QTestState *s, uint16_t addr)
804 return qtest_in(s, "inb", addr);
807 uint16_t qtest_inw(QTestState *s, uint16_t addr)
809 return qtest_in(s, "inw", addr);
812 uint32_t qtest_inl(QTestState *s, uint16_t addr)
814 return qtest_in(s, "inl", addr);
817 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
818 uint64_t value)
820 qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
821 qtest_rsp(s, 0);
824 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
826 qtest_write(s, "writeb", addr, value);
829 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
831 qtest_write(s, "writew", addr, value);
834 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
836 qtest_write(s, "writel", addr, value);
839 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
841 qtest_write(s, "writeq", addr, value);
844 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
846 gchar **args;
847 int ret;
848 uint64_t value;
850 qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
851 args = qtest_rsp(s, 2);
852 ret = qemu_strtou64(args[1], NULL, 0, &value);
853 g_assert(!ret);
854 g_strfreev(args);
856 return value;
859 uint8_t qtest_readb(QTestState *s, uint64_t addr)
861 return qtest_read(s, "readb", addr);
864 uint16_t qtest_readw(QTestState *s, uint64_t addr)
866 return qtest_read(s, "readw", addr);
869 uint32_t qtest_readl(QTestState *s, uint64_t addr)
871 return qtest_read(s, "readl", addr);
874 uint64_t qtest_readq(QTestState *s, uint64_t addr)
876 return qtest_read(s, "readq", addr);
879 static int hex2nib(char ch)
881 if (ch >= '0' && ch <= '9') {
882 return ch - '0';
883 } else if (ch >= 'a' && ch <= 'f') {
884 return 10 + (ch - 'a');
885 } else if (ch >= 'A' && ch <= 'F') {
886 return 10 + (ch - 'a');
887 } else {
888 return -1;
892 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
894 uint8_t *ptr = data;
895 gchar **args;
896 size_t i;
898 if (!size) {
899 return;
902 qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
903 args = qtest_rsp(s, 2);
905 for (i = 0; i < size; i++) {
906 ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
907 ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
910 g_strfreev(args);
913 uint64_t qtest_rtas_call(QTestState *s, const char *name,
914 uint32_t nargs, uint64_t args,
915 uint32_t nret, uint64_t ret)
917 qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n",
918 name, nargs, args, nret, ret);
919 qtest_rsp(s, 0);
920 return 0;
923 void qtest_add_func(const char *str, void (*fn)(void))
925 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
926 g_test_add_func(path, fn);
927 g_free(path);
930 void qtest_add_data_func_full(const char *str, void *data,
931 void (*fn)(const void *),
932 GDestroyNotify data_free_func)
934 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
935 g_test_add_data_func_full(path, data, fn, data_free_func);
936 g_free(path);
939 void qtest_add_data_func(const char *str, const void *data,
940 void (*fn)(const void *))
942 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
943 g_test_add_data_func(path, data, fn);
944 g_free(path);
947 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
949 gchar *bdata;
951 bdata = g_base64_encode(data, size);
952 qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
953 socket_send(s->fd, bdata, strlen(bdata));
954 socket_send(s->fd, "\n", 1);
955 qtest_rsp(s, 0);
956 g_free(bdata);
959 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
961 gchar **args;
962 size_t len;
964 qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
965 args = qtest_rsp(s, 2);
967 g_base64_decode_inplace(args[1], &len);
968 if (size != len) {
969 fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
970 size, len);
971 len = MIN(len, size);
974 memcpy(data, args[1], len);
975 g_strfreev(args);
978 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
980 const uint8_t *ptr = data;
981 size_t i;
982 char *enc;
984 if (!size) {
985 return;
988 enc = g_malloc(2 * size + 1);
990 for (i = 0; i < size; i++) {
991 sprintf(&enc[i * 2], "%02x", ptr[i]);
994 qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
995 qtest_rsp(s, 0);
996 g_free(enc);
999 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
1001 qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
1002 qtest_rsp(s, 0);
1005 QDict *qmp(const char *fmt, ...)
1007 va_list ap;
1008 QDict *response;
1010 va_start(ap, fmt);
1011 response = qtest_vqmp(global_qtest, fmt, ap);
1012 va_end(ap);
1013 return response;
1016 void qmp_send(const char *fmt, ...)
1018 va_list ap;
1020 va_start(ap, fmt);
1021 qtest_qmp_vsend(global_qtest, fmt, ap);
1022 va_end(ap);
1025 char *hmp(const char *fmt, ...)
1027 va_list ap;
1028 char *ret;
1030 va_start(ap, fmt);
1031 ret = qtest_vhmp(global_qtest, fmt, ap);
1032 va_end(ap);
1033 return ret;
1036 bool qtest_big_endian(QTestState *s)
1038 return s->big_endian;
1041 static bool qtest_check_machine_version(const char *mname, const char *basename,
1042 int major, int minor)
1044 char *newname;
1045 bool is_equal;
1047 newname = g_strdup_printf("%s-%i.%i", basename, major, minor);
1048 is_equal = g_str_equal(mname, newname);
1049 g_free(newname);
1051 return is_equal;
1054 static bool qtest_is_old_versioned_machine(const char *mname)
1056 const char *dash = strrchr(mname, '-');
1057 const char *dot = strrchr(mname, '.');
1058 const char *chr;
1059 char *bname;
1060 const int major = QEMU_VERSION_MAJOR;
1061 const int minor = QEMU_VERSION_MINOR;
1062 bool res = false;
1064 if (dash && dot && dot > dash) {
1065 for (chr = dash + 1; *chr; chr++) {
1066 if (!qemu_isdigit(*chr) && *chr != '.') {
1067 return false;
1071 * Now check if it is one of the latest versions. Check major + 1
1072 * and minor + 1 versions as well, since they might already exist
1073 * in the development branch.
1075 bname = g_strdup(mname);
1076 bname[dash - mname] = 0;
1077 res = !qtest_check_machine_version(mname, bname, major + 1, 0) &&
1078 !qtest_check_machine_version(mname, bname, major, minor + 1) &&
1079 !qtest_check_machine_version(mname, bname, major, minor);
1080 g_free(bname);
1083 return res;
1086 void qtest_cb_for_every_machine(void (*cb)(const char *machine),
1087 bool skip_old_versioned)
1089 QDict *response, *minfo;
1090 QList *list;
1091 const QListEntry *p;
1092 QObject *qobj;
1093 QString *qstr;
1094 const char *mname;
1096 qtest_start("-machine none");
1097 response = qmp("{ 'execute': 'query-machines' }");
1098 g_assert(response);
1099 list = qdict_get_qlist(response, "return");
1100 g_assert(list);
1102 for (p = qlist_first(list); p; p = qlist_next(p)) {
1103 minfo = qobject_to(QDict, qlist_entry_obj(p));
1104 g_assert(minfo);
1105 qobj = qdict_get(minfo, "name");
1106 g_assert(qobj);
1107 qstr = qobject_to(QString, qobj);
1108 g_assert(qstr);
1109 mname = qstring_get_str(qstr);
1110 if (!skip_old_versioned || !qtest_is_old_versioned_machine(mname)) {
1111 cb(mname);
1115 qtest_end();
1116 qobject_unref(response);
1119 QDict *qtest_qmp_receive_success(QTestState *s,
1120 void (*event_cb)(void *opaque,
1121 const char *event,
1122 QDict *data),
1123 void *opaque)
1125 QDict *response, *ret, *data;
1126 const char *event;
1128 for (;;) {
1129 response = qtest_qmp_receive(s);
1130 g_assert(!qdict_haskey(response, "error"));
1131 ret = qdict_get_qdict(response, "return");
1132 if (ret) {
1133 break;
1135 event = qdict_get_str(response, "event");
1136 data = qdict_get_qdict(response, "data");
1137 if (event_cb) {
1138 event_cb(opaque, event, data);
1140 qobject_unref(response);
1143 qobject_ref(ret);
1144 qobject_unref(response);
1145 return ret;
1149 * Generic hot-plugging test via the device_add QMP command.
1151 void qtest_qmp_device_add(const char *driver, const char *id,
1152 const char *fmt, ...)
1154 QDict *args, *response;
1155 va_list ap;
1157 va_start(ap, fmt);
1158 args = qdict_from_vjsonf_nofail(fmt, ap);
1159 va_end(ap);
1161 g_assert(!qdict_haskey(args, "driver") && !qdict_haskey(args, "id"));
1162 qdict_put_str(args, "driver", driver);
1163 qdict_put_str(args, "id", id);
1165 response = qmp("{'execute': 'device_add', 'arguments': %p}", args);
1166 g_assert(response);
1167 g_assert(!qdict_haskey(response, "event")); /* We don't expect any events */
1168 g_assert(!qdict_haskey(response, "error"));
1169 qobject_unref(response);
1172 static void device_deleted_cb(void *opaque, const char *name, QDict *data)
1174 bool *got_event = opaque;
1176 g_assert_cmpstr(name, ==, "DEVICE_DELETED");
1177 *got_event = true;
1181 * Generic hot-unplugging test via the device_del QMP command.
1182 * Device deletion will get one response and one event. For example:
1184 * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1186 * will get this one:
1188 * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1189 * "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1190 * "path": "/machine/peripheral/scsi-hd"}}
1192 * and this one:
1194 * {"return": {}}
1196 * But the order of arrival may vary - so we've got to detect both.
1198 void qtest_qmp_device_del(const char *id)
1200 bool got_event = false;
1201 QDict *rsp;
1203 qtest_qmp_send(global_qtest,
1204 "{'execute': 'device_del', 'arguments': {'id': %s}}",
1205 id);
1206 rsp = qtest_qmp_receive_success(global_qtest, device_deleted_cb,
1207 &got_event);
1208 qobject_unref(rsp);
1209 if (!got_event) {
1210 rsp = qmp_receive();
1211 g_assert_cmpstr(qdict_get_try_str(rsp, "event"),
1212 ==, "DEVICE_DELETED");
1213 qobject_unref(rsp);
1217 bool qmp_rsp_is_err(QDict *rsp)
1219 QDict *error = qdict_get_qdict(rsp, "error");
1220 qobject_unref(rsp);
1221 return !!error;
1224 void qmp_assert_error_class(QDict *rsp, const char *class)
1226 QDict *error = qdict_get_qdict(rsp, "error");
1228 g_assert_cmpstr(qdict_get_try_str(error, "class"), ==, class);
1229 g_assert_nonnull(qdict_get_try_str(error, "desc"));
1230 g_assert(!qdict_haskey(rsp, "return"));
1232 qobject_unref(rsp);