blockjob: add AioContext attached callback
[qemu/ar7.git] / tests / libqtest.c
blobeb00f1392bad081e62f1a6ecbd1a0de65f8f8868
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"
18 #include "libqtest.h"
20 #include <sys/socket.h>
21 #include <sys/wait.h>
22 #include <sys/un.h>
24 #include "qapi/qmp/json-parser.h"
25 #include "qapi/qmp/json-streamer.h"
26 #include "qapi/qmp/qjson.h"
28 #define MAX_IRQ 256
29 #define SOCKET_TIMEOUT 50
31 QTestState *global_qtest;
33 struct QTestState
35 int fd;
36 int qmp_fd;
37 bool irq_level[MAX_IRQ];
38 GString *rx;
39 pid_t qemu_pid; /* our child QEMU process */
42 static GHookList abrt_hooks;
43 static GList *qtest_instances;
44 static struct sigaction sigact_old;
46 #define g_assert_no_errno(ret) do { \
47 g_assert_cmpint(ret, !=, -1); \
48 } while (0)
50 static int init_socket(const char *socket_path)
52 struct sockaddr_un addr;
53 int sock;
54 int ret;
56 sock = socket(PF_UNIX, SOCK_STREAM, 0);
57 g_assert_no_errno(sock);
59 addr.sun_family = AF_UNIX;
60 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
61 qemu_set_cloexec(sock);
63 do {
64 ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
65 } while (ret == -1 && errno == EINTR);
66 g_assert_no_errno(ret);
67 ret = listen(sock, 1);
68 g_assert_no_errno(ret);
70 return sock;
73 static int socket_accept(int sock)
75 struct sockaddr_un addr;
76 socklen_t addrlen;
77 int ret;
78 struct timeval timeout = { .tv_sec = SOCKET_TIMEOUT,
79 .tv_usec = 0 };
81 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *)&timeout,
82 sizeof(timeout));
84 do {
85 addrlen = sizeof(addr);
86 ret = accept(sock, (struct sockaddr *)&addr, &addrlen);
87 } while (ret == -1 && errno == EINTR);
88 if (ret == -1) {
89 fprintf(stderr, "%s failed: %s\n", __func__, strerror(errno));
91 close(sock);
93 return ret;
96 static void kill_qemu(QTestState *s)
98 if (s->qemu_pid != -1) {
99 kill(s->qemu_pid, SIGTERM);
100 waitpid(s->qemu_pid, NULL, 0);
104 static void kill_qemu_hook_func(void *s)
106 kill_qemu(s);
109 static void sigabrt_handler(int signo)
111 g_hook_list_invoke(&abrt_hooks, FALSE);
114 static void setup_sigabrt_handler(void)
116 struct sigaction sigact;
118 /* Catch SIGABRT to clean up on g_assert() failure */
119 sigact = (struct sigaction){
120 .sa_handler = sigabrt_handler,
121 .sa_flags = SA_RESETHAND,
123 sigemptyset(&sigact.sa_mask);
124 sigaction(SIGABRT, &sigact, &sigact_old);
127 static void cleanup_sigabrt_handler(void)
129 sigaction(SIGABRT, &sigact_old, NULL);
132 void qtest_add_abrt_handler(GHookFunc fn, const void *data)
134 GHook *hook;
136 /* Only install SIGABRT handler once */
137 if (!abrt_hooks.is_setup) {
138 g_hook_list_init(&abrt_hooks, sizeof(GHook));
139 setup_sigabrt_handler();
142 hook = g_hook_alloc(&abrt_hooks);
143 hook->func = fn;
144 hook->data = (void *)data;
146 g_hook_prepend(&abrt_hooks, hook);
149 QTestState *qtest_init(const char *extra_args)
151 QTestState *s;
152 int sock, qmpsock, i;
153 gchar *socket_path;
154 gchar *qmp_socket_path;
155 gchar *command;
156 const char *qemu_binary;
158 qemu_binary = getenv("QTEST_QEMU_BINARY");
159 g_assert(qemu_binary != NULL);
161 s = g_malloc(sizeof(*s));
163 socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
164 qmp_socket_path = g_strdup_printf("/tmp/qtest-%d.qmp", getpid());
166 sock = init_socket(socket_path);
167 qmpsock = init_socket(qmp_socket_path);
169 qtest_add_abrt_handler(kill_qemu_hook_func, s);
171 s->qemu_pid = fork();
172 if (s->qemu_pid == 0) {
173 setenv("QEMU_AUDIO_DRV", "none", true);
174 command = g_strdup_printf("exec %s "
175 "-qtest unix:%s,nowait "
176 "-qtest-log %s "
177 "-qmp unix:%s,nowait "
178 "-machine accel=qtest "
179 "-display none "
180 "%s", qemu_binary, socket_path,
181 getenv("QTEST_LOG") ? "/dev/fd/2" : "/dev/null",
182 qmp_socket_path,
183 extra_args ?: "");
184 execlp("/bin/sh", "sh", "-c", command, NULL);
185 exit(1);
188 s->fd = socket_accept(sock);
189 if (s->fd >= 0) {
190 s->qmp_fd = socket_accept(qmpsock);
192 unlink(socket_path);
193 unlink(qmp_socket_path);
194 g_free(socket_path);
195 g_free(qmp_socket_path);
197 g_assert(s->fd >= 0 && s->qmp_fd >= 0);
199 s->rx = g_string_new("");
200 for (i = 0; i < MAX_IRQ; i++) {
201 s->irq_level[i] = false;
204 /* Read the QMP greeting and then do the handshake */
205 qtest_qmp_discard_response(s, "");
206 qtest_qmp_discard_response(s, "{ 'execute': 'qmp_capabilities' }");
208 if (getenv("QTEST_STOP")) {
209 kill(s->qemu_pid, SIGSTOP);
212 return s;
215 void qtest_quit(QTestState *s)
217 qtest_instances = g_list_remove(qtest_instances, s);
218 g_hook_destroy_link(&abrt_hooks, g_hook_find_data(&abrt_hooks, TRUE, s));
220 /* Uninstall SIGABRT handler on last instance */
221 if (!qtest_instances) {
222 cleanup_sigabrt_handler();
225 kill_qemu(s);
226 close(s->fd);
227 close(s->qmp_fd);
228 g_string_free(s->rx, true);
229 g_free(s);
232 static void socket_send(int fd, const char *buf, size_t size)
234 size_t offset;
236 offset = 0;
237 while (offset < size) {
238 ssize_t len;
240 len = write(fd, buf + offset, size - offset);
241 if (len == -1 && errno == EINTR) {
242 continue;
245 g_assert_no_errno(len);
246 g_assert_cmpint(len, >, 0);
248 offset += len;
252 static void socket_sendf(int fd, const char *fmt, va_list ap)
254 gchar *str = g_strdup_vprintf(fmt, ap);
255 size_t size = strlen(str);
257 socket_send(fd, str, size);
258 g_free(str);
261 static void GCC_FMT_ATTR(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...)
263 va_list ap;
265 va_start(ap, fmt);
266 socket_sendf(s->fd, fmt, ap);
267 va_end(ap);
270 static GString *qtest_recv_line(QTestState *s)
272 GString *line;
273 size_t offset;
274 char *eol;
276 while ((eol = strchr(s->rx->str, '\n')) == NULL) {
277 ssize_t len;
278 char buffer[1024];
280 len = read(s->fd, buffer, sizeof(buffer));
281 if (len == -1 && errno == EINTR) {
282 continue;
285 if (len == -1 || len == 0) {
286 fprintf(stderr, "Broken pipe\n");
287 exit(1);
290 g_string_append_len(s->rx, buffer, len);
293 offset = eol - s->rx->str;
294 line = g_string_new_len(s->rx->str, offset);
295 g_string_erase(s->rx, 0, offset + 1);
297 return line;
300 static gchar **qtest_rsp(QTestState *s, int expected_args)
302 GString *line;
303 gchar **words;
304 int i;
306 redo:
307 line = qtest_recv_line(s);
308 words = g_strsplit(line->str, " ", 0);
309 g_string_free(line, TRUE);
311 if (strcmp(words[0], "IRQ") == 0) {
312 int irq;
314 g_assert(words[1] != NULL);
315 g_assert(words[2] != NULL);
317 irq = strtoul(words[2], NULL, 0);
318 g_assert_cmpint(irq, >=, 0);
319 g_assert_cmpint(irq, <, MAX_IRQ);
321 if (strcmp(words[1], "raise") == 0) {
322 s->irq_level[irq] = true;
323 } else {
324 s->irq_level[irq] = false;
327 g_strfreev(words);
328 goto redo;
331 g_assert(words[0] != NULL);
332 g_assert_cmpstr(words[0], ==, "OK");
334 if (expected_args) {
335 for (i = 0; i < expected_args; i++) {
336 g_assert(words[i] != NULL);
338 } else {
339 g_strfreev(words);
342 return words;
345 typedef struct {
346 JSONMessageParser parser;
347 QDict *response;
348 } QMPResponseParser;
350 static void qmp_response(JSONMessageParser *parser, GQueue *tokens)
352 QMPResponseParser *qmp = container_of(parser, QMPResponseParser, parser);
353 QObject *obj;
355 obj = json_parser_parse(tokens, NULL);
356 if (!obj) {
357 fprintf(stderr, "QMP JSON response parsing failed\n");
358 exit(1);
361 g_assert(qobject_type(obj) == QTYPE_QDICT);
362 g_assert(!qmp->response);
363 qmp->response = (QDict *)obj;
366 QDict *qmp_fd_receive(int fd)
368 QMPResponseParser qmp;
369 bool log = getenv("QTEST_LOG") != NULL;
371 qmp.response = NULL;
372 json_message_parser_init(&qmp.parser, qmp_response);
373 while (!qmp.response) {
374 ssize_t len;
375 char c;
377 len = read(fd, &c, 1);
378 if (len == -1 && errno == EINTR) {
379 continue;
382 if (len == -1 || len == 0) {
383 fprintf(stderr, "Broken pipe\n");
384 exit(1);
387 if (log) {
388 len = write(2, &c, 1);
390 json_message_parser_feed(&qmp.parser, &c, 1);
392 json_message_parser_destroy(&qmp.parser);
394 return qmp.response;
397 QDict *qtest_qmp_receive(QTestState *s)
399 return qmp_fd_receive(s->qmp_fd);
403 * Allow users to send a message without waiting for the reply,
404 * in the case that they choose to discard all replies up until
405 * a particular EVENT is received.
407 void qmp_fd_sendv(int fd, const char *fmt, va_list ap)
409 va_list ap_copy;
410 QObject *qobj;
412 /* Going through qobject ensures we escape strings properly.
413 * This seemingly unnecessary copy is required in case va_list
414 * is an array type.
416 va_copy(ap_copy, ap);
417 qobj = qobject_from_jsonv(fmt, &ap_copy);
418 va_end(ap_copy);
420 /* No need to send anything for an empty QObject. */
421 if (qobj) {
422 int log = getenv("QTEST_LOG") != NULL;
423 QString *qstr = qobject_to_json(qobj);
424 const char *str = qstring_get_str(qstr);
425 size_t size = qstring_get_length(qstr);
427 if (log) {
428 fprintf(stderr, "%s", str);
430 /* Send QMP request */
431 socket_send(fd, str, size);
433 QDECREF(qstr);
434 qobject_decref(qobj);
438 void qtest_async_qmpv(QTestState *s, const char *fmt, va_list ap)
440 qmp_fd_sendv(s->qmp_fd, fmt, ap);
443 QDict *qmp_fdv(int fd, const char *fmt, va_list ap)
445 qmp_fd_sendv(fd, fmt, ap);
447 return qmp_fd_receive(fd);
450 QDict *qtest_qmpv(QTestState *s, const char *fmt, va_list ap)
452 qtest_async_qmpv(s, fmt, ap);
454 /* Receive reply */
455 return qtest_qmp_receive(s);
458 QDict *qmp_fd(int fd, const char *fmt, ...)
460 va_list ap;
461 QDict *response;
463 va_start(ap, fmt);
464 response = qmp_fdv(fd, fmt, ap);
465 va_end(ap);
466 return response;
469 void qmp_fd_send(int fd, const char *fmt, ...)
471 va_list ap;
473 va_start(ap, fmt);
474 qmp_fd_sendv(fd, fmt, ap);
475 va_end(ap);
478 QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
480 va_list ap;
481 QDict *response;
483 va_start(ap, fmt);
484 response = qtest_qmpv(s, fmt, ap);
485 va_end(ap);
486 return response;
489 void qtest_async_qmp(QTestState *s, const char *fmt, ...)
491 va_list ap;
493 va_start(ap, fmt);
494 qtest_async_qmpv(s, fmt, ap);
495 va_end(ap);
498 void qtest_qmpv_discard_response(QTestState *s, const char *fmt, va_list ap)
500 QDict *response = qtest_qmpv(s, fmt, ap);
501 QDECREF(response);
504 void qtest_qmp_discard_response(QTestState *s, const char *fmt, ...)
506 va_list ap;
507 QDict *response;
509 va_start(ap, fmt);
510 response = qtest_qmpv(s, fmt, ap);
511 va_end(ap);
512 QDECREF(response);
515 void qtest_qmp_eventwait(QTestState *s, const char *event)
517 QDict *response;
519 for (;;) {
520 response = qtest_qmp_receive(s);
521 if ((qdict_haskey(response, "event")) &&
522 (strcmp(qdict_get_str(response, "event"), event) == 0)) {
523 QDECREF(response);
524 break;
526 QDECREF(response);
530 char *qtest_hmpv(QTestState *s, const char *fmt, va_list ap)
532 char *cmd;
533 QDict *resp;
534 char *ret;
536 cmd = g_strdup_vprintf(fmt, ap);
537 resp = qtest_qmp(s, "{'execute': 'human-monitor-command',"
538 " 'arguments': {'command-line': %s}}",
539 cmd);
540 ret = g_strdup(qdict_get_try_str(resp, "return"));
541 g_assert(ret);
542 QDECREF(resp);
543 g_free(cmd);
544 return ret;
547 char *qtest_hmp(QTestState *s, const char *fmt, ...)
549 va_list ap;
550 char *ret;
552 va_start(ap, fmt);
553 ret = qtest_hmpv(s, fmt, ap);
554 va_end(ap);
555 return ret;
558 const char *qtest_get_arch(void)
560 const char *qemu = getenv("QTEST_QEMU_BINARY");
561 g_assert(qemu != NULL);
562 const char *end = strrchr(qemu, '/');
564 return end + strlen("/qemu-system-");
567 bool qtest_get_irq(QTestState *s, int num)
569 /* dummy operation in order to make sure irq is up to date */
570 qtest_inb(s, 0);
572 return s->irq_level[num];
575 static int64_t qtest_clock_rsp(QTestState *s)
577 gchar **words;
578 int64_t clock;
579 words = qtest_rsp(s, 2);
580 clock = g_ascii_strtoll(words[1], NULL, 0);
581 g_strfreev(words);
582 return clock;
585 int64_t qtest_clock_step_next(QTestState *s)
587 qtest_sendf(s, "clock_step\n");
588 return qtest_clock_rsp(s);
591 int64_t qtest_clock_step(QTestState *s, int64_t step)
593 qtest_sendf(s, "clock_step %"PRIi64"\n", step);
594 return qtest_clock_rsp(s);
597 int64_t qtest_clock_set(QTestState *s, int64_t val)
599 qtest_sendf(s, "clock_set %"PRIi64"\n", val);
600 return qtest_clock_rsp(s);
603 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
605 qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
606 qtest_rsp(s, 0);
609 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
611 qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
612 qtest_rsp(s, 0);
615 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
617 qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
618 qtest_rsp(s, 0);
621 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
623 qtest_out(s, "outb", addr, value);
626 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
628 qtest_out(s, "outw", addr, value);
631 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
633 qtest_out(s, "outl", addr, value);
636 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
638 gchar **args;
639 uint32_t value;
641 qtest_sendf(s, "%s 0x%x\n", cmd, addr);
642 args = qtest_rsp(s, 2);
643 value = strtoul(args[1], NULL, 0);
644 g_strfreev(args);
646 return value;
649 uint8_t qtest_inb(QTestState *s, uint16_t addr)
651 return qtest_in(s, "inb", addr);
654 uint16_t qtest_inw(QTestState *s, uint16_t addr)
656 return qtest_in(s, "inw", addr);
659 uint32_t qtest_inl(QTestState *s, uint16_t addr)
661 return qtest_in(s, "inl", addr);
664 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
665 uint64_t value)
667 qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
668 qtest_rsp(s, 0);
671 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
673 qtest_write(s, "writeb", addr, value);
676 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
678 qtest_write(s, "writew", addr, value);
681 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
683 qtest_write(s, "writel", addr, value);
686 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
688 qtest_write(s, "writeq", addr, value);
691 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
693 gchar **args;
694 uint64_t value;
696 qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
697 args = qtest_rsp(s, 2);
698 value = strtoull(args[1], NULL, 0);
699 g_strfreev(args);
701 return value;
704 uint8_t qtest_readb(QTestState *s, uint64_t addr)
706 return qtest_read(s, "readb", addr);
709 uint16_t qtest_readw(QTestState *s, uint64_t addr)
711 return qtest_read(s, "readw", addr);
714 uint32_t qtest_readl(QTestState *s, uint64_t addr)
716 return qtest_read(s, "readl", addr);
719 uint64_t qtest_readq(QTestState *s, uint64_t addr)
721 return qtest_read(s, "readq", addr);
724 static int hex2nib(char ch)
726 if (ch >= '0' && ch <= '9') {
727 return ch - '0';
728 } else if (ch >= 'a' && ch <= 'f') {
729 return 10 + (ch - 'a');
730 } else if (ch >= 'A' && ch <= 'F') {
731 return 10 + (ch - 'a');
732 } else {
733 return -1;
737 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
739 uint8_t *ptr = data;
740 gchar **args;
741 size_t i;
743 qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
744 args = qtest_rsp(s, 2);
746 for (i = 0; i < size; i++) {
747 ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
748 ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
751 g_strfreev(args);
754 void qtest_add_func(const char *str, void (*fn)(void))
756 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
757 g_test_add_func(path, fn);
758 g_free(path);
761 void qtest_add_data_func(const char *str, const void *data,
762 void (*fn)(const void *))
764 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
765 g_test_add_data_func(path, data, fn);
766 g_free(path);
769 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
771 gchar *bdata;
773 bdata = g_base64_encode(data, size);
774 qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
775 socket_send(s->fd, bdata, strlen(bdata));
776 socket_send(s->fd, "\n", 1);
777 qtest_rsp(s, 0);
778 g_free(bdata);
781 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
783 gchar **args;
784 size_t len;
786 qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
787 args = qtest_rsp(s, 2);
789 g_base64_decode_inplace(args[1], &len);
790 if (size != len) {
791 fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
792 size, len);
793 len = MIN(len, size);
796 memcpy(data, args[1], len);
797 g_strfreev(args);
800 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
802 const uint8_t *ptr = data;
803 size_t i;
804 char *enc = g_malloc(2 * size + 1);
806 for (i = 0; i < size; i++) {
807 sprintf(&enc[i * 2], "%02x", ptr[i]);
810 qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
811 qtest_rsp(s, 0);
812 g_free(enc);
815 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
817 qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
818 qtest_rsp(s, 0);
821 QDict *qmp(const char *fmt, ...)
823 va_list ap;
824 QDict *response;
826 va_start(ap, fmt);
827 response = qtest_qmpv(global_qtest, fmt, ap);
828 va_end(ap);
829 return response;
832 void qmp_async(const char *fmt, ...)
834 va_list ap;
836 va_start(ap, fmt);
837 qtest_async_qmpv(global_qtest, fmt, ap);
838 va_end(ap);
841 void qmp_discard_response(const char *fmt, ...)
843 va_list ap;
845 va_start(ap, fmt);
846 qtest_qmpv_discard_response(global_qtest, fmt, ap);
847 va_end(ap);
849 char *hmp(const char *fmt, ...)
851 va_list ap;
852 char *ret;
854 va_start(ap, fmt);
855 ret = qtest_hmpv(global_qtest, fmt, ap);
856 va_end(ap);
857 return ret;
860 bool qtest_big_endian(void)
862 const char *arch = qtest_get_arch();
863 int i;
865 static const struct {
866 const char *arch;
867 bool big_endian;
868 } endianness[] = {
869 { "aarch64", false },
870 { "alpha", false },
871 { "arm", false },
872 { "cris", false },
873 { "i386", false },
874 { "lm32", true },
875 { "m68k", true },
876 { "microblaze", true },
877 { "microblazeel", false },
878 { "mips", true },
879 { "mips64", true },
880 { "mips64el", false },
881 { "mipsel", false },
882 { "moxie", true },
883 { "or32", true },
884 { "ppc", true },
885 { "ppc64", true },
886 { "ppcemb", true },
887 { "s390x", true },
888 { "sh4", false },
889 { "sh4eb", true },
890 { "sparc", true },
891 { "sparc64", true },
892 { "unicore32", false },
893 { "x86_64", false },
894 { "xtensa", false },
895 { "xtensaeb", true },
899 for (i = 0; endianness[i].arch; i++) {
900 if (strcmp(endianness[i].arch, arch) == 0) {
901 return endianness[i].big_endian;
905 return false;