commit: Make base read-only if there is an early failure
[qemu/ar7.git] / tests / libqtest.c
blobc49b85482da215424e9cea9ab68a520acac1c89d
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 "
236 "-qtest-log %s "
237 "-chardev socket,path=%s,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 QTestState *qtest_init_with_serial(const char *extra_args, int *sock_fd)
320 int sock_fd_init;
321 char *sock_path, sock_dir[] = "/tmp/qtest-serial-XXXXXX";
322 QTestState *qts;
324 g_assert_true(mkdtemp(sock_dir) != NULL);
325 sock_path = g_strdup_printf("%s/sock", sock_dir);
327 sock_fd_init = init_socket(sock_path);
329 qts = qtest_initf("-chardev socket,id=s0,path=%s -serial chardev:s0 %s",
330 sock_path, extra_args);
332 *sock_fd = socket_accept(sock_fd_init);
334 unlink(sock_path);
335 g_free(sock_path);
336 rmdir(sock_dir);
338 g_assert_true(*sock_fd >= 0);
340 return qts;
343 void qtest_quit(QTestState *s)
345 g_hook_destroy_link(&abrt_hooks, g_hook_find_data(&abrt_hooks, TRUE, s));
347 /* Uninstall SIGABRT handler on last instance */
348 cleanup_sigabrt_handler();
350 kill_qemu(s);
351 close(s->fd);
352 close(s->qmp_fd);
353 g_string_free(s->rx, true);
354 g_free(s);
357 static void socket_send(int fd, const char *buf, size_t size)
359 size_t offset;
361 offset = 0;
362 while (offset < size) {
363 ssize_t len;
365 len = write(fd, buf + offset, size - offset);
366 if (len == -1 && errno == EINTR) {
367 continue;
370 g_assert_cmpint(len, >, 0);
372 offset += len;
376 static void socket_sendf(int fd, const char *fmt, va_list ap)
378 gchar *str = g_strdup_vprintf(fmt, ap);
379 size_t size = strlen(str);
381 socket_send(fd, str, size);
382 g_free(str);
385 static void GCC_FMT_ATTR(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...)
387 va_list ap;
389 va_start(ap, fmt);
390 socket_sendf(s->fd, fmt, ap);
391 va_end(ap);
394 static GString *qtest_recv_line(QTestState *s)
396 GString *line;
397 size_t offset;
398 char *eol;
400 while ((eol = strchr(s->rx->str, '\n')) == NULL) {
401 ssize_t len;
402 char buffer[1024];
404 len = read(s->fd, buffer, sizeof(buffer));
405 if (len == -1 && errno == EINTR) {
406 continue;
409 if (len == -1 || len == 0) {
410 fprintf(stderr, "Broken pipe\n");
411 abort();
414 g_string_append_len(s->rx, buffer, len);
417 offset = eol - s->rx->str;
418 line = g_string_new_len(s->rx->str, offset);
419 g_string_erase(s->rx, 0, offset + 1);
421 return line;
424 static gchar **qtest_rsp(QTestState *s, int expected_args)
426 GString *line;
427 gchar **words;
428 int i;
430 redo:
431 line = qtest_recv_line(s);
432 words = g_strsplit(line->str, " ", 0);
433 g_string_free(line, TRUE);
435 if (strcmp(words[0], "IRQ") == 0) {
436 long irq;
437 int ret;
439 g_assert(words[1] != NULL);
440 g_assert(words[2] != NULL);
442 ret = qemu_strtol(words[2], NULL, 0, &irq);
443 g_assert(!ret);
444 g_assert_cmpint(irq, >=, 0);
445 g_assert_cmpint(irq, <, MAX_IRQ);
447 if (strcmp(words[1], "raise") == 0) {
448 s->irq_level[irq] = true;
449 } else {
450 s->irq_level[irq] = false;
453 g_strfreev(words);
454 goto redo;
457 g_assert(words[0] != NULL);
458 g_assert_cmpstr(words[0], ==, "OK");
460 if (expected_args) {
461 for (i = 0; i < expected_args; i++) {
462 g_assert(words[i] != NULL);
464 } else {
465 g_strfreev(words);
468 return words;
471 static int qtest_query_target_endianness(QTestState *s)
473 gchar **args;
474 int big_endian;
476 qtest_sendf(s, "endianness\n");
477 args = qtest_rsp(s, 1);
478 g_assert(strcmp(args[1], "big") == 0 || strcmp(args[1], "little") == 0);
479 big_endian = strcmp(args[1], "big") == 0;
480 g_strfreev(args);
482 return big_endian;
485 typedef struct {
486 JSONMessageParser parser;
487 QDict *response;
488 } QMPResponseParser;
490 static void qmp_response(void *opaque, QObject *obj, Error *err)
492 QMPResponseParser *qmp = opaque;
494 assert(!obj != !err);
496 if (err) {
497 error_prepend(&err, "QMP JSON response parsing failed: ");
498 error_report_err(err);
499 abort();
502 g_assert(!qmp->response);
503 qmp->response = qobject_to(QDict, obj);
504 g_assert(qmp->response);
507 QDict *qmp_fd_receive(int fd)
509 QMPResponseParser qmp;
510 bool log = getenv("QTEST_LOG") != NULL;
512 qmp.response = NULL;
513 json_message_parser_init(&qmp.parser, qmp_response, &qmp, NULL);
514 while (!qmp.response) {
515 ssize_t len;
516 char c;
518 len = read(fd, &c, 1);
519 if (len == -1 && errno == EINTR) {
520 continue;
523 if (len == -1 || len == 0) {
524 fprintf(stderr, "Broken pipe\n");
525 abort();
528 if (log) {
529 len = write(2, &c, 1);
531 json_message_parser_feed(&qmp.parser, &c, 1);
533 json_message_parser_destroy(&qmp.parser);
535 return qmp.response;
538 QDict *qtest_qmp_receive(QTestState *s)
540 return qmp_fd_receive(s->qmp_fd);
544 * Allow users to send a message without waiting for the reply,
545 * in the case that they choose to discard all replies up until
546 * a particular EVENT is received.
548 void qmp_fd_vsend(int fd, const char *fmt, va_list ap)
550 QObject *qobj;
552 /* Going through qobject ensures we escape strings properly */
553 qobj = qobject_from_vjsonf_nofail(fmt, ap);
555 /* No need to send anything for an empty QObject. */
556 if (qobj) {
557 int log = getenv("QTEST_LOG") != NULL;
558 QString *qstr = qobject_to_json(qobj);
559 const char *str;
562 * BUG: QMP doesn't react to input until it sees a newline, an
563 * object, or an array. Work-around: give it a newline.
565 qstring_append_chr(qstr, '\n');
566 str = qstring_get_str(qstr);
568 if (log) {
569 fprintf(stderr, "%s", str);
571 /* Send QMP request */
572 socket_send(fd, str, qstring_get_length(qstr));
574 qobject_unref(qstr);
575 qobject_unref(qobj);
579 void qtest_qmp_vsend(QTestState *s, const char *fmt, va_list ap)
581 qmp_fd_vsend(s->qmp_fd, fmt, ap);
584 QDict *qmp_fdv(int fd, const char *fmt, va_list ap)
586 qmp_fd_vsend(fd, fmt, ap);
588 return qmp_fd_receive(fd);
591 QDict *qtest_vqmp(QTestState *s, const char *fmt, va_list ap)
593 qtest_qmp_vsend(s, fmt, ap);
595 /* Receive reply */
596 return qtest_qmp_receive(s);
599 QDict *qmp_fd(int fd, const char *fmt, ...)
601 va_list ap;
602 QDict *response;
604 va_start(ap, fmt);
605 response = qmp_fdv(fd, fmt, ap);
606 va_end(ap);
607 return response;
610 void qmp_fd_send(int fd, const char *fmt, ...)
612 va_list ap;
614 va_start(ap, fmt);
615 qmp_fd_vsend(fd, fmt, ap);
616 va_end(ap);
619 QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
621 va_list ap;
622 QDict *response;
624 va_start(ap, fmt);
625 response = qtest_vqmp(s, fmt, ap);
626 va_end(ap);
627 return response;
630 void qtest_qmp_send(QTestState *s, const char *fmt, ...)
632 va_list ap;
634 va_start(ap, fmt);
635 qtest_qmp_vsend(s, fmt, ap);
636 va_end(ap);
639 void qmp_fd_vsend_raw(int fd, const char *fmt, va_list ap)
641 bool log = getenv("QTEST_LOG") != NULL;
642 char *str = g_strdup_vprintf(fmt, ap);
644 if (log) {
645 fprintf(stderr, "%s", str);
647 socket_send(fd, str, strlen(str));
648 g_free(str);
651 void qmp_fd_send_raw(int fd, const char *fmt, ...)
653 va_list ap;
655 va_start(ap, fmt);
656 qmp_fd_vsend_raw(fd, fmt, ap);
657 va_end(ap);
660 void qtest_qmp_send_raw(QTestState *s, const char *fmt, ...)
662 va_list ap;
664 va_start(ap, fmt);
665 qmp_fd_vsend_raw(s->qmp_fd, fmt, ap);
666 va_end(ap);
669 QDict *qtest_qmp_eventwait_ref(QTestState *s, const char *event)
671 QDict *response;
673 for (;;) {
674 response = qtest_qmp_receive(s);
675 if ((qdict_haskey(response, "event")) &&
676 (strcmp(qdict_get_str(response, "event"), event) == 0)) {
677 return response;
679 qobject_unref(response);
683 void qtest_qmp_eventwait(QTestState *s, const char *event)
685 QDict *response;
687 response = qtest_qmp_eventwait_ref(s, event);
688 qobject_unref(response);
691 char *qtest_vhmp(QTestState *s, const char *fmt, va_list ap)
693 char *cmd;
694 QDict *resp;
695 char *ret;
697 cmd = g_strdup_vprintf(fmt, ap);
698 resp = qtest_qmp(s, "{'execute': 'human-monitor-command',"
699 " 'arguments': {'command-line': %s}}",
700 cmd);
701 ret = g_strdup(qdict_get_try_str(resp, "return"));
702 while (ret == NULL && qdict_get_try_str(resp, "event")) {
703 /* Ignore asynchronous QMP events */
704 qobject_unref(resp);
705 resp = qtest_qmp_receive(s);
706 ret = g_strdup(qdict_get_try_str(resp, "return"));
708 g_assert(ret);
709 qobject_unref(resp);
710 g_free(cmd);
711 return ret;
714 char *qtest_hmp(QTestState *s, const char *fmt, ...)
716 va_list ap;
717 char *ret;
719 va_start(ap, fmt);
720 ret = qtest_vhmp(s, fmt, ap);
721 va_end(ap);
722 return ret;
725 const char *qtest_get_arch(void)
727 const char *qemu = qtest_qemu_binary();
728 const char *end = strrchr(qemu, '/');
730 return end + strlen("/qemu-system-");
733 bool qtest_get_irq(QTestState *s, int num)
735 /* dummy operation in order to make sure irq is up to date */
736 qtest_inb(s, 0);
738 return s->irq_level[num];
741 static int64_t qtest_clock_rsp(QTestState *s)
743 gchar **words;
744 int64_t clock;
745 words = qtest_rsp(s, 2);
746 clock = g_ascii_strtoll(words[1], NULL, 0);
747 g_strfreev(words);
748 return clock;
751 int64_t qtest_clock_step_next(QTestState *s)
753 qtest_sendf(s, "clock_step\n");
754 return qtest_clock_rsp(s);
757 int64_t qtest_clock_step(QTestState *s, int64_t step)
759 qtest_sendf(s, "clock_step %"PRIi64"\n", step);
760 return qtest_clock_rsp(s);
763 int64_t qtest_clock_set(QTestState *s, int64_t val)
765 qtest_sendf(s, "clock_set %"PRIi64"\n", val);
766 return qtest_clock_rsp(s);
769 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
771 qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
772 qtest_rsp(s, 0);
775 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
777 qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
778 qtest_rsp(s, 0);
781 void qtest_set_irq_in(QTestState *s, const char *qom_path, const char *name,
782 int num, int level)
784 if (!name) {
785 name = "unnamed-gpio-in";
787 qtest_sendf(s, "set_irq_in %s %s %d %d\n", qom_path, name, num, level);
788 qtest_rsp(s, 0);
791 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
793 qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
794 qtest_rsp(s, 0);
797 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
799 qtest_out(s, "outb", addr, value);
802 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
804 qtest_out(s, "outw", addr, value);
807 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
809 qtest_out(s, "outl", addr, value);
812 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
814 gchar **args;
815 int ret;
816 unsigned long value;
818 qtest_sendf(s, "%s 0x%x\n", cmd, addr);
819 args = qtest_rsp(s, 2);
820 ret = qemu_strtoul(args[1], NULL, 0, &value);
821 g_assert(!ret && value <= UINT32_MAX);
822 g_strfreev(args);
824 return value;
827 uint8_t qtest_inb(QTestState *s, uint16_t addr)
829 return qtest_in(s, "inb", addr);
832 uint16_t qtest_inw(QTestState *s, uint16_t addr)
834 return qtest_in(s, "inw", addr);
837 uint32_t qtest_inl(QTestState *s, uint16_t addr)
839 return qtest_in(s, "inl", addr);
842 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
843 uint64_t value)
845 qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
846 qtest_rsp(s, 0);
849 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
851 qtest_write(s, "writeb", addr, value);
854 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
856 qtest_write(s, "writew", addr, value);
859 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
861 qtest_write(s, "writel", addr, value);
864 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
866 qtest_write(s, "writeq", addr, value);
869 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
871 gchar **args;
872 int ret;
873 uint64_t value;
875 qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
876 args = qtest_rsp(s, 2);
877 ret = qemu_strtou64(args[1], NULL, 0, &value);
878 g_assert(!ret);
879 g_strfreev(args);
881 return value;
884 uint8_t qtest_readb(QTestState *s, uint64_t addr)
886 return qtest_read(s, "readb", addr);
889 uint16_t qtest_readw(QTestState *s, uint64_t addr)
891 return qtest_read(s, "readw", addr);
894 uint32_t qtest_readl(QTestState *s, uint64_t addr)
896 return qtest_read(s, "readl", addr);
899 uint64_t qtest_readq(QTestState *s, uint64_t addr)
901 return qtest_read(s, "readq", addr);
904 static int hex2nib(char ch)
906 if (ch >= '0' && ch <= '9') {
907 return ch - '0';
908 } else if (ch >= 'a' && ch <= 'f') {
909 return 10 + (ch - 'a');
910 } else if (ch >= 'A' && ch <= 'F') {
911 return 10 + (ch - 'a');
912 } else {
913 return -1;
917 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
919 uint8_t *ptr = data;
920 gchar **args;
921 size_t i;
923 if (!size) {
924 return;
927 qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
928 args = qtest_rsp(s, 2);
930 for (i = 0; i < size; i++) {
931 ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
932 ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
935 g_strfreev(args);
938 uint64_t qtest_rtas_call(QTestState *s, const char *name,
939 uint32_t nargs, uint64_t args,
940 uint32_t nret, uint64_t ret)
942 qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n",
943 name, nargs, args, nret, ret);
944 qtest_rsp(s, 0);
945 return 0;
948 void qtest_add_func(const char *str, void (*fn)(void))
950 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
951 g_test_add_func(path, fn);
952 g_free(path);
955 void qtest_add_data_func_full(const char *str, void *data,
956 void (*fn)(const void *),
957 GDestroyNotify data_free_func)
959 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
960 g_test_add_data_func_full(path, data, fn, data_free_func);
961 g_free(path);
964 void qtest_add_data_func(const char *str, const void *data,
965 void (*fn)(const void *))
967 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
968 g_test_add_data_func(path, data, fn);
969 g_free(path);
972 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
974 gchar *bdata;
976 bdata = g_base64_encode(data, size);
977 qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
978 socket_send(s->fd, bdata, strlen(bdata));
979 socket_send(s->fd, "\n", 1);
980 qtest_rsp(s, 0);
981 g_free(bdata);
984 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
986 gchar **args;
987 size_t len;
989 qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
990 args = qtest_rsp(s, 2);
992 g_base64_decode_inplace(args[1], &len);
993 if (size != len) {
994 fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
995 size, len);
996 len = MIN(len, size);
999 memcpy(data, args[1], len);
1000 g_strfreev(args);
1003 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1005 const uint8_t *ptr = data;
1006 size_t i;
1007 char *enc;
1009 if (!size) {
1010 return;
1013 enc = g_malloc(2 * size + 1);
1015 for (i = 0; i < size; i++) {
1016 sprintf(&enc[i * 2], "%02x", ptr[i]);
1019 qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
1020 qtest_rsp(s, 0);
1021 g_free(enc);
1024 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
1026 qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
1027 qtest_rsp(s, 0);
1030 QDict *qmp(const char *fmt, ...)
1032 va_list ap;
1033 QDict *response;
1035 va_start(ap, fmt);
1036 response = qtest_vqmp(global_qtest, fmt, ap);
1037 va_end(ap);
1038 return response;
1041 void qmp_send(const char *fmt, ...)
1043 va_list ap;
1045 va_start(ap, fmt);
1046 qtest_qmp_vsend(global_qtest, fmt, ap);
1047 va_end(ap);
1050 char *hmp(const char *fmt, ...)
1052 va_list ap;
1053 char *ret;
1055 va_start(ap, fmt);
1056 ret = qtest_vhmp(global_qtest, fmt, ap);
1057 va_end(ap);
1058 return ret;
1061 bool qtest_big_endian(QTestState *s)
1063 return s->big_endian;
1066 static bool qtest_check_machine_version(const char *mname, const char *basename,
1067 int major, int minor)
1069 char *newname;
1070 bool is_equal;
1072 newname = g_strdup_printf("%s-%i.%i", basename, major, minor);
1073 is_equal = g_str_equal(mname, newname);
1074 g_free(newname);
1076 return is_equal;
1079 static bool qtest_is_old_versioned_machine(const char *mname)
1081 const char *dash = strrchr(mname, '-');
1082 const char *dot = strrchr(mname, '.');
1083 const char *chr;
1084 char *bname;
1085 const int major = QEMU_VERSION_MAJOR;
1086 const int minor = QEMU_VERSION_MINOR;
1087 bool res = false;
1089 if (dash && dot && dot > dash) {
1090 for (chr = dash + 1; *chr; chr++) {
1091 if (!qemu_isdigit(*chr) && *chr != '.') {
1092 return false;
1096 * Now check if it is one of the latest versions. Check major + 1
1097 * and minor + 1 versions as well, since they might already exist
1098 * in the development branch.
1100 bname = g_strdup(mname);
1101 bname[dash - mname] = 0;
1102 res = !qtest_check_machine_version(mname, bname, major + 1, 0) &&
1103 !qtest_check_machine_version(mname, bname, major, minor + 1) &&
1104 !qtest_check_machine_version(mname, bname, major, minor);
1105 g_free(bname);
1108 return res;
1111 void qtest_cb_for_every_machine(void (*cb)(const char *machine),
1112 bool skip_old_versioned)
1114 QDict *response, *minfo;
1115 QList *list;
1116 const QListEntry *p;
1117 QObject *qobj;
1118 QString *qstr;
1119 const char *mname;
1121 qtest_start("-machine none");
1122 response = qmp("{ 'execute': 'query-machines' }");
1123 g_assert(response);
1124 list = qdict_get_qlist(response, "return");
1125 g_assert(list);
1127 for (p = qlist_first(list); p; p = qlist_next(p)) {
1128 minfo = qobject_to(QDict, qlist_entry_obj(p));
1129 g_assert(minfo);
1130 qobj = qdict_get(minfo, "name");
1131 g_assert(qobj);
1132 qstr = qobject_to(QString, qobj);
1133 g_assert(qstr);
1134 mname = qstring_get_str(qstr);
1135 if (!skip_old_versioned || !qtest_is_old_versioned_machine(mname)) {
1136 cb(mname);
1140 qtest_end();
1141 qobject_unref(response);
1144 QDict *qtest_qmp_receive_success(QTestState *s,
1145 void (*event_cb)(void *opaque,
1146 const char *event,
1147 QDict *data),
1148 void *opaque)
1150 QDict *response, *ret, *data;
1151 const char *event;
1153 for (;;) {
1154 response = qtest_qmp_receive(s);
1155 g_assert(!qdict_haskey(response, "error"));
1156 ret = qdict_get_qdict(response, "return");
1157 if (ret) {
1158 break;
1160 event = qdict_get_str(response, "event");
1161 data = qdict_get_qdict(response, "data");
1162 if (event_cb) {
1163 event_cb(opaque, event, data);
1165 qobject_unref(response);
1168 qobject_ref(ret);
1169 qobject_unref(response);
1170 return ret;
1174 * Generic hot-plugging test via the device_add QMP command.
1176 void qtest_qmp_device_add(const char *driver, const char *id,
1177 const char *fmt, ...)
1179 QDict *args, *response;
1180 va_list ap;
1182 va_start(ap, fmt);
1183 args = qdict_from_vjsonf_nofail(fmt, ap);
1184 va_end(ap);
1186 g_assert(!qdict_haskey(args, "driver") && !qdict_haskey(args, "id"));
1187 qdict_put_str(args, "driver", driver);
1188 qdict_put_str(args, "id", id);
1190 response = qmp("{'execute': 'device_add', 'arguments': %p}", args);
1191 g_assert(response);
1192 g_assert(!qdict_haskey(response, "event")); /* We don't expect any events */
1193 g_assert(!qdict_haskey(response, "error"));
1194 qobject_unref(response);
1197 static void device_deleted_cb(void *opaque, const char *name, QDict *data)
1199 bool *got_event = opaque;
1201 g_assert_cmpstr(name, ==, "DEVICE_DELETED");
1202 *got_event = true;
1206 * Generic hot-unplugging test via the device_del QMP command.
1207 * Device deletion will get one response and one event. For example:
1209 * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1211 * will get this one:
1213 * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1214 * "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1215 * "path": "/machine/peripheral/scsi-hd"}}
1217 * and this one:
1219 * {"return": {}}
1221 * But the order of arrival may vary - so we've got to detect both.
1223 void qtest_qmp_device_del(const char *id)
1225 bool got_event = false;
1226 QDict *rsp;
1228 qtest_qmp_send(global_qtest,
1229 "{'execute': 'device_del', 'arguments': {'id': %s}}",
1230 id);
1231 rsp = qtest_qmp_receive_success(global_qtest, device_deleted_cb,
1232 &got_event);
1233 qobject_unref(rsp);
1234 if (!got_event) {
1235 rsp = qmp_receive();
1236 g_assert_cmpstr(qdict_get_try_str(rsp, "event"),
1237 ==, "DEVICE_DELETED");
1238 qobject_unref(rsp);
1242 bool qmp_rsp_is_err(QDict *rsp)
1244 QDict *error = qdict_get_qdict(rsp, "error");
1245 qobject_unref(rsp);
1246 return !!error;
1249 void qmp_assert_error_class(QDict *rsp, const char *class)
1251 QDict *error = qdict_get_qdict(rsp, "error");
1253 g_assert_cmpstr(qdict_get_try_str(error, "class"), ==, class);
1254 g_assert_nonnull(qdict_get_try_str(error, "desc"));
1255 g_assert(!qdict_haskey(rsp, "return"));
1257 qobject_unref(rsp);