xref: /openbmc/qemu/tests/qtest/libqtest.c (revision e6b5a071)
1 /*
2  * QTest
3  *
4  * Copyright IBM, Corp. 2012
5  * Copyright Red Hat, Inc. 2012
6  * Copyright SUSE LINUX Products GmbH 2013
7  *
8  * Authors:
9  *  Anthony Liguori   <aliguori@us.ibm.com>
10  *  Paolo Bonzini     <pbonzini@redhat.com>
11  *  Andreas Färber    <afaerber@suse.de>
12  *
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.
15  */
16 
17 #include "qemu/osdep.h"
18 
19 #include <sys/socket.h>
20 #include <sys/wait.h>
21 #include <sys/un.h>
22 
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"
33 
34 #define MAX_IRQ 256
35 #define SOCKET_TIMEOUT 50
36 #define SOCKET_MAX_FDS 16
37 
38 
39 typedef void (*QTestSendFn)(QTestState *s, const char *buf);
40 typedef void (*ExternalSendFn)(void *s, const char *buf);
41 typedef GString* (*QTestRecvFn)(QTestState *);
42 
43 typedef struct QTestClientTransportOps {
44     QTestSendFn     send;      /* for sending qtest commands */
45 
46     /*
47      * use external_send to send qtest command strings through functions which
48      * do not accept a QTestState as the first parameter.
49      */
50     ExternalSendFn  external_send;
51 
52     QTestRecvFn     recv_line; /* for receiving qtest command responses */
53 } QTestTransportOps;
54 
55 struct QTestState
56 {
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;
67 };
68 
69 static GHookList abrt_hooks;
70 static struct sigaction sigact_old;
71 
72 static int qtest_query_target_endianness(QTestState *s);
73 
74 static void qtest_client_socket_send(QTestState*, const char *buf);
75 static void socket_send(int fd, const char *buf, size_t size);
76 
77 static GString *qtest_client_socket_recv_line(QTestState *);
78 
79 static void qtest_client_set_tx_handler(QTestState *s, QTestSendFn send);
80 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv);
81 
82 static int init_socket(const char *socket_path)
83 {
84     struct sockaddr_un addr;
85     int sock;
86     int ret;
87 
88     sock = socket(PF_UNIX, SOCK_STREAM, 0);
89     g_assert_cmpint(sock, !=, -1);
90 
91     addr.sun_family = AF_UNIX;
92     snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", socket_path);
93     qemu_set_cloexec(sock);
94 
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);
101 
102     return sock;
103 }
104 
105 static int socket_accept(int sock)
106 {
107     struct sockaddr_un addr;
108     socklen_t addrlen;
109     int ret;
110     struct timeval timeout = { .tv_sec = SOCKET_TIMEOUT,
111                                .tv_usec = 0 };
112 
113     setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *)&timeout,
114                sizeof(timeout));
115 
116     do {
117         addrlen = sizeof(addr);
118         ret = accept(sock, (struct sockaddr *)&addr, &addrlen);
119     } while (ret == -1 && errno == EINTR);
120     if (ret == -1) {
121         fprintf(stderr, "%s failed: %s\n", __func__, strerror(errno));
122     }
123     close(sock);
124 
125     return ret;
126 }
127 
128 bool qtest_probe_child(QTestState *s)
129 {
130     pid_t pid = s->qemu_pid;
131 
132     if (pid != -1) {
133         pid = waitpid(pid, &s->wstatus, WNOHANG);
134         if (pid == 0) {
135             return true;
136         }
137         s->qemu_pid = -1;
138     }
139     return false;
140 }
141 
142 void qtest_set_expected_status(QTestState *s, int status)
143 {
144     s->expected_status = status;
145 }
146 
147 static void kill_qemu(QTestState *s)
148 {
149     pid_t pid = s->qemu_pid;
150     int wstatus;
151 
152     /* Skip wait if qtest_probe_child already reaped.  */
153     if (pid != -1) {
154         kill(pid, SIGTERM);
155         TFR(pid = waitpid(s->qemu_pid, &s->wstatus, 0));
156         assert(pid == s->qemu_pid);
157     }
158 
159     /*
160      * Check whether qemu exited with expected exit status; anything else is
161      * fishy and should be logged with as much detail as possible.
162      */
163     wstatus = s->wstatus;
164     if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) != s->expected_status) {
165         fprintf(stderr, "%s:%d: kill_qemu() tried to terminate QEMU "
166                 "process but encountered exit status %d (expected %d)\n",
167                 __FILE__, __LINE__, WEXITSTATUS(wstatus), s->expected_status);
168         abort();
169     } else if (WIFSIGNALED(wstatus)) {
170         int sig = WTERMSIG(wstatus);
171         const char *signame = strsignal(sig) ?: "unknown ???";
172         const char *dump = WCOREDUMP(wstatus) ? " (core dumped)" : "";
173 
174         fprintf(stderr, "%s:%d: kill_qemu() detected QEMU death "
175                 "from signal %d (%s)%s\n",
176                 __FILE__, __LINE__, sig, signame, dump);
177         abort();
178     }
179 }
180 
181 static void kill_qemu_hook_func(void *s)
182 {
183     kill_qemu(s);
184 }
185 
186 static void sigabrt_handler(int signo)
187 {
188     g_hook_list_invoke(&abrt_hooks, FALSE);
189 }
190 
191 static void setup_sigabrt_handler(void)
192 {
193     struct sigaction sigact;
194 
195     /* Catch SIGABRT to clean up on g_assert() failure */
196     sigact = (struct sigaction){
197         .sa_handler = sigabrt_handler,
198         .sa_flags = SA_RESETHAND,
199     };
200     sigemptyset(&sigact.sa_mask);
201     sigaction(SIGABRT, &sigact, &sigact_old);
202 }
203 
204 static void cleanup_sigabrt_handler(void)
205 {
206     sigaction(SIGABRT, &sigact_old, NULL);
207 }
208 
209 void qtest_add_abrt_handler(GHookFunc fn, const void *data)
210 {
211     GHook *hook;
212 
213     /* Only install SIGABRT handler once */
214     if (!abrt_hooks.is_setup) {
215         g_hook_list_init(&abrt_hooks, sizeof(GHook));
216     }
217     setup_sigabrt_handler();
218 
219     hook = g_hook_alloc(&abrt_hooks);
220     hook->func = fn;
221     hook->data = (void *)data;
222 
223     g_hook_prepend(&abrt_hooks, hook);
224 }
225 
226 static const char *qtest_qemu_binary(void)
227 {
228     const char *qemu_bin;
229 
230     qemu_bin = getenv("QTEST_QEMU_BINARY");
231     if (!qemu_bin) {
232         fprintf(stderr, "Environment variable QTEST_QEMU_BINARY required\n");
233         exit(1);
234     }
235 
236     return qemu_bin;
237 }
238 
239 QTestState *qtest_init_without_qmp_handshake(const char *extra_args)
240 {
241     QTestState *s;
242     int sock, qmpsock, i;
243     gchar *socket_path;
244     gchar *qmp_socket_path;
245     gchar *command;
246     const char *qemu_binary = qtest_qemu_binary();
247 
248     s = g_new(QTestState, 1);
249 
250     socket_path = g_strdup_printf("/tmp/qtest-%d.sock", getpid());
251     qmp_socket_path = g_strdup_printf("/tmp/qtest-%d.qmp", getpid());
252 
253     /* It's possible that if an earlier test run crashed it might
254      * have left a stale unix socket lying around. Delete any
255      * stale old socket to avoid spurious test failures with
256      * tests/libqtest.c:70:init_socket: assertion failed (ret != -1): (-1 != -1)
257      */
258     unlink(socket_path);
259     unlink(qmp_socket_path);
260 
261     sock = init_socket(socket_path);
262     qmpsock = init_socket(qmp_socket_path);
263 
264     qtest_client_set_rx_handler(s, qtest_client_socket_recv_line);
265     qtest_client_set_tx_handler(s, qtest_client_socket_send);
266 
267     qtest_add_abrt_handler(kill_qemu_hook_func, s);
268 
269     command = g_strdup_printf("exec %s "
270                               "-qtest unix:%s "
271                               "-qtest-log %s "
272                               "-chardev socket,path=%s,id=char0 "
273                               "-mon chardev=char0,mode=control "
274                               "-display none "
275                               "%s"
276                               " -accel qtest", qemu_binary, socket_path,
277                               getenv("QTEST_LOG") ? "/dev/fd/2" : "/dev/null",
278                               qmp_socket_path,
279                               extra_args ?: "");
280 
281     g_test_message("starting QEMU: %s", command);
282 
283     s->pending_events = NULL;
284     s->wstatus = 0;
285     s->expected_status = 0;
286     s->qemu_pid = fork();
287     if (s->qemu_pid == 0) {
288         g_setenv("QEMU_AUDIO_DRV", "none", true);
289         execlp("/bin/sh", "sh", "-c", command, NULL);
290         exit(1);
291     }
292 
293     g_free(command);
294     s->fd = socket_accept(sock);
295     if (s->fd >= 0) {
296         s->qmp_fd = socket_accept(qmpsock);
297     }
298     unlink(socket_path);
299     unlink(qmp_socket_path);
300     g_free(socket_path);
301     g_free(qmp_socket_path);
302 
303     g_assert(s->fd >= 0 && s->qmp_fd >= 0);
304 
305     s->rx = g_string_new("");
306     for (i = 0; i < MAX_IRQ; i++) {
307         s->irq_level[i] = false;
308     }
309 
310     if (getenv("QTEST_STOP")) {
311         kill(s->qemu_pid, SIGSTOP);
312     }
313 
314     /* ask endianness of the target */
315 
316     s->big_endian = qtest_query_target_endianness(s);
317 
318     return s;
319 }
320 
321 QTestState *qtest_init(const char *extra_args)
322 {
323     QTestState *s = qtest_init_without_qmp_handshake(extra_args);
324     QDict *greeting;
325 
326     /* Read the QMP greeting and then do the handshake */
327     greeting = qtest_qmp_receive(s);
328     qobject_unref(greeting);
329     qobject_unref(qtest_qmp(s, "{ 'execute': 'qmp_capabilities' }"));
330 
331     return s;
332 }
333 
334 QTestState *qtest_vinitf(const char *fmt, va_list ap)
335 {
336     char *args = g_strdup_vprintf(fmt, ap);
337     QTestState *s;
338 
339     s = qtest_init(args);
340     g_free(args);
341     return s;
342 }
343 
344 QTestState *qtest_initf(const char *fmt, ...)
345 {
346     va_list ap;
347     QTestState *s;
348 
349     va_start(ap, fmt);
350     s = qtest_vinitf(fmt, ap);
351     va_end(ap);
352     return s;
353 }
354 
355 QTestState *qtest_init_with_serial(const char *extra_args, int *sock_fd)
356 {
357     int sock_fd_init;
358     char *sock_path, sock_dir[] = "/tmp/qtest-serial-XXXXXX";
359     QTestState *qts;
360 
361     g_assert_true(mkdtemp(sock_dir) != NULL);
362     sock_path = g_strdup_printf("%s/sock", sock_dir);
363 
364     sock_fd_init = init_socket(sock_path);
365 
366     qts = qtest_initf("-chardev socket,id=s0,path=%s -serial chardev:s0 %s",
367                       sock_path, extra_args);
368 
369     *sock_fd = socket_accept(sock_fd_init);
370 
371     unlink(sock_path);
372     g_free(sock_path);
373     rmdir(sock_dir);
374 
375     g_assert_true(*sock_fd >= 0);
376 
377     return qts;
378 }
379 
380 void qtest_quit(QTestState *s)
381 {
382     g_hook_destroy_link(&abrt_hooks, g_hook_find_data(&abrt_hooks, TRUE, s));
383 
384     /* Uninstall SIGABRT handler on last instance */
385     cleanup_sigabrt_handler();
386 
387     kill_qemu(s);
388     close(s->fd);
389     close(s->qmp_fd);
390     g_string_free(s->rx, true);
391 
392     for (GList *it = s->pending_events; it != NULL; it = it->next) {
393         qobject_unref((QDict *)it->data);
394     }
395 
396     g_list_free(s->pending_events);
397 
398     g_free(s);
399 }
400 
401 static void socket_send(int fd, const char *buf, size_t size)
402 {
403     size_t offset;
404 
405     offset = 0;
406     while (offset < size) {
407         ssize_t len;
408 
409         len = write(fd, buf + offset, size - offset);
410         if (len == -1 && errno == EINTR) {
411             continue;
412         }
413 
414         g_assert_cmpint(len, >, 0);
415 
416         offset += len;
417     }
418 }
419 
420 static void qtest_client_socket_send(QTestState *s, const char *buf)
421 {
422     socket_send(s->fd, buf, strlen(buf));
423 }
424 
425 static void GCC_FMT_ATTR(2, 3) qtest_sendf(QTestState *s, const char *fmt, ...)
426 {
427     va_list ap;
428 
429     va_start(ap, fmt);
430     gchar *str = g_strdup_vprintf(fmt, ap);
431     va_end(ap);
432 
433     s->ops.send(s, str);
434     g_free(str);
435 }
436 
437 /* Sends a message and file descriptors to the socket.
438  * It's needed for qmp-commands like getfd/add-fd */
439 static void socket_send_fds(int socket_fd, int *fds, size_t fds_num,
440                             const char *buf, size_t buf_size)
441 {
442     ssize_t ret;
443     struct msghdr msg = { 0 };
444     char control[CMSG_SPACE(sizeof(int) * SOCKET_MAX_FDS)] = { 0 };
445     size_t fdsize = sizeof(int) * fds_num;
446     struct cmsghdr *cmsg;
447     struct iovec iov = { .iov_base = (char *)buf, .iov_len = buf_size };
448 
449     msg.msg_iov = &iov;
450     msg.msg_iovlen = 1;
451 
452     if (fds && fds_num > 0) {
453         g_assert_cmpuint(fds_num, <, SOCKET_MAX_FDS);
454 
455         msg.msg_control = control;
456         msg.msg_controllen = CMSG_SPACE(fdsize);
457 
458         cmsg = CMSG_FIRSTHDR(&msg);
459         cmsg->cmsg_len = CMSG_LEN(fdsize);
460         cmsg->cmsg_level = SOL_SOCKET;
461         cmsg->cmsg_type = SCM_RIGHTS;
462         memcpy(CMSG_DATA(cmsg), fds, fdsize);
463     }
464 
465     do {
466         ret = sendmsg(socket_fd, &msg, 0);
467     } while (ret < 0 && errno == EINTR);
468     g_assert_cmpint(ret, >, 0);
469 }
470 
471 static GString *qtest_client_socket_recv_line(QTestState *s)
472 {
473     GString *line;
474     size_t offset;
475     char *eol;
476 
477     while ((eol = strchr(s->rx->str, '\n')) == NULL) {
478         ssize_t len;
479         char buffer[1024];
480 
481         len = read(s->fd, buffer, sizeof(buffer));
482         if (len == -1 && errno == EINTR) {
483             continue;
484         }
485 
486         if (len == -1 || len == 0) {
487             fprintf(stderr, "Broken pipe\n");
488             abort();
489         }
490 
491         g_string_append_len(s->rx, buffer, len);
492     }
493 
494     offset = eol - s->rx->str;
495     line = g_string_new_len(s->rx->str, offset);
496     g_string_erase(s->rx, 0, offset + 1);
497 
498     return line;
499 }
500 
501 static gchar **qtest_rsp(QTestState *s, int expected_args)
502 {
503     GString *line;
504     gchar **words;
505     int i;
506 
507 redo:
508     line = s->ops.recv_line(s);
509     words = g_strsplit(line->str, " ", 0);
510     g_string_free(line, TRUE);
511 
512     if (strcmp(words[0], "IRQ") == 0) {
513         long irq;
514         int ret;
515 
516         g_assert(words[1] != NULL);
517         g_assert(words[2] != NULL);
518 
519         ret = qemu_strtol(words[2], NULL, 0, &irq);
520         g_assert(!ret);
521         g_assert_cmpint(irq, >=, 0);
522         g_assert_cmpint(irq, <, MAX_IRQ);
523 
524         if (strcmp(words[1], "raise") == 0) {
525             s->irq_level[irq] = true;
526         } else {
527             s->irq_level[irq] = false;
528         }
529 
530         g_strfreev(words);
531         goto redo;
532     }
533 
534     g_assert(words[0] != NULL);
535     g_assert_cmpstr(words[0], ==, "OK");
536 
537     if (expected_args) {
538         for (i = 0; i < expected_args; i++) {
539             g_assert(words[i] != NULL);
540         }
541     } else {
542         g_strfreev(words);
543     }
544 
545     return words;
546 }
547 
548 static int qtest_query_target_endianness(QTestState *s)
549 {
550     gchar **args;
551     int big_endian;
552 
553     qtest_sendf(s, "endianness\n");
554     args = qtest_rsp(s, 1);
555     g_assert(strcmp(args[1], "big") == 0 || strcmp(args[1], "little") == 0);
556     big_endian = strcmp(args[1], "big") == 0;
557     g_strfreev(args);
558 
559     return big_endian;
560 }
561 
562 typedef struct {
563     JSONMessageParser parser;
564     QDict *response;
565 } QMPResponseParser;
566 
567 static void qmp_response(void *opaque, QObject *obj, Error *err)
568 {
569     QMPResponseParser *qmp = opaque;
570 
571     assert(!obj != !err);
572 
573     if (err) {
574         error_prepend(&err, "QMP JSON response parsing failed: ");
575         error_report_err(err);
576         abort();
577     }
578 
579     g_assert(!qmp->response);
580     qmp->response = qobject_to(QDict, obj);
581     g_assert(qmp->response);
582 }
583 
584 QDict *qmp_fd_receive(int fd)
585 {
586     QMPResponseParser qmp;
587     bool log = getenv("QTEST_LOG") != NULL;
588 
589     qmp.response = NULL;
590     json_message_parser_init(&qmp.parser, qmp_response, &qmp, NULL);
591     while (!qmp.response) {
592         ssize_t len;
593         char c;
594 
595         len = read(fd, &c, 1);
596         if (len == -1 && errno == EINTR) {
597             continue;
598         }
599 
600         if (len == -1 || len == 0) {
601             fprintf(stderr, "Broken pipe\n");
602             abort();
603         }
604 
605         if (log) {
606             len = write(2, &c, 1);
607         }
608         json_message_parser_feed(&qmp.parser, &c, 1);
609     }
610     json_message_parser_destroy(&qmp.parser);
611 
612     return qmp.response;
613 }
614 
615 QDict *qtest_qmp_receive(QTestState *s)
616 {
617     while (true) {
618         QDict *response = qtest_qmp_receive_dict(s);
619 
620         if (!qdict_get_try_str(response, "event")) {
621             return response;
622         }
623         /* Stash the event for a later consumption */
624         s->pending_events = g_list_prepend(s->pending_events, response);
625     }
626 }
627 
628 QDict *qtest_qmp_receive_dict(QTestState *s)
629 {
630     return qmp_fd_receive(s->qmp_fd);
631 }
632 
633 /**
634  * Allow users to send a message without waiting for the reply,
635  * in the case that they choose to discard all replies up until
636  * a particular EVENT is received.
637  */
638 void qmp_fd_vsend_fds(int fd, int *fds, size_t fds_num,
639                       const char *fmt, va_list ap)
640 {
641     QObject *qobj;
642 
643     /* Going through qobject ensures we escape strings properly */
644     qobj = qobject_from_vjsonf_nofail(fmt, ap);
645 
646     /* No need to send anything for an empty QObject.  */
647     if (qobj) {
648         int log = getenv("QTEST_LOG") != NULL;
649         QString *qstr = qobject_to_json(qobj);
650         const char *str;
651 
652         /*
653          * BUG: QMP doesn't react to input until it sees a newline, an
654          * object, or an array.  Work-around: give it a newline.
655          */
656         qstring_append_chr(qstr, '\n');
657         str = qstring_get_str(qstr);
658 
659         if (log) {
660             fprintf(stderr, "%s", str);
661         }
662         /* Send QMP request */
663         if (fds && fds_num > 0) {
664             socket_send_fds(fd, fds, fds_num, str, qstring_get_length(qstr));
665         } else {
666             socket_send(fd, str, qstring_get_length(qstr));
667         }
668 
669         qobject_unref(qstr);
670         qobject_unref(qobj);
671     }
672 }
673 
674 void qmp_fd_vsend(int fd, const char *fmt, va_list ap)
675 {
676     qmp_fd_vsend_fds(fd, NULL, 0, fmt, ap);
677 }
678 
679 void qtest_qmp_vsend_fds(QTestState *s, int *fds, size_t fds_num,
680                          const char *fmt, va_list ap)
681 {
682     qmp_fd_vsend_fds(s->qmp_fd, fds, fds_num, fmt, ap);
683 }
684 
685 void qtest_qmp_vsend(QTestState *s, const char *fmt, va_list ap)
686 {
687     qmp_fd_vsend_fds(s->qmp_fd, NULL, 0, fmt, ap);
688 }
689 
690 QDict *qmp_fdv(int fd, const char *fmt, va_list ap)
691 {
692     qmp_fd_vsend_fds(fd, NULL, 0, fmt, ap);
693 
694     return qmp_fd_receive(fd);
695 }
696 
697 QDict *qtest_vqmp_fds(QTestState *s, int *fds, size_t fds_num,
698                       const char *fmt, va_list ap)
699 {
700     qtest_qmp_vsend_fds(s, fds, fds_num, fmt, ap);
701 
702     /* Receive reply */
703     return qtest_qmp_receive(s);
704 }
705 
706 QDict *qtest_vqmp(QTestState *s, const char *fmt, va_list ap)
707 {
708     qtest_qmp_vsend(s, fmt, ap);
709 
710     /* Receive reply */
711     return qtest_qmp_receive(s);
712 }
713 
714 QDict *qmp_fd(int fd, const char *fmt, ...)
715 {
716     va_list ap;
717     QDict *response;
718 
719     va_start(ap, fmt);
720     response = qmp_fdv(fd, fmt, ap);
721     va_end(ap);
722     return response;
723 }
724 
725 void qmp_fd_send(int fd, const char *fmt, ...)
726 {
727     va_list ap;
728 
729     va_start(ap, fmt);
730     qmp_fd_vsend(fd, fmt, ap);
731     va_end(ap);
732 }
733 
734 QDict *qtest_qmp_fds(QTestState *s, int *fds, size_t fds_num,
735                      const char *fmt, ...)
736 {
737     va_list ap;
738     QDict *response;
739 
740     va_start(ap, fmt);
741     response = qtest_vqmp_fds(s, fds, fds_num, fmt, ap);
742     va_end(ap);
743     return response;
744 }
745 
746 QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
747 {
748     va_list ap;
749     QDict *response;
750 
751     va_start(ap, fmt);
752     response = qtest_vqmp(s, fmt, ap);
753     va_end(ap);
754     return response;
755 }
756 
757 void qtest_qmp_send(QTestState *s, const char *fmt, ...)
758 {
759     va_list ap;
760 
761     va_start(ap, fmt);
762     qtest_qmp_vsend(s, fmt, ap);
763     va_end(ap);
764 }
765 
766 void qmp_fd_vsend_raw(int fd, const char *fmt, va_list ap)
767 {
768     bool log = getenv("QTEST_LOG") != NULL;
769     char *str = g_strdup_vprintf(fmt, ap);
770 
771     if (log) {
772         fprintf(stderr, "%s", str);
773     }
774     socket_send(fd, str, strlen(str));
775     g_free(str);
776 }
777 
778 void qmp_fd_send_raw(int fd, const char *fmt, ...)
779 {
780     va_list ap;
781 
782     va_start(ap, fmt);
783     qmp_fd_vsend_raw(fd, fmt, ap);
784     va_end(ap);
785 }
786 
787 void qtest_qmp_send_raw(QTestState *s, const char *fmt, ...)
788 {
789     va_list ap;
790 
791     va_start(ap, fmt);
792     qmp_fd_vsend_raw(s->qmp_fd, fmt, ap);
793     va_end(ap);
794 }
795 
796 QDict *qtest_qmp_event_ref(QTestState *s, const char *event)
797 {
798     GList *next = NULL;
799     QDict *response;
800 
801     for (GList *it = s->pending_events; it != NULL; it = next) {
802 
803         next = it->next;
804         response = (QDict *)it->data;
805 
806         s->pending_events = g_list_remove_link(s->pending_events, it);
807 
808         if (!strcmp(qdict_get_str(response, "event"), event)) {
809             return response;
810         }
811         qobject_unref(response);
812     }
813     return NULL;
814 }
815 
816 QDict *qtest_qmp_eventwait_ref(QTestState *s, const char *event)
817 {
818     QDict *response = qtest_qmp_event_ref(s, event);
819 
820     if (response) {
821         return response;
822     }
823 
824     for (;;) {
825         response = qtest_qmp_receive_dict(s);
826         if ((qdict_haskey(response, "event")) &&
827             (strcmp(qdict_get_str(response, "event"), event) == 0)) {
828             return response;
829         }
830         qobject_unref(response);
831     }
832 }
833 
834 void qtest_qmp_eventwait(QTestState *s, const char *event)
835 {
836     QDict *response;
837 
838     response = qtest_qmp_eventwait_ref(s, event);
839     qobject_unref(response);
840 }
841 
842 char *qtest_vhmp(QTestState *s, const char *fmt, va_list ap)
843 {
844     char *cmd;
845     QDict *resp;
846     char *ret;
847 
848     cmd = g_strdup_vprintf(fmt, ap);
849     resp = qtest_qmp(s, "{'execute': 'human-monitor-command',"
850                      " 'arguments': {'command-line': %s}}",
851                      cmd);
852     ret = g_strdup(qdict_get_try_str(resp, "return"));
853     g_assert(ret);
854     qobject_unref(resp);
855     g_free(cmd);
856     return ret;
857 }
858 
859 char *qtest_hmp(QTestState *s, const char *fmt, ...)
860 {
861     va_list ap;
862     char *ret;
863 
864     va_start(ap, fmt);
865     ret = qtest_vhmp(s, fmt, ap);
866     va_end(ap);
867     return ret;
868 }
869 
870 const char *qtest_get_arch(void)
871 {
872     const char *qemu = qtest_qemu_binary();
873     const char *end = strrchr(qemu, '/');
874 
875     return end + strlen("/qemu-system-");
876 }
877 
878 bool qtest_get_irq(QTestState *s, int num)
879 {
880     /* dummy operation in order to make sure irq is up to date */
881     qtest_inb(s, 0);
882 
883     return s->irq_level[num];
884 }
885 
886 void qtest_module_load(QTestState *s, const char *prefix, const char *libname)
887 {
888     qtest_sendf(s, "module_load %s %s\n", prefix, libname);
889     qtest_rsp(s, 0);
890 }
891 
892 static int64_t qtest_clock_rsp(QTestState *s)
893 {
894     gchar **words;
895     int64_t clock;
896     words = qtest_rsp(s, 2);
897     clock = g_ascii_strtoll(words[1], NULL, 0);
898     g_strfreev(words);
899     return clock;
900 }
901 
902 int64_t qtest_clock_step_next(QTestState *s)
903 {
904     qtest_sendf(s, "clock_step\n");
905     return qtest_clock_rsp(s);
906 }
907 
908 int64_t qtest_clock_step(QTestState *s, int64_t step)
909 {
910     qtest_sendf(s, "clock_step %"PRIi64"\n", step);
911     return qtest_clock_rsp(s);
912 }
913 
914 int64_t qtest_clock_set(QTestState *s, int64_t val)
915 {
916     qtest_sendf(s, "clock_set %"PRIi64"\n", val);
917     return qtest_clock_rsp(s);
918 }
919 
920 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
921 {
922     qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
923     qtest_rsp(s, 0);
924 }
925 
926 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
927 {
928     qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
929     qtest_rsp(s, 0);
930 }
931 
932 void qtest_set_irq_in(QTestState *s, const char *qom_path, const char *name,
933                       int num, int level)
934 {
935     if (!name) {
936         name = "unnamed-gpio-in";
937     }
938     qtest_sendf(s, "set_irq_in %s %s %d %d\n", qom_path, name, num, level);
939     qtest_rsp(s, 0);
940 }
941 
942 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
943 {
944     qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
945     qtest_rsp(s, 0);
946 }
947 
948 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
949 {
950     qtest_out(s, "outb", addr, value);
951 }
952 
953 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
954 {
955     qtest_out(s, "outw", addr, value);
956 }
957 
958 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
959 {
960     qtest_out(s, "outl", addr, value);
961 }
962 
963 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
964 {
965     gchar **args;
966     int ret;
967     unsigned long value;
968 
969     qtest_sendf(s, "%s 0x%x\n", cmd, addr);
970     args = qtest_rsp(s, 2);
971     ret = qemu_strtoul(args[1], NULL, 0, &value);
972     g_assert(!ret && value <= UINT32_MAX);
973     g_strfreev(args);
974 
975     return value;
976 }
977 
978 uint8_t qtest_inb(QTestState *s, uint16_t addr)
979 {
980     return qtest_in(s, "inb", addr);
981 }
982 
983 uint16_t qtest_inw(QTestState *s, uint16_t addr)
984 {
985     return qtest_in(s, "inw", addr);
986 }
987 
988 uint32_t qtest_inl(QTestState *s, uint16_t addr)
989 {
990     return qtest_in(s, "inl", addr);
991 }
992 
993 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
994                         uint64_t value)
995 {
996     qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
997     qtest_rsp(s, 0);
998 }
999 
1000 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
1001 {
1002     qtest_write(s, "writeb", addr, value);
1003 }
1004 
1005 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
1006 {
1007     qtest_write(s, "writew", addr, value);
1008 }
1009 
1010 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
1011 {
1012     qtest_write(s, "writel", addr, value);
1013 }
1014 
1015 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
1016 {
1017     qtest_write(s, "writeq", addr, value);
1018 }
1019 
1020 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
1021 {
1022     gchar **args;
1023     int ret;
1024     uint64_t value;
1025 
1026     qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
1027     args = qtest_rsp(s, 2);
1028     ret = qemu_strtou64(args[1], NULL, 0, &value);
1029     g_assert(!ret);
1030     g_strfreev(args);
1031 
1032     return value;
1033 }
1034 
1035 uint8_t qtest_readb(QTestState *s, uint64_t addr)
1036 {
1037     return qtest_read(s, "readb", addr);
1038 }
1039 
1040 uint16_t qtest_readw(QTestState *s, uint64_t addr)
1041 {
1042     return qtest_read(s, "readw", addr);
1043 }
1044 
1045 uint32_t qtest_readl(QTestState *s, uint64_t addr)
1046 {
1047     return qtest_read(s, "readl", addr);
1048 }
1049 
1050 uint64_t qtest_readq(QTestState *s, uint64_t addr)
1051 {
1052     return qtest_read(s, "readq", addr);
1053 }
1054 
1055 static int hex2nib(char ch)
1056 {
1057     if (ch >= '0' && ch <= '9') {
1058         return ch - '0';
1059     } else if (ch >= 'a' && ch <= 'f') {
1060         return 10 + (ch - 'a');
1061     } else if (ch >= 'A' && ch <= 'F') {
1062         return 10 + (ch - 'a');
1063     } else {
1064         return -1;
1065     }
1066 }
1067 
1068 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
1069 {
1070     uint8_t *ptr = data;
1071     gchar **args;
1072     size_t i;
1073 
1074     if (!size) {
1075         return;
1076     }
1077 
1078     qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
1079     args = qtest_rsp(s, 2);
1080 
1081     for (i = 0; i < size; i++) {
1082         ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
1083         ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
1084     }
1085 
1086     g_strfreev(args);
1087 }
1088 
1089 uint64_t qtest_rtas_call(QTestState *s, const char *name,
1090                          uint32_t nargs, uint64_t args,
1091                          uint32_t nret, uint64_t ret)
1092 {
1093     qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n",
1094                 name, nargs, args, nret, ret);
1095     qtest_rsp(s, 0);
1096     return 0;
1097 }
1098 
1099 void qtest_add_func(const char *str, void (*fn)(void))
1100 {
1101     gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1102     g_test_add_func(path, fn);
1103     g_free(path);
1104 }
1105 
1106 void qtest_add_data_func_full(const char *str, void *data,
1107                               void (*fn)(const void *),
1108                               GDestroyNotify data_free_func)
1109 {
1110     gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1111     g_test_add_data_func_full(path, data, fn, data_free_func);
1112     g_free(path);
1113 }
1114 
1115 void qtest_add_data_func(const char *str, const void *data,
1116                          void (*fn)(const void *))
1117 {
1118     gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1119     g_test_add_data_func(path, data, fn);
1120     g_free(path);
1121 }
1122 
1123 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1124 {
1125     gchar *bdata;
1126 
1127     bdata = g_base64_encode(data, size);
1128     qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
1129     s->ops.send(s, bdata);
1130     s->ops.send(s, "\n");
1131     qtest_rsp(s, 0);
1132     g_free(bdata);
1133 }
1134 
1135 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
1136 {
1137     gchar **args;
1138     size_t len;
1139 
1140     qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
1141     args = qtest_rsp(s, 2);
1142 
1143     g_base64_decode_inplace(args[1], &len);
1144     if (size != len) {
1145         fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
1146                 size, len);
1147         len = MIN(len, size);
1148     }
1149 
1150     memcpy(data, args[1], len);
1151     g_strfreev(args);
1152 }
1153 
1154 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1155 {
1156     const uint8_t *ptr = data;
1157     size_t i;
1158     char *enc;
1159 
1160     if (!size) {
1161         return;
1162     }
1163 
1164     enc = g_malloc(2 * size + 1);
1165 
1166     for (i = 0; i < size; i++) {
1167         sprintf(&enc[i * 2], "%02x", ptr[i]);
1168     }
1169 
1170     qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
1171     qtest_rsp(s, 0);
1172     g_free(enc);
1173 }
1174 
1175 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
1176 {
1177     qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
1178     qtest_rsp(s, 0);
1179 }
1180 
1181 void qtest_qmp_assert_success(QTestState *qts, const char *fmt, ...)
1182 {
1183     va_list ap;
1184     QDict *response;
1185 
1186     va_start(ap, fmt);
1187     response = qtest_vqmp(qts, fmt, ap);
1188     va_end(ap);
1189 
1190     g_assert(response);
1191     if (!qdict_haskey(response, "return")) {
1192         QString *s = qobject_to_json_pretty(QOBJECT(response));
1193         g_test_message("%s", qstring_get_str(s));
1194         qobject_unref(s);
1195     }
1196     g_assert(qdict_haskey(response, "return"));
1197     qobject_unref(response);
1198 }
1199 
1200 bool qtest_big_endian(QTestState *s)
1201 {
1202     return s->big_endian;
1203 }
1204 
1205 static bool qtest_check_machine_version(const char *mname, const char *basename,
1206                                         int major, int minor)
1207 {
1208     char *newname;
1209     bool is_equal;
1210 
1211     newname = g_strdup_printf("%s-%i.%i", basename, major, minor);
1212     is_equal = g_str_equal(mname, newname);
1213     g_free(newname);
1214 
1215     return is_equal;
1216 }
1217 
1218 static bool qtest_is_old_versioned_machine(const char *mname)
1219 {
1220     const char *dash = strrchr(mname, '-');
1221     const char *dot = strrchr(mname, '.');
1222     const char *chr;
1223     char *bname;
1224     const int major = QEMU_VERSION_MAJOR;
1225     const int minor = QEMU_VERSION_MINOR;
1226     bool res = false;
1227 
1228     if (dash && dot && dot > dash) {
1229         for (chr = dash + 1; *chr; chr++) {
1230             if (!qemu_isdigit(*chr) && *chr != '.') {
1231                 return false;
1232             }
1233         }
1234         /*
1235          * Now check if it is one of the latest versions. Check major + 1
1236          * and minor + 1 versions as well, since they might already exist
1237          * in the development branch.
1238          */
1239         bname = g_strdup(mname);
1240         bname[dash - mname] = 0;
1241         res = !qtest_check_machine_version(mname, bname, major + 1, 0) &&
1242               !qtest_check_machine_version(mname, bname, major, minor + 1) &&
1243               !qtest_check_machine_version(mname, bname, major, minor);
1244         g_free(bname);
1245     }
1246 
1247     return res;
1248 }
1249 
1250 void qtest_cb_for_every_machine(void (*cb)(const char *machine),
1251                                 bool skip_old_versioned)
1252 {
1253     QDict *response, *minfo;
1254     QList *list;
1255     const QListEntry *p;
1256     QObject *qobj;
1257     QString *qstr;
1258     const char *mname;
1259     QTestState *qts;
1260 
1261     qts = qtest_init("-machine none");
1262     response = qtest_qmp(qts, "{ 'execute': 'query-machines' }");
1263     g_assert(response);
1264     list = qdict_get_qlist(response, "return");
1265     g_assert(list);
1266 
1267     for (p = qlist_first(list); p; p = qlist_next(p)) {
1268         minfo = qobject_to(QDict, qlist_entry_obj(p));
1269         g_assert(minfo);
1270         qobj = qdict_get(minfo, "name");
1271         g_assert(qobj);
1272         qstr = qobject_to(QString, qobj);
1273         g_assert(qstr);
1274         mname = qstring_get_str(qstr);
1275         /* Ignore machines that cannot be used for qtests */
1276         if (!memcmp("xenfv", mname, 5) || g_str_equal("xenpv", mname)) {
1277             continue;
1278         }
1279         if (!skip_old_versioned || !qtest_is_old_versioned_machine(mname)) {
1280             cb(mname);
1281         }
1282     }
1283 
1284     qtest_quit(qts);
1285     qobject_unref(response);
1286 }
1287 
1288 /*
1289  * Generic hot-plugging test via the device_add QMP commands.
1290  */
1291 void qtest_qmp_device_add_qdict(QTestState *qts, const char *drv,
1292                                 const QDict *arguments)
1293 {
1294     QDict *resp;
1295     QDict *args = arguments ? qdict_clone_shallow(arguments) : qdict_new();
1296 
1297     g_assert(!qdict_haskey(args, "driver"));
1298     qdict_put_str(args, "driver", drv);
1299     resp = qtest_qmp(qts, "{'execute': 'device_add', 'arguments': %p}", args);
1300     g_assert(resp);
1301     g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1302     g_assert(!qdict_haskey(resp, "error"));
1303     qobject_unref(resp);
1304 }
1305 
1306 void qtest_qmp_device_add(QTestState *qts, const char *driver, const char *id,
1307                           const char *fmt, ...)
1308 {
1309     QDict *args;
1310     va_list ap;
1311 
1312     va_start(ap, fmt);
1313     args = qdict_from_vjsonf_nofail(fmt, ap);
1314     va_end(ap);
1315 
1316     g_assert(!qdict_haskey(args, "id"));
1317     qdict_put_str(args, "id", id);
1318 
1319     qtest_qmp_device_add_qdict(qts, driver, args);
1320     qobject_unref(args);
1321 }
1322 
1323 
1324 /*
1325  * Generic hot-unplugging test via the device_del QMP command.
1326  * Device deletion will get one response and one event. For example:
1327  *
1328  * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1329  *
1330  * will get this one:
1331  *
1332  * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1333  *  "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1334  *  "path": "/machine/peripheral/scsi-hd"}}
1335  *
1336  * and this one:
1337  *
1338  * {"return": {}}
1339  */
1340 void qtest_qmp_device_del(QTestState *qts, const char *id)
1341 {
1342     QDict *rsp;
1343 
1344     rsp = qtest_qmp(qts, "{'execute': 'device_del', 'arguments': {'id': %s}}",
1345                     id);
1346 
1347     g_assert(qdict_haskey(rsp, "return"));
1348     qobject_unref(rsp);
1349     qtest_qmp_eventwait(qts, "DEVICE_DELETED");
1350 }
1351 
1352 bool qmp_rsp_is_err(QDict *rsp)
1353 {
1354     QDict *error = qdict_get_qdict(rsp, "error");
1355     qobject_unref(rsp);
1356     return !!error;
1357 }
1358 
1359 void qmp_expect_error_and_unref(QDict *rsp, const char *class)
1360 {
1361     QDict *error = qdict_get_qdict(rsp, "error");
1362 
1363     g_assert_cmpstr(qdict_get_try_str(error, "class"), ==, class);
1364     g_assert_nonnull(qdict_get_try_str(error, "desc"));
1365     g_assert(!qdict_haskey(rsp, "return"));
1366 
1367     qobject_unref(rsp);
1368 }
1369 
1370 static void qtest_client_set_tx_handler(QTestState *s,
1371                     QTestSendFn send)
1372 {
1373     s->ops.send = send;
1374 }
1375 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv)
1376 {
1377     s->ops.recv_line = recv;
1378 }
1379 /* A type-safe wrapper for s->send() */
1380 static void send_wrapper(QTestState *s, const char *buf)
1381 {
1382     s->ops.external_send(s, buf);
1383 }
1384 
1385 static GString *qtest_client_inproc_recv_line(QTestState *s)
1386 {
1387     GString *line;
1388     size_t offset;
1389     char *eol;
1390 
1391     eol = strchr(s->rx->str, '\n');
1392     offset = eol - s->rx->str;
1393     line = g_string_new_len(s->rx->str, offset);
1394     g_string_erase(s->rx, 0, offset + 1);
1395     return line;
1396 }
1397 
1398 QTestState *qtest_inproc_init(QTestState **s, bool log, const char* arch,
1399                     void (*send)(void*, const char*))
1400 {
1401     QTestState *qts;
1402     qts = g_new0(QTestState, 1);
1403     qts->pending_events = NULL;
1404     *s = qts; /* Expose qts early on, since the query endianness relies on it */
1405     qts->wstatus = 0;
1406     for (int i = 0; i < MAX_IRQ; i++) {
1407         qts->irq_level[i] = false;
1408     }
1409 
1410     qtest_client_set_rx_handler(qts, qtest_client_inproc_recv_line);
1411 
1412     /* send() may not have a matching protoype, so use a type-safe wrapper */
1413     qts->ops.external_send = send;
1414     qtest_client_set_tx_handler(qts, send_wrapper);
1415 
1416     qts->big_endian = qtest_query_target_endianness(qts);
1417 
1418     /*
1419      * Set a dummy path for QTEST_QEMU_BINARY. Doesn't need to exist, but this
1420      * way, qtest_get_arch works for inproc qtest.
1421      */
1422     gchar *bin_path = g_strconcat("/qemu-system-", arch, NULL);
1423     setenv("QTEST_QEMU_BINARY", bin_path, 0);
1424     g_free(bin_path);
1425 
1426     return qts;
1427 }
1428 
1429 void qtest_client_inproc_recv(void *opaque, const char *str)
1430 {
1431     QTestState *qts = *(QTestState **)opaque;
1432 
1433     if (!qts->rx) {
1434         qts->rx = g_string_new(NULL);
1435     }
1436     g_string_append(qts->rx, str);
1437     return;
1438 }
1439