cpu: Move the softmmu tlb to CPUNegativeOffsetState
[qemu/ar7.git] / tests / libqtest.c
blob9b9b5f37fc97e162fbc89982a68f4ca55bde1684
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
35 #define SOCKET_MAX_FDS 16
37 QTestState *global_qtest;
39 struct QTestState
41 int fd;
42 int qmp_fd;
43 pid_t qemu_pid; /* our child QEMU process */
44 int wstatus;
45 bool big_endian;
46 bool irq_level[MAX_IRQ];
47 GString *rx;
50 static GHookList abrt_hooks;
51 static struct sigaction sigact_old;
53 static int qtest_query_target_endianness(QTestState *s);
55 static int init_socket(const char *socket_path)
57 struct sockaddr_un addr;
58 int sock;
59 int ret;
61 sock = socket(PF_UNIX, SOCK_STREAM, 0);
62 g_assert_cmpint(sock, !=, -1);
64 addr.sun_family = AF_UNIX;
65 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
66 qemu_set_cloexec(sock);
68 do {
69 ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
70 } while (ret == -1 && errno == EINTR);
71 g_assert_cmpint(ret, !=, -1);
72 ret = listen(sock, 1);
73 g_assert_cmpint(ret, !=, -1);
75 return sock;
78 static int socket_accept(int sock)
80 struct sockaddr_un addr;
81 socklen_t addrlen;
82 int ret;
83 struct timeval timeout = { .tv_sec = SOCKET_TIMEOUT,
84 .tv_usec = 0 };
86 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *)&timeout,
87 sizeof(timeout));
89 do {
90 addrlen = sizeof(addr);
91 ret = accept(sock, (struct sockaddr *)&addr, &addrlen);
92 } while (ret == -1 && errno == EINTR);
93 if (ret == -1) {
94 fprintf(stderr, "%s failed: %s\n", __func__, strerror(errno));
96 close(sock);
98 return ret;
101 bool qtest_probe_child(QTestState *s)
103 pid_t pid = s->qemu_pid;
105 if (pid != -1) {
106 pid = waitpid(pid, &s->wstatus, WNOHANG);
107 if (pid == 0) {
108 return true;
110 s->qemu_pid = -1;
112 return false;
115 static void kill_qemu(QTestState *s)
117 pid_t pid = s->qemu_pid;
118 int wstatus;
120 /* Skip wait if qtest_probe_child already reaped. */
121 if (pid != -1) {
122 kill(pid, SIGTERM);
123 TFR(pid = waitpid(s->qemu_pid, &s->wstatus, 0));
124 assert(pid == s->qemu_pid);
128 * We expect qemu to exit with status 0; anything else is
129 * fishy and should be logged with as much detail as possible.
131 wstatus = s->wstatus;
132 if (wstatus) {
133 if (WIFEXITED(wstatus)) {
134 fprintf(stderr, "%s:%d: kill_qemu() tried to terminate QEMU "
135 "process but encountered exit status %d\n",
136 __FILE__, __LINE__, WEXITSTATUS(wstatus));
137 } else if (WIFSIGNALED(wstatus)) {
138 int sig = WTERMSIG(wstatus);
139 const char *signame = strsignal(sig) ?: "unknown ???";
140 const char *dump = WCOREDUMP(wstatus) ? " (core dumped)" : "";
142 fprintf(stderr, "%s:%d: kill_qemu() detected QEMU death "
143 "from signal %d (%s)%s\n",
144 __FILE__, __LINE__, sig, signame, dump);
146 abort();
150 static void kill_qemu_hook_func(void *s)
152 kill_qemu(s);
155 static void sigabrt_handler(int signo)
157 g_hook_list_invoke(&abrt_hooks, FALSE);
160 static void setup_sigabrt_handler(void)
162 struct sigaction sigact;
164 /* Catch SIGABRT to clean up on g_assert() failure */
165 sigact = (struct sigaction){
166 .sa_handler = sigabrt_handler,
167 .sa_flags = SA_RESETHAND,
169 sigemptyset(&sigact.sa_mask);
170 sigaction(SIGABRT, &sigact, &sigact_old);
173 static void cleanup_sigabrt_handler(void)
175 sigaction(SIGABRT, &sigact_old, NULL);
178 void qtest_add_abrt_handler(GHookFunc fn, const void *data)
180 GHook *hook;
182 /* Only install SIGABRT handler once */
183 if (!abrt_hooks.is_setup) {
184 g_hook_list_init(&abrt_hooks, sizeof(GHook));
186 setup_sigabrt_handler();
188 hook = g_hook_alloc(&abrt_hooks);
189 hook->func = fn;
190 hook->data = (void *)data;
192 g_hook_prepend(&abrt_hooks, hook);
195 static const char *qtest_qemu_binary(void)
197 const char *qemu_bin;
199 qemu_bin = getenv("QTEST_QEMU_BINARY");
200 if (!qemu_bin) {
201 fprintf(stderr, "Environment variable QTEST_QEMU_BINARY required\n");
202 exit(1);
205 return qemu_bin;
208 QTestState *qtest_init_without_qmp_handshake(const char *extra_args)
210 QTestState *s;
211 int sock, qmpsock, i;
212 gchar *socket_path;
213 gchar *qmp_socket_path;
214 gchar *command;
215 const char *qemu_binary = qtest_qemu_binary();
217 s = g_new(QTestState, 1);
219 socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
220 qmp_socket_path = g_strdup_printf("/tmp/qtest-%d.qmp", getpid());
222 /* It's possible that if an earlier test run crashed it might
223 * have left a stale unix socket lying around. Delete any
224 * stale old socket to avoid spurious test failures with
225 * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1)
227 unlink(socket_path);
228 unlink(qmp_socket_path);
230 sock = init_socket(socket_path);
231 qmpsock = init_socket(qmp_socket_path);
233 qtest_add_abrt_handler(kill_qemu_hook_func, s);
235 command = g_strdup_printf("exec %s "
236 "-qtest unix:%s "
237 "-qtest-log %s "
238 "-chardev socket,path=%s,id=char0 "
239 "-mon chardev=char0,mode=control "
240 "-machine accel=qtest "
241 "-display none "
242 "%s", qemu_binary, socket_path,
243 getenv("QTEST_LOG") ? "/dev/fd/2" : "/dev/null",
244 qmp_socket_path,
245 extra_args ?: "");
247 g_test_message("starting QEMU: %s", command);
249 s->wstatus = 0;
250 s->qemu_pid = fork();
251 if (s->qemu_pid == 0) {
252 setenv("QEMU_AUDIO_DRV", "none", true);
253 execlp("/bin/sh", "sh", "-c", command, NULL);
254 exit(1);
257 g_free(command);
258 s->fd = socket_accept(sock);
259 if (s->fd >= 0) {
260 s->qmp_fd = socket_accept(qmpsock);
262 unlink(socket_path);
263 unlink(qmp_socket_path);
264 g_free(socket_path);
265 g_free(qmp_socket_path);
267 g_assert(s->fd >= 0 && s->qmp_fd >= 0);
269 s->rx = g_string_new("");
270 for (i = 0; i < MAX_IRQ; i++) {
271 s->irq_level[i] = false;
274 if (getenv("QTEST_STOP")) {
275 kill(s->qemu_pid, SIGSTOP);
278 /* ask endianness of the target */
280 s->big_endian = qtest_query_target_endianness(s);
282 return s;
285 QTestState *qtest_init(const char *extra_args)
287 QTestState *s = qtest_init_without_qmp_handshake(extra_args);
288 QDict *greeting;
290 /* Read the QMP greeting and then do the handshake */
291 greeting = qtest_qmp_receive(s);
292 qobject_unref(greeting);
293 qobject_unref(qtest_qmp(s, "{ 'execute': 'qmp_capabilities' }"));
295 return s;
298 QTestState *qtest_vinitf(const char *fmt, va_list ap)
300 char *args = g_strdup_vprintf(fmt, ap);
301 QTestState *s;
303 s = qtest_init(args);
304 g_free(args);
305 return s;
308 QTestState *qtest_initf(const char *fmt, ...)
310 va_list ap;
311 QTestState *s;
313 va_start(ap, fmt);
314 s = qtest_vinitf(fmt, ap);
315 va_end(ap);
316 return s;
319 QTestState *qtest_init_with_serial(const char *extra_args, int *sock_fd)
321 int sock_fd_init;
322 char *sock_path, sock_dir[] = "/tmp/qtest-serial-XXXXXX";
323 QTestState *qts;
325 g_assert_true(mkdtemp(sock_dir) != NULL);
326 sock_path = g_strdup_printf("%s/sock", sock_dir);
328 sock_fd_init = init_socket(sock_path);
330 qts = qtest_initf("-chardev socket,id=s0,path=%s -serial chardev:s0 %s",
331 sock_path, extra_args);
333 *sock_fd = socket_accept(sock_fd_init);
335 unlink(sock_path);
336 g_free(sock_path);
337 rmdir(sock_dir);
339 g_assert_true(*sock_fd >= 0);
341 return qts;
344 void qtest_quit(QTestState *s)
346 g_hook_destroy_link(&abrt_hooks, g_hook_find_data(&abrt_hooks, TRUE, s));
348 /* Uninstall SIGABRT handler on last instance */
349 cleanup_sigabrt_handler();
351 kill_qemu(s);
352 close(s->fd);
353 close(s->qmp_fd);
354 g_string_free(s->rx, true);
355 g_free(s);
358 static void socket_send(int fd, const char *buf, size_t size)
360 size_t offset;
362 offset = 0;
363 while (offset < size) {
364 ssize_t len;
366 len = write(fd, buf + offset, size - offset);
367 if (len == -1 && errno == EINTR) {
368 continue;
371 g_assert_cmpint(len, >, 0);
373 offset += len;
377 static void socket_sendf(int fd, const char *fmt, va_list ap)
379 gchar *str = g_strdup_vprintf(fmt, ap);
380 size_t size = strlen(str);
382 socket_send(fd, str, size);
383 g_free(str);
386 static void GCC_FMT_ATTR(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...)
388 va_list ap;
390 va_start(ap, fmt);
391 socket_sendf(s->fd, fmt, ap);
392 va_end(ap);
395 /* Sends a message and file descriptors to the socket.
396 * It's needed for qmp-commands like getfd/add-fd */
397 static void socket_send_fds(int socket_fd, int *fds, size_t fds_num,
398 const char *buf, size_t buf_size)
400 ssize_t ret;
401 struct msghdr msg = { 0 };
402 char control[CMSG_SPACE(sizeof(int) * SOCKET_MAX_FDS)] = { 0 };
403 size_t fdsize = sizeof(int) * fds_num;
404 struct cmsghdr *cmsg;
405 struct iovec iov = { .iov_base = (char *)buf, .iov_len = buf_size };
407 msg.msg_iov = &iov;
408 msg.msg_iovlen = 1;
410 if (fds && fds_num > 0) {
411 g_assert_cmpuint(fds_num, <, SOCKET_MAX_FDS);
413 msg.msg_control = control;
414 msg.msg_controllen = CMSG_SPACE(fdsize);
416 cmsg = CMSG_FIRSTHDR(&msg);
417 cmsg->cmsg_len = CMSG_LEN(fdsize);
418 cmsg->cmsg_level = SOL_SOCKET;
419 cmsg->cmsg_type = SCM_RIGHTS;
420 memcpy(CMSG_DATA(cmsg), fds, fdsize);
423 do {
424 ret = sendmsg(socket_fd, &msg, 0);
425 } while (ret < 0 && errno == EINTR);
426 g_assert_cmpint(ret, >, 0);
429 static GString *qtest_recv_line(QTestState *s)
431 GString *line;
432 size_t offset;
433 char *eol;
435 while ((eol = strchr(s->rx->str, '\n')) == NULL) {
436 ssize_t len;
437 char buffer[1024];
439 len = read(s->fd, buffer, sizeof(buffer));
440 if (len == -1 && errno == EINTR) {
441 continue;
444 if (len == -1 || len == 0) {
445 fprintf(stderr, "Broken pipe\n");
446 abort();
449 g_string_append_len(s->rx, buffer, len);
452 offset = eol - s->rx->str;
453 line = g_string_new_len(s->rx->str, offset);
454 g_string_erase(s->rx, 0, offset + 1);
456 return line;
459 static gchar **qtest_rsp(QTestState *s, int expected_args)
461 GString *line;
462 gchar **words;
463 int i;
465 redo:
466 line = qtest_recv_line(s);
467 words = g_strsplit(line->str, " ", 0);
468 g_string_free(line, TRUE);
470 if (strcmp(words[0], "IRQ") == 0) {
471 long irq;
472 int ret;
474 g_assert(words[1] != NULL);
475 g_assert(words[2] != NULL);
477 ret = qemu_strtol(words[2], NULL, 0, &irq);
478 g_assert(!ret);
479 g_assert_cmpint(irq, >=, 0);
480 g_assert_cmpint(irq, <, MAX_IRQ);
482 if (strcmp(words[1], "raise") == 0) {
483 s->irq_level[irq] = true;
484 } else {
485 s->irq_level[irq] = false;
488 g_strfreev(words);
489 goto redo;
492 g_assert(words[0] != NULL);
493 g_assert_cmpstr(words[0], ==, "OK");
495 if (expected_args) {
496 for (i = 0; i < expected_args; i++) {
497 g_assert(words[i] != NULL);
499 } else {
500 g_strfreev(words);
503 return words;
506 static int qtest_query_target_endianness(QTestState *s)
508 gchar **args;
509 int big_endian;
511 qtest_sendf(s, "endianness\n");
512 args = qtest_rsp(s, 1);
513 g_assert(strcmp(args[1], "big") == 0 || strcmp(args[1], "little") == 0);
514 big_endian = strcmp(args[1], "big") == 0;
515 g_strfreev(args);
517 return big_endian;
520 typedef struct {
521 JSONMessageParser parser;
522 QDict *response;
523 } QMPResponseParser;
525 static void qmp_response(void *opaque, QObject *obj, Error *err)
527 QMPResponseParser *qmp = opaque;
529 assert(!obj != !err);
531 if (err) {
532 error_prepend(&err, "QMP JSON response parsing failed: ");
533 error_report_err(err);
534 abort();
537 g_assert(!qmp->response);
538 qmp->response = qobject_to(QDict, obj);
539 g_assert(qmp->response);
542 QDict *qmp_fd_receive(int fd)
544 QMPResponseParser qmp;
545 bool log = getenv("QTEST_LOG") != NULL;
547 qmp.response = NULL;
548 json_message_parser_init(&qmp.parser, qmp_response, &qmp, NULL);
549 while (!qmp.response) {
550 ssize_t len;
551 char c;
553 len = read(fd, &c, 1);
554 if (len == -1 && errno == EINTR) {
555 continue;
558 if (len == -1 || len == 0) {
559 fprintf(stderr, "Broken pipe\n");
560 abort();
563 if (log) {
564 len = write(2, &c, 1);
566 json_message_parser_feed(&qmp.parser, &c, 1);
568 json_message_parser_destroy(&qmp.parser);
570 return qmp.response;
573 QDict *qtest_qmp_receive(QTestState *s)
575 return qmp_fd_receive(s->qmp_fd);
579 * Allow users to send a message without waiting for the reply,
580 * in the case that they choose to discard all replies up until
581 * a particular EVENT is received.
583 void qmp_fd_vsend_fds(int fd, int *fds, size_t fds_num,
584 const char *fmt, va_list ap)
586 QObject *qobj;
588 /* Going through qobject ensures we escape strings properly */
589 qobj = qobject_from_vjsonf_nofail(fmt, ap);
591 /* No need to send anything for an empty QObject. */
592 if (qobj) {
593 int log = getenv("QTEST_LOG") != NULL;
594 QString *qstr = qobject_to_json(qobj);
595 const char *str;
598 * BUG: QMP doesn't react to input until it sees a newline, an
599 * object, or an array. Work-around: give it a newline.
601 qstring_append_chr(qstr, '\n');
602 str = qstring_get_str(qstr);
604 if (log) {
605 fprintf(stderr, "%s", str);
607 /* Send QMP request */
608 if (fds && fds_num > 0) {
609 socket_send_fds(fd, fds, fds_num, str, qstring_get_length(qstr));
610 } else {
611 socket_send(fd, str, qstring_get_length(qstr));
614 qobject_unref(qstr);
615 qobject_unref(qobj);
619 void qmp_fd_vsend(int fd, const char *fmt, va_list ap)
621 qmp_fd_vsend_fds(fd, NULL, 0, fmt, ap);
624 void qtest_qmp_vsend_fds(QTestState *s, int *fds, size_t fds_num,
625 const char *fmt, va_list ap)
627 qmp_fd_vsend_fds(s->qmp_fd, fds, fds_num, fmt, ap);
630 void qtest_qmp_vsend(QTestState *s, const char *fmt, va_list ap)
632 qmp_fd_vsend_fds(s->qmp_fd, NULL, 0, fmt, ap);
635 QDict *qmp_fdv(int fd, const char *fmt, va_list ap)
637 qmp_fd_vsend_fds(fd, NULL, 0, fmt, ap);
639 return qmp_fd_receive(fd);
642 QDict *qtest_vqmp_fds(QTestState *s, int *fds, size_t fds_num,
643 const char *fmt, va_list ap)
645 qtest_qmp_vsend_fds(s, fds, fds_num, fmt, ap);
647 /* Receive reply */
648 return qtest_qmp_receive(s);
651 QDict *qtest_vqmp(QTestState *s, const char *fmt, va_list ap)
653 qtest_qmp_vsend(s, fmt, ap);
655 /* Receive reply */
656 return qtest_qmp_receive(s);
659 QDict *qmp_fd(int fd, const char *fmt, ...)
661 va_list ap;
662 QDict *response;
664 va_start(ap, fmt);
665 response = qmp_fdv(fd, fmt, ap);
666 va_end(ap);
667 return response;
670 void qmp_fd_send(int fd, const char *fmt, ...)
672 va_list ap;
674 va_start(ap, fmt);
675 qmp_fd_vsend(fd, fmt, ap);
676 va_end(ap);
679 QDict *qtest_qmp_fds(QTestState *s, int *fds, size_t fds_num,
680 const char *fmt, ...)
682 va_list ap;
683 QDict *response;
685 va_start(ap, fmt);
686 response = qtest_vqmp_fds(s, fds, fds_num, fmt, ap);
687 va_end(ap);
688 return response;
691 QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
693 va_list ap;
694 QDict *response;
696 va_start(ap, fmt);
697 response = qtest_vqmp(s, fmt, ap);
698 va_end(ap);
699 return response;
702 void qtest_qmp_send(QTestState *s, const char *fmt, ...)
704 va_list ap;
706 va_start(ap, fmt);
707 qtest_qmp_vsend(s, fmt, ap);
708 va_end(ap);
711 void qmp_fd_vsend_raw(int fd, const char *fmt, va_list ap)
713 bool log = getenv("QTEST_LOG") != NULL;
714 char *str = g_strdup_vprintf(fmt, ap);
716 if (log) {
717 fprintf(stderr, "%s", str);
719 socket_send(fd, str, strlen(str));
720 g_free(str);
723 void qmp_fd_send_raw(int fd, const char *fmt, ...)
725 va_list ap;
727 va_start(ap, fmt);
728 qmp_fd_vsend_raw(fd, fmt, ap);
729 va_end(ap);
732 void qtest_qmp_send_raw(QTestState *s, const char *fmt, ...)
734 va_list ap;
736 va_start(ap, fmt);
737 qmp_fd_vsend_raw(s->qmp_fd, fmt, ap);
738 va_end(ap);
741 QDict *qtest_qmp_eventwait_ref(QTestState *s, const char *event)
743 QDict *response;
745 for (;;) {
746 response = qtest_qmp_receive(s);
747 if ((qdict_haskey(response, "event")) &&
748 (strcmp(qdict_get_str(response, "event"), event) == 0)) {
749 return response;
751 qobject_unref(response);
755 void qtest_qmp_eventwait(QTestState *s, const char *event)
757 QDict *response;
759 response = qtest_qmp_eventwait_ref(s, event);
760 qobject_unref(response);
763 char *qtest_vhmp(QTestState *s, const char *fmt, va_list ap)
765 char *cmd;
766 QDict *resp;
767 char *ret;
769 cmd = g_strdup_vprintf(fmt, ap);
770 resp = qtest_qmp(s, "{'execute': 'human-monitor-command',"
771 " 'arguments': {'command-line': %s}}",
772 cmd);
773 ret = g_strdup(qdict_get_try_str(resp, "return"));
774 while (ret == NULL && qdict_get_try_str(resp, "event")) {
775 /* Ignore asynchronous QMP events */
776 qobject_unref(resp);
777 resp = qtest_qmp_receive(s);
778 ret = g_strdup(qdict_get_try_str(resp, "return"));
780 g_assert(ret);
781 qobject_unref(resp);
782 g_free(cmd);
783 return ret;
786 char *qtest_hmp(QTestState *s, const char *fmt, ...)
788 va_list ap;
789 char *ret;
791 va_start(ap, fmt);
792 ret = qtest_vhmp(s, fmt, ap);
793 va_end(ap);
794 return ret;
797 const char *qtest_get_arch(void)
799 const char *qemu = qtest_qemu_binary();
800 const char *end = strrchr(qemu, '/');
802 return end + strlen("/qemu-system-");
805 bool qtest_get_irq(QTestState *s, int num)
807 /* dummy operation in order to make sure irq is up to date */
808 qtest_inb(s, 0);
810 return s->irq_level[num];
813 static int64_t qtest_clock_rsp(QTestState *s)
815 gchar **words;
816 int64_t clock;
817 words = qtest_rsp(s, 2);
818 clock = g_ascii_strtoll(words[1], NULL, 0);
819 g_strfreev(words);
820 return clock;
823 int64_t qtest_clock_step_next(QTestState *s)
825 qtest_sendf(s, "clock_step\n");
826 return qtest_clock_rsp(s);
829 int64_t qtest_clock_step(QTestState *s, int64_t step)
831 qtest_sendf(s, "clock_step %"PRIi64"\n", step);
832 return qtest_clock_rsp(s);
835 int64_t qtest_clock_set(QTestState *s, int64_t val)
837 qtest_sendf(s, "clock_set %"PRIi64"\n", val);
838 return qtest_clock_rsp(s);
841 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
843 qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
844 qtest_rsp(s, 0);
847 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
849 qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
850 qtest_rsp(s, 0);
853 void qtest_set_irq_in(QTestState *s, const char *qom_path, const char *name,
854 int num, int level)
856 if (!name) {
857 name = "unnamed-gpio-in";
859 qtest_sendf(s, "set_irq_in %s %s %d %d\n", qom_path, name, num, level);
860 qtest_rsp(s, 0);
863 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
865 qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
866 qtest_rsp(s, 0);
869 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
871 qtest_out(s, "outb", addr, value);
874 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
876 qtest_out(s, "outw", addr, value);
879 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
881 qtest_out(s, "outl", addr, value);
884 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
886 gchar **args;
887 int ret;
888 unsigned long value;
890 qtest_sendf(s, "%s 0x%x\n", cmd, addr);
891 args = qtest_rsp(s, 2);
892 ret = qemu_strtoul(args[1], NULL, 0, &value);
893 g_assert(!ret && value <= UINT32_MAX);
894 g_strfreev(args);
896 return value;
899 uint8_t qtest_inb(QTestState *s, uint16_t addr)
901 return qtest_in(s, "inb", addr);
904 uint16_t qtest_inw(QTestState *s, uint16_t addr)
906 return qtest_in(s, "inw", addr);
909 uint32_t qtest_inl(QTestState *s, uint16_t addr)
911 return qtest_in(s, "inl", addr);
914 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
915 uint64_t value)
917 qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
918 qtest_rsp(s, 0);
921 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
923 qtest_write(s, "writeb", addr, value);
926 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
928 qtest_write(s, "writew", addr, value);
931 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
933 qtest_write(s, "writel", addr, value);
936 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
938 qtest_write(s, "writeq", addr, value);
941 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
943 gchar **args;
944 int ret;
945 uint64_t value;
947 qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
948 args = qtest_rsp(s, 2);
949 ret = qemu_strtou64(args[1], NULL, 0, &value);
950 g_assert(!ret);
951 g_strfreev(args);
953 return value;
956 uint8_t qtest_readb(QTestState *s, uint64_t addr)
958 return qtest_read(s, "readb", addr);
961 uint16_t qtest_readw(QTestState *s, uint64_t addr)
963 return qtest_read(s, "readw", addr);
966 uint32_t qtest_readl(QTestState *s, uint64_t addr)
968 return qtest_read(s, "readl", addr);
971 uint64_t qtest_readq(QTestState *s, uint64_t addr)
973 return qtest_read(s, "readq", addr);
976 static int hex2nib(char ch)
978 if (ch >= '0' && ch <= '9') {
979 return ch - '0';
980 } else if (ch >= 'a' && ch <= 'f') {
981 return 10 + (ch - 'a');
982 } else if (ch >= 'A' && ch <= 'F') {
983 return 10 + (ch - 'a');
984 } else {
985 return -1;
989 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
991 uint8_t *ptr = data;
992 gchar **args;
993 size_t i;
995 if (!size) {
996 return;
999 qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
1000 args = qtest_rsp(s, 2);
1002 for (i = 0; i < size; i++) {
1003 ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
1004 ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
1007 g_strfreev(args);
1010 uint64_t qtest_rtas_call(QTestState *s, const char *name,
1011 uint32_t nargs, uint64_t args,
1012 uint32_t nret, uint64_t ret)
1014 qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n",
1015 name, nargs, args, nret, ret);
1016 qtest_rsp(s, 0);
1017 return 0;
1020 void qtest_add_func(const char *str, void (*fn)(void))
1022 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1023 g_test_add_func(path, fn);
1024 g_free(path);
1027 void qtest_add_data_func_full(const char *str, void *data,
1028 void (*fn)(const void *),
1029 GDestroyNotify data_free_func)
1031 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1032 g_test_add_data_func_full(path, data, fn, data_free_func);
1033 g_free(path);
1036 void qtest_add_data_func(const char *str, const void *data,
1037 void (*fn)(const void *))
1039 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1040 g_test_add_data_func(path, data, fn);
1041 g_free(path);
1044 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1046 gchar *bdata;
1048 bdata = g_base64_encode(data, size);
1049 qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
1050 socket_send(s->fd, bdata, strlen(bdata));
1051 socket_send(s->fd, "\n", 1);
1052 qtest_rsp(s, 0);
1053 g_free(bdata);
1056 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
1058 gchar **args;
1059 size_t len;
1061 qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
1062 args = qtest_rsp(s, 2);
1064 g_base64_decode_inplace(args[1], &len);
1065 if (size != len) {
1066 fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
1067 size, len);
1068 len = MIN(len, size);
1071 memcpy(data, args[1], len);
1072 g_strfreev(args);
1075 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1077 const uint8_t *ptr = data;
1078 size_t i;
1079 char *enc;
1081 if (!size) {
1082 return;
1085 enc = g_malloc(2 * size + 1);
1087 for (i = 0; i < size; i++) {
1088 sprintf(&enc[i * 2], "%02x", ptr[i]);
1091 qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
1092 qtest_rsp(s, 0);
1093 g_free(enc);
1096 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
1098 qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
1099 qtest_rsp(s, 0);
1102 QDict *qmp(const char *fmt, ...)
1104 va_list ap;
1105 QDict *response;
1107 va_start(ap, fmt);
1108 response = qtest_vqmp(global_qtest, fmt, ap);
1109 va_end(ap);
1110 return response;
1113 void qmp_assert_success(const char *fmt, ...)
1115 va_list ap;
1116 QDict *response;
1118 va_start(ap, fmt);
1119 response = qtest_vqmp(global_qtest, fmt, ap);
1120 va_end(ap);
1122 g_assert(response);
1123 if (!qdict_haskey(response, "return")) {
1124 QString *s = qobject_to_json_pretty(QOBJECT(response));
1125 g_test_message("%s", qstring_get_str(s));
1126 qobject_unref(s);
1128 g_assert(qdict_haskey(response, "return"));
1129 qobject_unref(response);
1132 char *hmp(const char *fmt, ...)
1134 va_list ap;
1135 char *ret;
1137 va_start(ap, fmt);
1138 ret = qtest_vhmp(global_qtest, fmt, ap);
1139 va_end(ap);
1140 return ret;
1143 bool qtest_big_endian(QTestState *s)
1145 return s->big_endian;
1148 static bool qtest_check_machine_version(const char *mname, const char *basename,
1149 int major, int minor)
1151 char *newname;
1152 bool is_equal;
1154 newname = g_strdup_printf("%s-%i.%i", basename, major, minor);
1155 is_equal = g_str_equal(mname, newname);
1156 g_free(newname);
1158 return is_equal;
1161 static bool qtest_is_old_versioned_machine(const char *mname)
1163 const char *dash = strrchr(mname, '-');
1164 const char *dot = strrchr(mname, '.');
1165 const char *chr;
1166 char *bname;
1167 const int major = QEMU_VERSION_MAJOR;
1168 const int minor = QEMU_VERSION_MINOR;
1169 bool res = false;
1171 if (dash && dot && dot > dash) {
1172 for (chr = dash + 1; *chr; chr++) {
1173 if (!qemu_isdigit(*chr) && *chr != '.') {
1174 return false;
1178 * Now check if it is one of the latest versions. Check major + 1
1179 * and minor + 1 versions as well, since they might already exist
1180 * in the development branch.
1182 bname = g_strdup(mname);
1183 bname[dash - mname] = 0;
1184 res = !qtest_check_machine_version(mname, bname, major + 1, 0) &&
1185 !qtest_check_machine_version(mname, bname, major, minor + 1) &&
1186 !qtest_check_machine_version(mname, bname, major, minor);
1187 g_free(bname);
1190 return res;
1193 void qtest_cb_for_every_machine(void (*cb)(const char *machine),
1194 bool skip_old_versioned)
1196 QDict *response, *minfo;
1197 QList *list;
1198 const QListEntry *p;
1199 QObject *qobj;
1200 QString *qstr;
1201 const char *mname;
1203 qtest_start("-machine none");
1204 response = qmp("{ 'execute': 'query-machines' }");
1205 g_assert(response);
1206 list = qdict_get_qlist(response, "return");
1207 g_assert(list);
1209 for (p = qlist_first(list); p; p = qlist_next(p)) {
1210 minfo = qobject_to(QDict, qlist_entry_obj(p));
1211 g_assert(minfo);
1212 qobj = qdict_get(minfo, "name");
1213 g_assert(qobj);
1214 qstr = qobject_to(QString, qobj);
1215 g_assert(qstr);
1216 mname = qstring_get_str(qstr);
1217 if (!skip_old_versioned || !qtest_is_old_versioned_machine(mname)) {
1218 cb(mname);
1222 qtest_end();
1223 qobject_unref(response);
1226 QDict *qtest_qmp_receive_success(QTestState *s,
1227 void (*event_cb)(void *opaque,
1228 const char *event,
1229 QDict *data),
1230 void *opaque)
1232 QDict *response, *ret, *data;
1233 const char *event;
1235 for (;;) {
1236 response = qtest_qmp_receive(s);
1237 g_assert(!qdict_haskey(response, "error"));
1238 ret = qdict_get_qdict(response, "return");
1239 if (ret) {
1240 break;
1242 event = qdict_get_str(response, "event");
1243 data = qdict_get_qdict(response, "data");
1244 if (event_cb) {
1245 event_cb(opaque, event, data);
1247 qobject_unref(response);
1250 qobject_ref(ret);
1251 qobject_unref(response);
1252 return ret;
1256 * Generic hot-plugging test via the device_add QMP command.
1258 void qtest_qmp_device_add(const char *driver, const char *id,
1259 const char *fmt, ...)
1261 QDict *args, *response;
1262 va_list ap;
1264 va_start(ap, fmt);
1265 args = qdict_from_vjsonf_nofail(fmt, ap);
1266 va_end(ap);
1268 g_assert(!qdict_haskey(args, "driver") && !qdict_haskey(args, "id"));
1269 qdict_put_str(args, "driver", driver);
1270 qdict_put_str(args, "id", id);
1272 response = qmp("{'execute': 'device_add', 'arguments': %p}", args);
1273 g_assert(response);
1274 g_assert(!qdict_haskey(response, "event")); /* We don't expect any events */
1275 g_assert(!qdict_haskey(response, "error"));
1276 qobject_unref(response);
1279 static void device_deleted_cb(void *opaque, const char *name, QDict *data)
1281 bool *got_event = opaque;
1283 g_assert_cmpstr(name, ==, "DEVICE_DELETED");
1284 *got_event = true;
1288 * Generic hot-unplugging test via the device_del QMP command.
1289 * Device deletion will get one response and one event. For example:
1291 * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1293 * will get this one:
1295 * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1296 * "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1297 * "path": "/machine/peripheral/scsi-hd"}}
1299 * and this one:
1301 * {"return": {}}
1303 * But the order of arrival may vary - so we've got to detect both.
1305 void qtest_qmp_device_del(const char *id)
1307 bool got_event = false;
1308 QDict *rsp;
1310 qtest_qmp_send(global_qtest,
1311 "{'execute': 'device_del', 'arguments': {'id': %s}}",
1312 id);
1313 rsp = qtest_qmp_receive_success(global_qtest, device_deleted_cb,
1314 &got_event);
1315 qobject_unref(rsp);
1316 if (!got_event) {
1317 rsp = qtest_qmp_receive(global_qtest);
1318 g_assert_cmpstr(qdict_get_try_str(rsp, "event"),
1319 ==, "DEVICE_DELETED");
1320 qobject_unref(rsp);
1324 bool qmp_rsp_is_err(QDict *rsp)
1326 QDict *error = qdict_get_qdict(rsp, "error");
1327 qobject_unref(rsp);
1328 return !!error;
1331 void qmp_assert_error_class(QDict *rsp, const char *class)
1333 QDict *error = qdict_get_qdict(rsp, "error");
1335 g_assert_cmpstr(qdict_get_try_str(error, "class"), ==, class);
1336 g_assert_nonnull(qdict_get_try_str(error, "desc"));
1337 g_assert(!qdict_haskey(rsp, "return"));
1339 qobject_unref(rsp);