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