compiler: remove GNUC check
[qemu/ar7.git] / tests / qtest / libqtest.c
blobe49f3a1e45f4cd96279241fdb2bbe231029ab922
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 "libqos/libqtest.h"
24 #include "qemu-common.h"
25 #include "qemu/ctype.h"
26 #include "qemu/cutils.h"
27 #include "qapi/error.h"
28 #include "qapi/qmp/json-parser.h"
29 #include "qapi/qmp/qdict.h"
30 #include "qapi/qmp/qjson.h"
31 #include "qapi/qmp/qlist.h"
32 #include "qapi/qmp/qstring.h"
34 #define MAX_IRQ 256
35 #define SOCKET_TIMEOUT 50
36 #define SOCKET_MAX_FDS 16
39 typedef void (*QTestSendFn)(QTestState *s, const char *buf);
40 typedef void (*ExternalSendFn)(void *s, const char *buf);
41 typedef GString* (*QTestRecvFn)(QTestState *);
43 typedef struct QTestClientTransportOps {
44 QTestSendFn send; /* for sending qtest commands */
47 * use external_send to send qtest command strings through functions which
48 * do not accept a QTestState as the first parameter.
50 ExternalSendFn external_send;
52 QTestRecvFn recv_line; /* for receiving qtest command responses */
53 } QTestTransportOps;
55 struct QTestState
57 int fd;
58 int qmp_fd;
59 pid_t qemu_pid; /* our child QEMU process */
60 int wstatus;
61 int expected_status;
62 bool big_endian;
63 bool irq_level[MAX_IRQ];
64 GString *rx;
65 QTestTransportOps ops;
66 GList *pending_events;
69 static GHookList abrt_hooks;
70 static struct sigaction sigact_old;
72 static int qtest_query_target_endianness(QTestState *s);
74 static void qtest_client_socket_send(QTestState*, const char *buf);
75 static void socket_send(int fd, const char *buf, size_t size);
77 static GString *qtest_client_socket_recv_line(QTestState *);
79 static void qtest_client_set_tx_handler(QTestState *s, QTestSendFn send);
80 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv);
82 static int init_socket(const char *socket_path)
84 struct sockaddr_un addr;
85 int sock;
86 int ret;
88 sock = socket(PF_UNIX, SOCK_STREAM, 0);
89 g_assert_cmpint(sock, !=, -1);
91 addr.sun_family = AF_UNIX;
92 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
93 qemu_set_cloexec(sock);
95 do {
96 ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
97 } while (ret == -1 && errno == EINTR);
98 g_assert_cmpint(ret, !=, -1);
99 ret = listen(sock, 1);
100 g_assert_cmpint(ret, !=, -1);
102 return sock;
105 static int socket_accept(int sock)
107 struct sockaddr_un addr;
108 socklen_t addrlen;
109 int ret;
110 struct timeval timeout = { .tv_sec = SOCKET_TIMEOUT,
111 .tv_usec = 0 };
113 if (qemu_setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
114 (void *)&timeout, sizeof(timeout))) {
115 fprintf(stderr, "%s failed to set SO_RCVTIMEO: %s\n",
116 __func__, strerror(errno));
117 close(sock);
118 return -1;
121 do {
122 addrlen = sizeof(addr);
123 ret = accept(sock, (struct sockaddr *)&addr, &addrlen);
124 } while (ret == -1 && errno == EINTR);
125 if (ret == -1) {
126 fprintf(stderr, "%s failed: %s\n", __func__, strerror(errno));
128 close(sock);
130 return ret;
133 bool qtest_probe_child(QTestState *s)
135 pid_t pid = s->qemu_pid;
137 if (pid != -1) {
138 pid = waitpid(pid, &s->wstatus, WNOHANG);
139 if (pid == 0) {
140 return true;
142 s->qemu_pid = -1;
144 return false;
147 void qtest_set_expected_status(QTestState *s, int status)
149 s->expected_status = status;
152 static void kill_qemu(QTestState *s)
154 pid_t pid = s->qemu_pid;
155 int wstatus;
157 /* Skip wait if qtest_probe_child already reaped. */
158 if (pid != -1) {
159 kill(pid, SIGTERM);
160 TFR(pid = waitpid(s->qemu_pid, &s->wstatus, 0));
161 assert(pid == s->qemu_pid);
165 * Check whether qemu exited with expected exit status; anything else is
166 * fishy and should be logged with as much detail as possible.
168 wstatus = s->wstatus;
169 if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != s->expected_status) {
170 fprintf(stderr, "%s:%d: kill_qemu() tried to terminate QEMU "
171 "process but encountered exit status %d (expected %d)\n",
172 __FILE__, __LINE__, WEXITSTATUS(wstatus), s->expected_status);
173 abort();
174 } else if (WIFSIGNALED(wstatus)) {
175 int sig = WTERMSIG(wstatus);
176 const char *signame = strsignal(sig) ?: "unknown ???";
177 const char *dump = WCOREDUMP(wstatus) ? " (core dumped)" : "";
179 fprintf(stderr, "%s:%d: kill_qemu() detected QEMU death "
180 "from signal %d (%s)%s\n",
181 __FILE__, __LINE__, sig, signame, dump);
182 abort();
186 static void kill_qemu_hook_func(void *s)
188 kill_qemu(s);
191 static void sigabrt_handler(int signo)
193 g_hook_list_invoke(&abrt_hooks, FALSE);
196 static void setup_sigabrt_handler(void)
198 struct sigaction sigact;
200 /* Catch SIGABRT to clean up on g_assert() failure */
201 sigact = (struct sigaction){
202 .sa_handler = sigabrt_handler,
203 .sa_flags = SA_RESETHAND,
205 sigemptyset(&sigact.sa_mask);
206 sigaction(SIGABRT, &sigact, &sigact_old);
209 static void cleanup_sigabrt_handler(void)
211 sigaction(SIGABRT, &sigact_old, NULL);
214 void qtest_add_abrt_handler(GHookFunc fn, const void *data)
216 GHook *hook;
218 /* Only install SIGABRT handler once */
219 if (!abrt_hooks.is_setup) {
220 g_hook_list_init(&abrt_hooks, sizeof(GHook));
222 setup_sigabrt_handler();
224 hook = g_hook_alloc(&abrt_hooks);
225 hook->func = fn;
226 hook->data = (void *)data;
228 g_hook_prepend(&abrt_hooks, hook);
231 static const char *qtest_qemu_binary(void)
233 const char *qemu_bin;
235 qemu_bin = getenv("QTEST_QEMU_BINARY");
236 if (!qemu_bin) {
237 fprintf(stderr, "Environment variable QTEST_QEMU_BINARY required\n");
238 exit(1);
241 return qemu_bin;
244 QTestState *qtest_init_without_qmp_handshake(const char *extra_args)
246 QTestState *s;
247 int sock, qmpsock, i;
248 gchar *socket_path;
249 gchar *qmp_socket_path;
250 gchar *command;
251 const char *qemu_binary = qtest_qemu_binary();
253 s = g_new(QTestState, 1);
255 socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
256 qmp_socket_path = g_strdup_printf("/tmp/qtest-%d.qmp", getpid());
258 /* It's possible that if an earlier test run crashed it might
259 * have left a stale unix socket lying around. Delete any
260 * stale old socket to avoid spurious test failures with
261 * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1)
263 unlink(socket_path);
264 unlink(qmp_socket_path);
266 sock = init_socket(socket_path);
267 qmpsock = init_socket(qmp_socket_path);
269 qtest_client_set_rx_handler(s, qtest_client_socket_recv_line);
270 qtest_client_set_tx_handler(s, qtest_client_socket_send);
272 qtest_add_abrt_handler(kill_qemu_hook_func, s);
274 command = g_strdup_printf("exec %s "
275 "-qtest unix:%s "
276 "-qtest-log %s "
277 "-chardev socket,path=%s,id=char0 "
278 "-mon chardev=char0,mode=control "
279 "-display none "
280 "%s"
281 " -accel qtest", qemu_binary, socket_path,
282 getenv("QTEST_LOG") ? "/dev/fd/2" : "/dev/null",
283 qmp_socket_path,
284 extra_args ?: "");
286 g_test_message("starting QEMU: %s", command);
288 s->pending_events = NULL;
289 s->wstatus = 0;
290 s->expected_status = 0;
291 s->qemu_pid = fork();
292 if (s->qemu_pid == 0) {
293 g_setenv("QEMU_AUDIO_DRV", "none", true);
294 execlp("/bin/sh", "sh", "-c", command, NULL);
295 exit(1);
298 g_free(command);
299 s->fd = socket_accept(sock);
300 if (s->fd >= 0) {
301 s->qmp_fd = socket_accept(qmpsock);
303 unlink(socket_path);
304 unlink(qmp_socket_path);
305 g_free(socket_path);
306 g_free(qmp_socket_path);
308 g_assert(s->fd >= 0 && s->qmp_fd >= 0);
310 s->rx = g_string_new("");
311 for (i = 0; i < MAX_IRQ; i++) {
312 s->irq_level[i] = false;
315 if (getenv("QTEST_STOP")) {
316 kill(s->qemu_pid, SIGSTOP);
319 /* ask endianness of the target */
321 s->big_endian = qtest_query_target_endianness(s);
323 return s;
326 QTestState *qtest_init(const char *extra_args)
328 QTestState *s = qtest_init_without_qmp_handshake(extra_args);
329 QDict *greeting;
331 /* Read the QMP greeting and then do the handshake */
332 greeting = qtest_qmp_receive(s);
333 qobject_unref(greeting);
334 qobject_unref(qtest_qmp(s, "{ 'execute': 'qmp_capabilities' }"));
336 return s;
339 QTestState *qtest_vinitf(const char *fmt, va_list ap)
341 char *args = g_strdup_vprintf(fmt, ap);
342 QTestState *s;
344 s = qtest_init(args);
345 g_free(args);
346 return s;
349 QTestState *qtest_initf(const char *fmt, ...)
351 va_list ap;
352 QTestState *s;
354 va_start(ap, fmt);
355 s = qtest_vinitf(fmt, ap);
356 va_end(ap);
357 return s;
360 QTestState *qtest_init_with_serial(const char *extra_args, int *sock_fd)
362 int sock_fd_init;
363 char *sock_path, sock_dir[] = "/tmp/qtest-serial-XXXXXX";
364 QTestState *qts;
366 g_assert_true(mkdtemp(sock_dir) != NULL);
367 sock_path = g_strdup_printf("%s/sock", sock_dir);
369 sock_fd_init = init_socket(sock_path);
371 qts = qtest_initf("-chardev socket,id=s0,path=%s -serial chardev:s0 %s",
372 sock_path, extra_args);
374 *sock_fd = socket_accept(sock_fd_init);
376 unlink(sock_path);
377 g_free(sock_path);
378 rmdir(sock_dir);
380 g_assert_true(*sock_fd >= 0);
382 return qts;
385 void qtest_quit(QTestState *s)
387 g_hook_destroy_link(&abrt_hooks, g_hook_find_data(&abrt_hooks, TRUE, s));
389 /* Uninstall SIGABRT handler on last instance */
390 cleanup_sigabrt_handler();
392 kill_qemu(s);
393 close(s->fd);
394 close(s->qmp_fd);
395 g_string_free(s->rx, true);
397 for (GList *it = s->pending_events; it != NULL; it = it->next) {
398 qobject_unref((QDict *)it->data);
401 g_list_free(s->pending_events);
403 g_free(s);
406 static void socket_send(int fd, const char *buf, size_t size)
408 size_t offset;
410 offset = 0;
411 while (offset < size) {
412 ssize_t len;
414 len = write(fd, buf + offset, size - offset);
415 if (len == -1 && errno == EINTR) {
416 continue;
419 g_assert_cmpint(len, >, 0);
421 offset += len;
425 static void qtest_client_socket_send(QTestState *s, const char *buf)
427 socket_send(s->fd, buf, strlen(buf));
430 static void GCC_FMT_ATTR(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...)
432 va_list ap;
434 va_start(ap, fmt);
435 gchar *str = g_strdup_vprintf(fmt, ap);
436 va_end(ap);
438 s->ops.send(s, str);
439 g_free(str);
442 /* Sends a message and file descriptors to the socket.
443 * It's needed for qmp-commands like getfd/add-fd */
444 static void socket_send_fds(int socket_fd, int *fds, size_t fds_num,
445 const char *buf, size_t buf_size)
447 ssize_t ret;
448 struct msghdr msg = { 0 };
449 char control[CMSG_SPACE(sizeof(int) * SOCKET_MAX_FDS)] = { 0 };
450 size_t fdsize = sizeof(int) * fds_num;
451 struct cmsghdr *cmsg;
452 struct iovec iov = { .iov_base = (char *)buf, .iov_len = buf_size };
454 msg.msg_iov = &iov;
455 msg.msg_iovlen = 1;
457 if (fds && fds_num > 0) {
458 g_assert_cmpuint(fds_num, <, SOCKET_MAX_FDS);
460 msg.msg_control = control;
461 msg.msg_controllen = CMSG_SPACE(fdsize);
463 cmsg = CMSG_FIRSTHDR(&msg);
464 cmsg->cmsg_len = CMSG_LEN(fdsize);
465 cmsg->cmsg_level = SOL_SOCKET;
466 cmsg->cmsg_type = SCM_RIGHTS;
467 memcpy(CMSG_DATA(cmsg), fds, fdsize);
470 do {
471 ret = sendmsg(socket_fd, &msg, 0);
472 } while (ret < 0 && errno == EINTR);
473 g_assert_cmpint(ret, >, 0);
476 static GString *qtest_client_socket_recv_line(QTestState *s)
478 GString *line;
479 size_t offset;
480 char *eol;
482 while ((eol = strchr(s->rx->str, '\n')) == NULL) {
483 ssize_t len;
484 char buffer[1024];
486 len = read(s->fd, buffer, sizeof(buffer));
487 if (len == -1 && errno == EINTR) {
488 continue;
491 if (len == -1 || len == 0) {
492 fprintf(stderr, "Broken pipe\n");
493 abort();
496 g_string_append_len(s->rx, buffer, len);
499 offset = eol - s->rx->str;
500 line = g_string_new_len(s->rx->str, offset);
501 g_string_erase(s->rx, 0, offset + 1);
503 return line;
506 static gchar **qtest_rsp(QTestState *s, int expected_args)
508 GString *line;
509 gchar **words;
510 int i;
512 redo:
513 line = s->ops.recv_line(s);
514 words = g_strsplit(line->str, " ", 0);
515 g_string_free(line, TRUE);
517 if (strcmp(words[0], "IRQ") == 0) {
518 long irq;
519 int ret;
521 g_assert(words[1] != NULL);
522 g_assert(words[2] != NULL);
524 ret = qemu_strtol(words[2], NULL, 0, &irq);
525 g_assert(!ret);
526 g_assert_cmpint(irq, >=, 0);
527 g_assert_cmpint(irq, <, MAX_IRQ);
529 if (strcmp(words[1], "raise") == 0) {
530 s->irq_level[irq] = true;
531 } else {
532 s->irq_level[irq] = false;
535 g_strfreev(words);
536 goto redo;
539 g_assert(words[0] != NULL);
540 g_assert_cmpstr(words[0], ==, "OK");
542 if (expected_args) {
543 for (i = 0; i < expected_args; i++) {
544 g_assert(words[i] != NULL);
546 } else {
547 g_strfreev(words);
548 words = NULL;
551 return words;
554 static int qtest_query_target_endianness(QTestState *s)
556 gchar **args;
557 int big_endian;
559 qtest_sendf(s, "endianness\n");
560 args = qtest_rsp(s, 1);
561 g_assert(strcmp(args[1], "big") == 0 || strcmp(args[1], "little") == 0);
562 big_endian = strcmp(args[1], "big") == 0;
563 g_strfreev(args);
565 return big_endian;
568 typedef struct {
569 JSONMessageParser parser;
570 QDict *response;
571 } QMPResponseParser;
573 static void qmp_response(void *opaque, QObject *obj, Error *err)
575 QMPResponseParser *qmp = opaque;
577 assert(!obj != !err);
579 if (err) {
580 error_prepend(&err, "QMP JSON response parsing failed: ");
581 error_report_err(err);
582 abort();
585 g_assert(!qmp->response);
586 qmp->response = qobject_to(QDict, obj);
587 g_assert(qmp->response);
590 QDict *qmp_fd_receive(int fd)
592 QMPResponseParser qmp;
593 bool log = getenv("QTEST_LOG") != NULL;
595 qmp.response = NULL;
596 json_message_parser_init(&qmp.parser, qmp_response, &qmp, NULL);
597 while (!qmp.response) {
598 ssize_t len;
599 char c;
601 len = read(fd, &c, 1);
602 if (len == -1 && errno == EINTR) {
603 continue;
606 if (len == -1 || len == 0) {
607 fprintf(stderr, "Broken pipe\n");
608 abort();
611 if (log) {
612 len = write(2, &c, 1);
614 json_message_parser_feed(&qmp.parser, &c, 1);
616 json_message_parser_destroy(&qmp.parser);
618 return qmp.response;
621 QDict *qtest_qmp_receive(QTestState *s)
623 while (true) {
624 QDict *response = qtest_qmp_receive_dict(s);
626 if (!qdict_get_try_str(response, "event")) {
627 return response;
629 /* Stash the event for a later consumption */
630 s->pending_events = g_list_append(s->pending_events, response);
634 QDict *qtest_qmp_receive_dict(QTestState *s)
636 return qmp_fd_receive(s->qmp_fd);
640 * Allow users to send a message without waiting for the reply,
641 * in the case that they choose to discard all replies up until
642 * a particular EVENT is received.
644 void qmp_fd_vsend_fds(int fd, int *fds, size_t fds_num,
645 const char *fmt, va_list ap)
647 QObject *qobj;
649 /* Going through qobject ensures we escape strings properly */
650 qobj = qobject_from_vjsonf_nofail(fmt, ap);
652 /* No need to send anything for an empty QObject. */
653 if (qobj) {
654 int log = getenv("QTEST_LOG") != NULL;
655 QString *qstr = qobject_to_json(qobj);
656 const char *str;
659 * BUG: QMP doesn't react to input until it sees a newline, an
660 * object, or an array. Work-around: give it a newline.
662 qstring_append_chr(qstr, '\n');
663 str = qstring_get_str(qstr);
665 if (log) {
666 fprintf(stderr, "%s", str);
668 /* Send QMP request */
669 if (fds && fds_num > 0) {
670 socket_send_fds(fd, fds, fds_num, str, qstring_get_length(qstr));
671 } else {
672 socket_send(fd, str, qstring_get_length(qstr));
675 qobject_unref(qstr);
676 qobject_unref(qobj);
680 void qmp_fd_vsend(int fd, const char *fmt, va_list ap)
682 qmp_fd_vsend_fds(fd, NULL, 0, fmt, ap);
685 void qtest_qmp_vsend_fds(QTestState *s, int *fds, size_t fds_num,
686 const char *fmt, va_list ap)
688 qmp_fd_vsend_fds(s->qmp_fd, fds, fds_num, fmt, ap);
691 void qtest_qmp_vsend(QTestState *s, const char *fmt, va_list ap)
693 qmp_fd_vsend_fds(s->qmp_fd, NULL, 0, fmt, ap);
696 QDict *qmp_fdv(int fd, const char *fmt, va_list ap)
698 qmp_fd_vsend_fds(fd, NULL, 0, fmt, ap);
700 return qmp_fd_receive(fd);
703 QDict *qtest_vqmp_fds(QTestState *s, int *fds, size_t fds_num,
704 const char *fmt, va_list ap)
706 qtest_qmp_vsend_fds(s, fds, fds_num, fmt, ap);
708 /* Receive reply */
709 return qtest_qmp_receive(s);
712 QDict *qtest_vqmp(QTestState *s, const char *fmt, va_list ap)
714 qtest_qmp_vsend(s, fmt, ap);
716 /* Receive reply */
717 return qtest_qmp_receive(s);
720 QDict *qmp_fd(int fd, const char *fmt, ...)
722 va_list ap;
723 QDict *response;
725 va_start(ap, fmt);
726 response = qmp_fdv(fd, fmt, ap);
727 va_end(ap);
728 return response;
731 void qmp_fd_send(int fd, const char *fmt, ...)
733 va_list ap;
735 va_start(ap, fmt);
736 qmp_fd_vsend(fd, fmt, ap);
737 va_end(ap);
740 QDict *qtest_qmp_fds(QTestState *s, int *fds, size_t fds_num,
741 const char *fmt, ...)
743 va_list ap;
744 QDict *response;
746 va_start(ap, fmt);
747 response = qtest_vqmp_fds(s, fds, fds_num, fmt, ap);
748 va_end(ap);
749 return response;
752 QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
754 va_list ap;
755 QDict *response;
757 va_start(ap, fmt);
758 response = qtest_vqmp(s, fmt, ap);
759 va_end(ap);
760 return response;
763 void qtest_qmp_send(QTestState *s, const char *fmt, ...)
765 va_list ap;
767 va_start(ap, fmt);
768 qtest_qmp_vsend(s, fmt, ap);
769 va_end(ap);
772 void qmp_fd_vsend_raw(int fd, const char *fmt, va_list ap)
774 bool log = getenv("QTEST_LOG") != NULL;
775 char *str = g_strdup_vprintf(fmt, ap);
777 if (log) {
778 fprintf(stderr, "%s", str);
780 socket_send(fd, str, strlen(str));
781 g_free(str);
784 void qmp_fd_send_raw(int fd, const char *fmt, ...)
786 va_list ap;
788 va_start(ap, fmt);
789 qmp_fd_vsend_raw(fd, fmt, ap);
790 va_end(ap);
793 void qtest_qmp_send_raw(QTestState *s, const char *fmt, ...)
795 va_list ap;
797 va_start(ap, fmt);
798 qmp_fd_vsend_raw(s->qmp_fd, fmt, ap);
799 va_end(ap);
802 QDict *qtest_qmp_event_ref(QTestState *s, const char *event)
804 while (s->pending_events) {
806 GList *first = s->pending_events;
807 QDict *response = (QDict *)first->data;
809 s->pending_events = g_list_delete_link(s->pending_events, first);
811 if (!strcmp(qdict_get_str(response, "event"), event)) {
812 return response;
814 qobject_unref(response);
816 return NULL;
819 QDict *qtest_qmp_eventwait_ref(QTestState *s, const char *event)
821 QDict *response = qtest_qmp_event_ref(s, event);
823 if (response) {
824 return response;
827 for (;;) {
828 response = qtest_qmp_receive_dict(s);
829 if ((qdict_haskey(response, "event")) &&
830 (strcmp(qdict_get_str(response, "event"), event) == 0)) {
831 return response;
833 qobject_unref(response);
837 void qtest_qmp_eventwait(QTestState *s, const char *event)
839 QDict *response;
841 response = qtest_qmp_eventwait_ref(s, event);
842 qobject_unref(response);
845 char *qtest_vhmp(QTestState *s, const char *fmt, va_list ap)
847 char *cmd;
848 QDict *resp;
849 char *ret;
851 cmd = g_strdup_vprintf(fmt, ap);
852 resp = qtest_qmp(s, "{'execute': 'human-monitor-command',"
853 " 'arguments': {'command-line': %s}}",
854 cmd);
855 ret = g_strdup(qdict_get_try_str(resp, "return"));
856 g_assert(ret);
857 qobject_unref(resp);
858 g_free(cmd);
859 return ret;
862 char *qtest_hmp(QTestState *s, const char *fmt, ...)
864 va_list ap;
865 char *ret;
867 va_start(ap, fmt);
868 ret = qtest_vhmp(s, fmt, ap);
869 va_end(ap);
870 return ret;
873 const char *qtest_get_arch(void)
875 const char *qemu = qtest_qemu_binary();
876 const char *end = strrchr(qemu, '-');
878 if (!end) {
879 fprintf(stderr, "Can't determine architecture from binary name.\n");
880 abort();
883 return end + 1;
886 bool qtest_get_irq(QTestState *s, int num)
888 /* dummy operation in order to make sure irq is up to date */
889 qtest_inb(s, 0);
891 return s->irq_level[num];
894 void qtest_module_load(QTestState *s, const char *prefix, const char *libname)
896 qtest_sendf(s, "module_load %s %s\n", prefix, libname);
897 qtest_rsp(s, 0);
900 static int64_t qtest_clock_rsp(QTestState *s)
902 gchar **words;
903 int64_t clock;
904 words = qtest_rsp(s, 2);
905 clock = g_ascii_strtoll(words[1], NULL, 0);
906 g_strfreev(words);
907 return clock;
910 int64_t qtest_clock_step_next(QTestState *s)
912 qtest_sendf(s, "clock_step\n");
913 return qtest_clock_rsp(s);
916 int64_t qtest_clock_step(QTestState *s, int64_t step)
918 qtest_sendf(s, "clock_step %"PRIi64"\n", step);
919 return qtest_clock_rsp(s);
922 int64_t qtest_clock_set(QTestState *s, int64_t val)
924 qtest_sendf(s, "clock_set %"PRIi64"\n", val);
925 return qtest_clock_rsp(s);
928 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
930 qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
931 qtest_rsp(s, 0);
934 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
936 qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
937 qtest_rsp(s, 0);
940 void qtest_set_irq_in(QTestState *s, const char *qom_path, const char *name,
941 int num, int level)
943 if (!name) {
944 name = "unnamed-gpio-in";
946 qtest_sendf(s, "set_irq_in %s %s %d %d\n", qom_path, name, num, level);
947 qtest_rsp(s, 0);
950 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
952 qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
953 qtest_rsp(s, 0);
956 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
958 qtest_out(s, "outb", addr, value);
961 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
963 qtest_out(s, "outw", addr, value);
966 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
968 qtest_out(s, "outl", addr, value);
971 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
973 gchar **args;
974 int ret;
975 unsigned long value;
977 qtest_sendf(s, "%s 0x%x\n", cmd, addr);
978 args = qtest_rsp(s, 2);
979 ret = qemu_strtoul(args[1], NULL, 0, &value);
980 g_assert(!ret && value <= UINT32_MAX);
981 g_strfreev(args);
983 return value;
986 uint8_t qtest_inb(QTestState *s, uint16_t addr)
988 return qtest_in(s, "inb", addr);
991 uint16_t qtest_inw(QTestState *s, uint16_t addr)
993 return qtest_in(s, "inw", addr);
996 uint32_t qtest_inl(QTestState *s, uint16_t addr)
998 return qtest_in(s, "inl", addr);
1001 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
1002 uint64_t value)
1004 qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
1005 qtest_rsp(s, 0);
1008 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
1010 qtest_write(s, "writeb", addr, value);
1013 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
1015 qtest_write(s, "writew", addr, value);
1018 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
1020 qtest_write(s, "writel", addr, value);
1023 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
1025 qtest_write(s, "writeq", addr, value);
1028 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
1030 gchar **args;
1031 int ret;
1032 uint64_t value;
1034 qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
1035 args = qtest_rsp(s, 2);
1036 ret = qemu_strtou64(args[1], NULL, 0, &value);
1037 g_assert(!ret);
1038 g_strfreev(args);
1040 return value;
1043 uint8_t qtest_readb(QTestState *s, uint64_t addr)
1045 return qtest_read(s, "readb", addr);
1048 uint16_t qtest_readw(QTestState *s, uint64_t addr)
1050 return qtest_read(s, "readw", addr);
1053 uint32_t qtest_readl(QTestState *s, uint64_t addr)
1055 return qtest_read(s, "readl", addr);
1058 uint64_t qtest_readq(QTestState *s, uint64_t addr)
1060 return qtest_read(s, "readq", addr);
1063 static int hex2nib(char ch)
1065 if (ch >= '0' && ch <= '9') {
1066 return ch - '0';
1067 } else if (ch >= 'a' && ch <= 'f') {
1068 return 10 + (ch - 'a');
1069 } else if (ch >= 'A' && ch <= 'F') {
1070 return 10 + (ch - 'a');
1071 } else {
1072 return -1;
1076 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
1078 uint8_t *ptr = data;
1079 gchar **args;
1080 size_t i;
1082 if (!size) {
1083 return;
1086 qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
1087 args = qtest_rsp(s, 2);
1089 for (i = 0; i < size; i++) {
1090 ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
1091 ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
1094 g_strfreev(args);
1097 uint64_t qtest_rtas_call(QTestState *s, const char *name,
1098 uint32_t nargs, uint64_t args,
1099 uint32_t nret, uint64_t ret)
1101 qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n",
1102 name, nargs, args, nret, ret);
1103 qtest_rsp(s, 0);
1104 return 0;
1107 void qtest_add_func(const char *str, void (*fn)(void))
1109 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1110 g_test_add_func(path, fn);
1111 g_free(path);
1114 void qtest_add_data_func_full(const char *str, void *data,
1115 void (*fn)(const void *),
1116 GDestroyNotify data_free_func)
1118 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1119 g_test_add_data_func_full(path, data, fn, data_free_func);
1120 g_free(path);
1123 void qtest_add_data_func(const char *str, const void *data,
1124 void (*fn)(const void *))
1126 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1127 g_test_add_data_func(path, data, fn);
1128 g_free(path);
1131 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1133 gchar *bdata;
1135 bdata = g_base64_encode(data, size);
1136 qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
1137 s->ops.send(s, bdata);
1138 s->ops.send(s, "\n");
1139 qtest_rsp(s, 0);
1140 g_free(bdata);
1143 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
1145 gchar **args;
1146 size_t len;
1148 qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
1149 args = qtest_rsp(s, 2);
1151 g_base64_decode_inplace(args[1], &len);
1152 if (size != len) {
1153 fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
1154 size, len);
1155 len = MIN(len, size);
1158 memcpy(data, args[1], len);
1159 g_strfreev(args);
1162 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1164 const uint8_t *ptr = data;
1165 size_t i;
1166 char *enc;
1168 if (!size) {
1169 return;
1172 enc = g_malloc(2 * size + 1);
1174 for (i = 0; i < size; i++) {
1175 sprintf(&enc[i * 2], "%02x", ptr[i]);
1178 qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
1179 qtest_rsp(s, 0);
1180 g_free(enc);
1183 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
1185 qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
1186 qtest_rsp(s, 0);
1189 void qtest_qmp_assert_success(QTestState *qts, const char *fmt, ...)
1191 va_list ap;
1192 QDict *response;
1194 va_start(ap, fmt);
1195 response = qtest_vqmp(qts, fmt, ap);
1196 va_end(ap);
1198 g_assert(response);
1199 if (!qdict_haskey(response, "return")) {
1200 QString *s = qobject_to_json_pretty(QOBJECT(response));
1201 g_test_message("%s", qstring_get_str(s));
1202 qobject_unref(s);
1204 g_assert(qdict_haskey(response, "return"));
1205 qobject_unref(response);
1208 bool qtest_big_endian(QTestState *s)
1210 return s->big_endian;
1213 static bool qtest_check_machine_version(const char *mname, const char *basename,
1214 int major, int minor)
1216 char *newname;
1217 bool is_equal;
1219 newname = g_strdup_printf("%s-%i.%i", basename, major, minor);
1220 is_equal = g_str_equal(mname, newname);
1221 g_free(newname);
1223 return is_equal;
1226 static bool qtest_is_old_versioned_machine(const char *mname)
1228 const char *dash = strrchr(mname, '-');
1229 const char *dot = strrchr(mname, '.');
1230 const char *chr;
1231 char *bname;
1232 const int major = QEMU_VERSION_MAJOR;
1233 const int minor = QEMU_VERSION_MINOR;
1234 bool res = false;
1236 if (dash && dot && dot > dash) {
1237 for (chr = dash + 1; *chr; chr++) {
1238 if (!qemu_isdigit(*chr) && *chr != '.') {
1239 return false;
1243 * Now check if it is one of the latest versions. Check major + 1
1244 * and minor + 1 versions as well, since they might already exist
1245 * in the development branch.
1247 bname = g_strdup(mname);
1248 bname[dash - mname] = 0;
1249 res = !qtest_check_machine_version(mname, bname, major + 1, 0) &&
1250 !qtest_check_machine_version(mname, bname, major, minor + 1) &&
1251 !qtest_check_machine_version(mname, bname, major, minor);
1252 g_free(bname);
1255 return res;
1258 void qtest_cb_for_every_machine(void (*cb)(const char *machine),
1259 bool skip_old_versioned)
1261 QDict *response, *minfo;
1262 QList *list;
1263 const QListEntry *p;
1264 QObject *qobj;
1265 QString *qstr;
1266 const char *mname;
1267 QTestState *qts;
1269 qts = qtest_init("-machine none");
1270 response = qtest_qmp(qts, "{ 'execute': 'query-machines' }");
1271 g_assert(response);
1272 list = qdict_get_qlist(response, "return");
1273 g_assert(list);
1275 for (p = qlist_first(list); p; p = qlist_next(p)) {
1276 minfo = qobject_to(QDict, qlist_entry_obj(p));
1277 g_assert(minfo);
1278 qobj = qdict_get(minfo, "name");
1279 g_assert(qobj);
1280 qstr = qobject_to(QString, qobj);
1281 g_assert(qstr);
1282 mname = qstring_get_str(qstr);
1283 /* Ignore machines that cannot be used for qtests */
1284 if (!memcmp("xenfv", mname, 5) || g_str_equal("xenpv", mname)) {
1285 continue;
1287 if (!skip_old_versioned || !qtest_is_old_versioned_machine(mname)) {
1288 cb(mname);
1292 qtest_quit(qts);
1293 qobject_unref(response);
1297 * Generic hot-plugging test via the device_add QMP commands.
1299 void qtest_qmp_device_add_qdict(QTestState *qts, const char *drv,
1300 const QDict *arguments)
1302 QDict *resp;
1303 QDict *args = arguments ? qdict_clone_shallow(arguments) : qdict_new();
1305 g_assert(!qdict_haskey(args, "driver"));
1306 qdict_put_str(args, "driver", drv);
1307 resp = qtest_qmp(qts, "{'execute': 'device_add', 'arguments': %p}", args);
1308 g_assert(resp);
1309 g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1310 g_assert(!qdict_haskey(resp, "error"));
1311 qobject_unref(resp);
1314 void qtest_qmp_device_add(QTestState *qts, const char *driver, const char *id,
1315 const char *fmt, ...)
1317 QDict *args;
1318 va_list ap;
1320 va_start(ap, fmt);
1321 args = qdict_from_vjsonf_nofail(fmt, ap);
1322 va_end(ap);
1324 g_assert(!qdict_haskey(args, "id"));
1325 qdict_put_str(args, "id", id);
1327 qtest_qmp_device_add_qdict(qts, driver, args);
1328 qobject_unref(args);
1333 * Generic hot-unplugging test via the device_del QMP command.
1334 * Device deletion will get one response and one event. For example:
1336 * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1338 * will get this one:
1340 * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1341 * "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1342 * "path": "/machine/peripheral/scsi-hd"}}
1344 * and this one:
1346 * {"return": {}}
1348 void qtest_qmp_device_del(QTestState *qts, const char *id)
1350 QDict *rsp;
1352 rsp = qtest_qmp(qts, "{'execute': 'device_del', 'arguments': {'id': %s}}",
1353 id);
1355 g_assert(qdict_haskey(rsp, "return"));
1356 qobject_unref(rsp);
1357 qtest_qmp_eventwait(qts, "DEVICE_DELETED");
1360 bool qmp_rsp_is_err(QDict *rsp)
1362 QDict *error = qdict_get_qdict(rsp, "error");
1363 qobject_unref(rsp);
1364 return !!error;
1367 void qmp_expect_error_and_unref(QDict *rsp, const char *class)
1369 QDict *error = qdict_get_qdict(rsp, "error");
1371 g_assert_cmpstr(qdict_get_try_str(error, "class"), ==, class);
1372 g_assert_nonnull(qdict_get_try_str(error, "desc"));
1373 g_assert(!qdict_haskey(rsp, "return"));
1375 qobject_unref(rsp);
1378 static void qtest_client_set_tx_handler(QTestState *s,
1379 QTestSendFn send)
1381 s->ops.send = send;
1383 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv)
1385 s->ops.recv_line = recv;
1387 /* A type-safe wrapper for s->send() */
1388 static void send_wrapper(QTestState *s, const char *buf)
1390 s->ops.external_send(s, buf);
1393 static GString *qtest_client_inproc_recv_line(QTestState *s)
1395 GString *line;
1396 size_t offset;
1397 char *eol;
1399 eol = strchr(s->rx->str, '\n');
1400 offset = eol - s->rx->str;
1401 line = g_string_new_len(s->rx->str, offset);
1402 g_string_erase(s->rx, 0, offset + 1);
1403 return line;
1406 QTestState *qtest_inproc_init(QTestState **s, bool log, const char* arch,
1407 void (*send)(void*, const char*))
1409 QTestState *qts;
1410 qts = g_new0(QTestState, 1);
1411 qts->pending_events = NULL;
1412 *s = qts; /* Expose qts early on, since the query endianness relies on it */
1413 qts->wstatus = 0;
1414 for (int i = 0; i < MAX_IRQ; i++) {
1415 qts->irq_level[i] = false;
1418 qtest_client_set_rx_handler(qts, qtest_client_inproc_recv_line);
1420 /* send() may not have a matching protoype, so use a type-safe wrapper */
1421 qts->ops.external_send = send;
1422 qtest_client_set_tx_handler(qts, send_wrapper);
1424 qts->big_endian = qtest_query_target_endianness(qts);
1427 * Set a dummy path for QTEST_QEMU_BINARY. Doesn't need to exist, but this
1428 * way, qtest_get_arch works for inproc qtest.
1430 gchar *bin_path = g_strconcat("/qemu-system-", arch, NULL);
1431 setenv("QTEST_QEMU_BINARY", bin_path, 0);
1432 g_free(bin_path);
1434 return qts;
1437 void qtest_client_inproc_recv(void *opaque, const char *str)
1439 QTestState *qts = *(QTestState **)opaque;
1441 if (!qts->rx) {
1442 qts->rx = g_string_new(NULL);
1444 g_string_append(qts->rx, str);
1445 return;