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