audio: don't use 'Yoda conditions'
[qemu/kevin.git] / tests / libqtest.c
blob98e8f4b648d54305babb264ee2b5ae950a0f8190
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 "libqtest.h"
19 #include <glib.h>
20 #include <sys/types.h>
21 #include <sys/socket.h>
22 #include <sys/wait.h>
23 #include <sys/un.h>
24 #include <inttypes.h>
25 #include <errno.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <string.h>
31 #include "qemu/compiler.h"
32 #include "qemu/osdep.h"
33 #include "qapi/qmp/json-parser.h"
34 #include "qapi/qmp/json-streamer.h"
35 #include "qapi/qmp/qjson.h"
37 #define MAX_IRQ 256
38 #define SOCKET_TIMEOUT 5
40 QTestState *global_qtest;
42 struct QTestState
44 int fd;
45 int qmp_fd;
46 bool irq_level[MAX_IRQ];
47 GString *rx;
48 pid_t qemu_pid; /* our child QEMU process */
49 struct sigaction sigact_old; /* restored on exit */
52 static GList *qtest_instances;
53 static struct sigaction sigact_old;
55 #define g_assert_no_errno(ret) do { \
56 g_assert_cmpint(ret, !=, -1); \
57 } while (0)
59 static int init_socket(const char *socket_path)
61 struct sockaddr_un addr;
62 int sock;
63 int ret;
65 sock = socket(PF_UNIX, SOCK_STREAM, 0);
66 g_assert_no_errno(sock);
68 addr.sun_family = AF_UNIX;
69 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
70 qemu_set_cloexec(sock);
72 do {
73 ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
74 } while (ret == -1 && errno == EINTR);
75 g_assert_no_errno(ret);
76 ret = listen(sock, 1);
77 g_assert_no_errno(ret);
79 return sock;
82 static int socket_accept(int sock)
84 struct sockaddr_un addr;
85 socklen_t addrlen;
86 int ret;
87 struct timeval timeout = { .tv_sec = SOCKET_TIMEOUT,
88 .tv_usec = 0 };
90 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *)&timeout,
91 sizeof(timeout));
93 do {
94 addrlen = sizeof(addr);
95 ret = accept(sock, (struct sockaddr *)&addr, &addrlen);
96 } while (ret == -1 && errno == EINTR);
97 if (ret == -1) {
98 fprintf(stderr, "%s failed: %s\n", __func__, strerror(errno));
100 close(sock);
102 return ret;
105 static void kill_qemu(QTestState *s)
107 if (s->qemu_pid != -1) {
108 kill(s->qemu_pid, SIGTERM);
109 waitpid(s->qemu_pid, NULL, 0);
113 static void sigabrt_handler(int signo)
115 GList *elem;
116 for (elem = qtest_instances; elem; elem = elem->next) {
117 kill_qemu(elem->data);
121 static void setup_sigabrt_handler(void)
123 struct sigaction sigact;
125 /* Catch SIGABRT to clean up on g_assert() failure */
126 sigact = (struct sigaction){
127 .sa_handler = sigabrt_handler,
128 .sa_flags = SA_RESETHAND,
130 sigemptyset(&sigact.sa_mask);
131 sigaction(SIGABRT, &sigact, &sigact_old);
134 static void cleanup_sigabrt_handler(void)
136 sigaction(SIGABRT, &sigact_old, NULL);
139 QTestState *qtest_init(const char *extra_args)
141 QTestState *s;
142 int sock, qmpsock, i;
143 gchar *socket_path;
144 gchar *qmp_socket_path;
145 gchar *command;
146 const char *qemu_binary;
148 qemu_binary = getenv("QTEST_QEMU_BINARY");
149 g_assert(qemu_binary != NULL);
151 s = g_malloc(sizeof(*s));
153 socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
154 qmp_socket_path = g_strdup_printf("/tmp/qtest-%d.qmp", getpid());
156 sock = init_socket(socket_path);
157 qmpsock = init_socket(qmp_socket_path);
159 /* Only install SIGABRT handler once */
160 if (!qtest_instances) {
161 setup_sigabrt_handler();
164 qtest_instances = g_list_prepend(qtest_instances, s);
166 s->qemu_pid = fork();
167 if (s->qemu_pid == 0) {
168 command = g_strdup_printf("exec %s "
169 "-qtest unix:%s,nowait "
170 "-qtest-log /dev/null "
171 "-qmp unix:%s,nowait "
172 "-machine accel=qtest "
173 "-display none "
174 "%s", qemu_binary, socket_path,
175 qmp_socket_path,
176 extra_args ?: "");
177 execlp("/bin/sh", "sh", "-c", command, NULL);
178 exit(1);
181 s->fd = socket_accept(sock);
182 if (s->fd >= 0) {
183 s->qmp_fd = socket_accept(qmpsock);
185 unlink(socket_path);
186 unlink(qmp_socket_path);
187 g_free(socket_path);
188 g_free(qmp_socket_path);
190 g_assert(s->fd >= 0 && s->qmp_fd >= 0);
192 s->rx = g_string_new("");
193 for (i = 0; i < MAX_IRQ; i++) {
194 s->irq_level[i] = false;
197 /* Read the QMP greeting and then do the handshake */
198 qtest_qmp_discard_response(s, "");
199 qtest_qmp_discard_response(s, "{ 'execute': 'qmp_capabilities' }");
201 if (getenv("QTEST_STOP")) {
202 kill(s->qemu_pid, SIGSTOP);
205 return s;
208 void qtest_quit(QTestState *s)
210 /* Uninstall SIGABRT handler on last instance */
211 if (qtest_instances && !qtest_instances->next) {
212 cleanup_sigabrt_handler();
215 qtest_instances = g_list_remove(qtest_instances, s);
217 kill_qemu(s);
218 close(s->fd);
219 close(s->qmp_fd);
220 g_string_free(s->rx, true);
221 g_free(s);
224 static void socket_send(int fd, const char *buf, size_t size)
226 size_t offset;
228 offset = 0;
229 while (offset < size) {
230 ssize_t len;
232 len = write(fd, buf + offset, size - offset);
233 if (len == -1 && errno == EINTR) {
234 continue;
237 g_assert_no_errno(len);
238 g_assert_cmpint(len, >, 0);
240 offset += len;
244 static void socket_sendf(int fd, const char *fmt, va_list ap)
246 gchar *str = g_strdup_vprintf(fmt, ap);
247 size_t size = strlen(str);
249 socket_send(fd, str, size);
250 g_free(str);
253 static void GCC_FMT_ATTR(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...)
255 va_list ap;
257 va_start(ap, fmt);
258 socket_sendf(s->fd, fmt, ap);
259 va_end(ap);
262 static GString *qtest_recv_line(QTestState *s)
264 GString *line;
265 size_t offset;
266 char *eol;
268 while ((eol = strchr(s->rx->str, '\n')) == NULL) {
269 ssize_t len;
270 char buffer[1024];
272 len = read(s->fd, buffer, sizeof(buffer));
273 if (len == -1 && errno == EINTR) {
274 continue;
277 if (len == -1 || len == 0) {
278 fprintf(stderr, "Broken pipe\n");
279 exit(1);
282 g_string_append_len(s->rx, buffer, len);
285 offset = eol - s->rx->str;
286 line = g_string_new_len(s->rx->str, offset);
287 g_string_erase(s->rx, 0, offset + 1);
289 return line;
292 static gchar **qtest_rsp(QTestState *s, int expected_args)
294 GString *line;
295 gchar **words;
296 int i;
298 redo:
299 line = qtest_recv_line(s);
300 words = g_strsplit(line->str, " ", 0);
301 g_string_free(line, TRUE);
303 if (strcmp(words[0], "IRQ") == 0) {
304 int irq;
306 g_assert(words[1] != NULL);
307 g_assert(words[2] != NULL);
309 irq = strtoul(words[2], NULL, 0);
310 g_assert_cmpint(irq, >=, 0);
311 g_assert_cmpint(irq, <, MAX_IRQ);
313 if (strcmp(words[1], "raise") == 0) {
314 s->irq_level[irq] = true;
315 } else {
316 s->irq_level[irq] = false;
319 g_strfreev(words);
320 goto redo;
323 g_assert(words[0] != NULL);
324 g_assert_cmpstr(words[0], ==, "OK");
326 if (expected_args) {
327 for (i = 0; i < expected_args; i++) {
328 g_assert(words[i] != NULL);
330 } else {
331 g_strfreev(words);
334 return words;
337 typedef struct {
338 JSONMessageParser parser;
339 QDict *response;
340 } QMPResponseParser;
342 static void qmp_response(JSONMessageParser *parser, QList *tokens)
344 QMPResponseParser *qmp = container_of(parser, QMPResponseParser, parser);
345 QObject *obj;
347 obj = json_parser_parse(tokens, NULL);
348 if (!obj) {
349 fprintf(stderr, "QMP JSON response parsing failed\n");
350 exit(1);
353 g_assert(qobject_type(obj) == QTYPE_QDICT);
354 g_assert(!qmp->response);
355 qmp->response = (QDict *)obj;
358 QDict *qtest_qmp_receive(QTestState *s)
360 QMPResponseParser qmp;
362 qmp.response = NULL;
363 json_message_parser_init(&qmp.parser, qmp_response);
364 while (!qmp.response) {
365 ssize_t len;
366 char c;
368 len = read(s->qmp_fd, &c, 1);
369 if (len == -1 && errno == EINTR) {
370 continue;
373 if (len == -1 || len == 0) {
374 fprintf(stderr, "Broken pipe\n");
375 exit(1);
378 json_message_parser_feed(&qmp.parser, &c, 1);
380 json_message_parser_destroy(&qmp.parser);
382 return qmp.response;
385 QDict *qtest_qmpv(QTestState *s, const char *fmt, va_list ap)
387 va_list ap_copy;
388 QObject *qobj;
390 /* Going through qobject ensures we escape strings properly.
391 * This seemingly unnecessary copy is required in case va_list
392 * is an array type.
394 va_copy(ap_copy, ap);
395 qobj = qobject_from_jsonv(fmt, &ap_copy);
396 va_end(ap_copy);
398 /* No need to send anything for an empty QObject. */
399 if (qobj) {
400 QString *qstr = qobject_to_json(qobj);
401 const char *str = qstring_get_str(qstr);
402 size_t size = qstring_get_length(qstr);
404 /* Send QMP request */
405 socket_send(s->qmp_fd, str, size);
407 QDECREF(qstr);
408 qobject_decref(qobj);
411 /* Receive reply */
412 return qtest_qmp_receive(s);
415 QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
417 va_list ap;
418 QDict *response;
420 va_start(ap, fmt);
421 response = qtest_qmpv(s, fmt, ap);
422 va_end(ap);
423 return response;
426 void qtest_qmpv_discard_response(QTestState *s, const char *fmt, va_list ap)
428 QDict *response = qtest_qmpv(s, fmt, ap);
429 QDECREF(response);
432 void qtest_qmp_discard_response(QTestState *s, const char *fmt, ...)
434 va_list ap;
435 QDict *response;
437 va_start(ap, fmt);
438 response = qtest_qmpv(s, fmt, ap);
439 va_end(ap);
440 QDECREF(response);
443 const char *qtest_get_arch(void)
445 const char *qemu = getenv("QTEST_QEMU_BINARY");
446 const char *end = strrchr(qemu, '/');
448 return end + strlen("/qemu-system-");
451 bool qtest_get_irq(QTestState *s, int num)
453 /* dummy operation in order to make sure irq is up to date */
454 qtest_inb(s, 0);
456 return s->irq_level[num];
459 static int64_t qtest_clock_rsp(QTestState *s)
461 gchar **words;
462 int64_t clock;
463 words = qtest_rsp(s, 2);
464 clock = g_ascii_strtoll(words[1], NULL, 0);
465 g_strfreev(words);
466 return clock;
469 int64_t qtest_clock_step_next(QTestState *s)
471 qtest_sendf(s, "clock_step\n");
472 return qtest_clock_rsp(s);
475 int64_t qtest_clock_step(QTestState *s, int64_t step)
477 qtest_sendf(s, "clock_step %"PRIi64"\n", step);
478 return qtest_clock_rsp(s);
481 int64_t qtest_clock_set(QTestState *s, int64_t val)
483 qtest_sendf(s, "clock_set %"PRIi64"\n", val);
484 return qtest_clock_rsp(s);
487 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
489 qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
490 qtest_rsp(s, 0);
493 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
495 qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
496 qtest_rsp(s, 0);
499 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
501 qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
502 qtest_rsp(s, 0);
505 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
507 qtest_out(s, "outb", addr, value);
510 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
512 qtest_out(s, "outw", addr, value);
515 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
517 qtest_out(s, "outl", addr, value);
520 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
522 gchar **args;
523 uint32_t value;
525 qtest_sendf(s, "%s 0x%x\n", cmd, addr);
526 args = qtest_rsp(s, 2);
527 value = strtoul(args[1], NULL, 0);
528 g_strfreev(args);
530 return value;
533 uint8_t qtest_inb(QTestState *s, uint16_t addr)
535 return qtest_in(s, "inb", addr);
538 uint16_t qtest_inw(QTestState *s, uint16_t addr)
540 return qtest_in(s, "inw", addr);
543 uint32_t qtest_inl(QTestState *s, uint16_t addr)
545 return qtest_in(s, "inl", addr);
548 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
549 uint64_t value)
551 qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
552 qtest_rsp(s, 0);
555 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
557 qtest_write(s, "writeb", addr, value);
560 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
562 qtest_write(s, "writew", addr, value);
565 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
567 qtest_write(s, "writel", addr, value);
570 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
572 qtest_write(s, "writeq", addr, value);
575 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
577 gchar **args;
578 uint64_t value;
580 qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
581 args = qtest_rsp(s, 2);
582 value = strtoull(args[1], NULL, 0);
583 g_strfreev(args);
585 return value;
588 uint8_t qtest_readb(QTestState *s, uint64_t addr)
590 return qtest_read(s, "readb", addr);
593 uint16_t qtest_readw(QTestState *s, uint64_t addr)
595 return qtest_read(s, "readw", addr);
598 uint32_t qtest_readl(QTestState *s, uint64_t addr)
600 return qtest_read(s, "readl", addr);
603 uint64_t qtest_readq(QTestState *s, uint64_t addr)
605 return qtest_read(s, "readq", addr);
608 static int hex2nib(char ch)
610 if (ch >= '0' && ch <= '9') {
611 return ch - '0';
612 } else if (ch >= 'a' && ch <= 'f') {
613 return 10 + (ch - 'a');
614 } else if (ch >= 'A' && ch <= 'F') {
615 return 10 + (ch - 'a');
616 } else {
617 return -1;
621 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
623 uint8_t *ptr = data;
624 gchar **args;
625 size_t i;
627 qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
628 args = qtest_rsp(s, 2);
630 for (i = 0; i < size; i++) {
631 ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
632 ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
635 g_strfreev(args);
638 void qtest_add_func(const char *str, void (*fn))
640 gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
641 g_test_add_func(path, fn);
644 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
646 const uint8_t *ptr = data;
647 size_t i;
649 qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x", addr, size);
650 for (i = 0; i < size; i++) {
651 qtest_sendf(s, "%02x", ptr[i]);
653 qtest_sendf(s, "\n");
654 qtest_rsp(s, 0);
657 QDict *qmp(const char *fmt, ...)
659 va_list ap;
660 QDict *response;
662 va_start(ap, fmt);
663 response = qtest_qmpv(global_qtest, fmt, ap);
664 va_end(ap);
665 return response;
668 void qmp_discard_response(const char *fmt, ...)
670 va_list ap;
672 va_start(ap, fmt);
673 qtest_qmpv_discard_response(global_qtest, fmt, ap);
674 va_end(ap);