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