xref: /openbmc/qemu/tests/qtest/libqtest.c (revision b21e2380)
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_has_accel(const char *accel_name)
926 {
927     if (g_str_equal(accel_name, "tcg")) {
928 #if defined(CONFIG_TCG)
929         return true;
930 #else
931         return false;
932 #endif
933     } else if (g_str_equal(accel_name, "kvm")) {
934         int i;
935         const char *arch = qtest_get_arch();
936         const char *targets[] = { CONFIG_KVM_TARGETS };
937 
938         for (i = 0; i < ARRAY_SIZE(targets); i++) {
939             if (!strncmp(targets[i], arch, strlen(arch))) {
940                 if (!access("/dev/kvm", R_OK | W_OK)) {
941                     return true;
942                 }
943             }
944         }
945     } else {
946         /* not implemented */
947         g_assert_not_reached();
948     }
949     return false;
950 }
951 
952 bool qtest_get_irq(QTestState *s, int num)
953 {
954     /* dummy operation in order to make sure irq is up to date */
955     qtest_inb(s, 0);
956 
957     return s->irq_level[num];
958 }
959 
960 void qtest_module_load(QTestState *s, const char *prefix, const char *libname)
961 {
962     qtest_sendf(s, "module_load %s %s\n", prefix, libname);
963     qtest_rsp(s);
964 }
965 
966 static int64_t qtest_clock_rsp(QTestState *s)
967 {
968     gchar **words;
969     int64_t clock;
970     words = qtest_rsp_args(s, 2);
971     clock = g_ascii_strtoll(words[1], NULL, 0);
972     g_strfreev(words);
973     return clock;
974 }
975 
976 int64_t qtest_clock_step_next(QTestState *s)
977 {
978     qtest_sendf(s, "clock_step\n");
979     return qtest_clock_rsp(s);
980 }
981 
982 int64_t qtest_clock_step(QTestState *s, int64_t step)
983 {
984     qtest_sendf(s, "clock_step %"PRIi64"\n", step);
985     return qtest_clock_rsp(s);
986 }
987 
988 int64_t qtest_clock_set(QTestState *s, int64_t val)
989 {
990     qtest_sendf(s, "clock_set %"PRIi64"\n", val);
991     return qtest_clock_rsp(s);
992 }
993 
994 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
995 {
996     qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
997     qtest_rsp(s);
998 }
999 
1000 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
1001 {
1002     qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
1003     qtest_rsp(s);
1004 }
1005 
1006 void qtest_set_irq_in(QTestState *s, const char *qom_path, const char *name,
1007                       int num, int level)
1008 {
1009     if (!name) {
1010         name = "unnamed-gpio-in";
1011     }
1012     qtest_sendf(s, "set_irq_in %s %s %d %d\n", qom_path, name, num, level);
1013     qtest_rsp(s);
1014 }
1015 
1016 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
1017 {
1018     qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
1019     qtest_rsp(s);
1020 }
1021 
1022 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
1023 {
1024     qtest_out(s, "outb", addr, value);
1025 }
1026 
1027 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
1028 {
1029     qtest_out(s, "outw", addr, value);
1030 }
1031 
1032 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
1033 {
1034     qtest_out(s, "outl", addr, value);
1035 }
1036 
1037 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
1038 {
1039     gchar **args;
1040     int ret;
1041     unsigned long value;
1042 
1043     qtest_sendf(s, "%s 0x%x\n", cmd, addr);
1044     args = qtest_rsp_args(s, 2);
1045     ret = qemu_strtoul(args[1], NULL, 0, &value);
1046     g_assert(!ret && value <= UINT32_MAX);
1047     g_strfreev(args);
1048 
1049     return value;
1050 }
1051 
1052 uint8_t qtest_inb(QTestState *s, uint16_t addr)
1053 {
1054     return qtest_in(s, "inb", addr);
1055 }
1056 
1057 uint16_t qtest_inw(QTestState *s, uint16_t addr)
1058 {
1059     return qtest_in(s, "inw", addr);
1060 }
1061 
1062 uint32_t qtest_inl(QTestState *s, uint16_t addr)
1063 {
1064     return qtest_in(s, "inl", addr);
1065 }
1066 
1067 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
1068                         uint64_t value)
1069 {
1070     qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
1071     qtest_rsp(s);
1072 }
1073 
1074 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
1075 {
1076     qtest_write(s, "writeb", addr, value);
1077 }
1078 
1079 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
1080 {
1081     qtest_write(s, "writew", addr, value);
1082 }
1083 
1084 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
1085 {
1086     qtest_write(s, "writel", addr, value);
1087 }
1088 
1089 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
1090 {
1091     qtest_write(s, "writeq", addr, value);
1092 }
1093 
1094 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
1095 {
1096     gchar **args;
1097     int ret;
1098     uint64_t value;
1099 
1100     qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
1101     args = qtest_rsp_args(s, 2);
1102     ret = qemu_strtou64(args[1], NULL, 0, &value);
1103     g_assert(!ret);
1104     g_strfreev(args);
1105 
1106     return value;
1107 }
1108 
1109 uint8_t qtest_readb(QTestState *s, uint64_t addr)
1110 {
1111     return qtest_read(s, "readb", addr);
1112 }
1113 
1114 uint16_t qtest_readw(QTestState *s, uint64_t addr)
1115 {
1116     return qtest_read(s, "readw", addr);
1117 }
1118 
1119 uint32_t qtest_readl(QTestState *s, uint64_t addr)
1120 {
1121     return qtest_read(s, "readl", addr);
1122 }
1123 
1124 uint64_t qtest_readq(QTestState *s, uint64_t addr)
1125 {
1126     return qtest_read(s, "readq", addr);
1127 }
1128 
1129 static int hex2nib(char ch)
1130 {
1131     if (ch >= '0' && ch <= '9') {
1132         return ch - '0';
1133     } else if (ch >= 'a' && ch <= 'f') {
1134         return 10 + (ch - 'a');
1135     } else if (ch >= 'A' && ch <= 'F') {
1136         return 10 + (ch - 'a');
1137     } else {
1138         return -1;
1139     }
1140 }
1141 
1142 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
1143 {
1144     uint8_t *ptr = data;
1145     gchar **args;
1146     size_t i;
1147 
1148     if (!size) {
1149         return;
1150     }
1151 
1152     qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
1153     args = qtest_rsp_args(s, 2);
1154 
1155     for (i = 0; i < size; i++) {
1156         ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
1157         ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
1158     }
1159 
1160     g_strfreev(args);
1161 }
1162 
1163 uint64_t qtest_rtas_call(QTestState *s, const char *name,
1164                          uint32_t nargs, uint64_t args,
1165                          uint32_t nret, uint64_t ret)
1166 {
1167     qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n",
1168                 name, nargs, args, nret, ret);
1169     qtest_rsp(s);
1170     return 0;
1171 }
1172 
1173 void qtest_add_func(const char *str, void (*fn)(void))
1174 {
1175     gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1176     g_test_add_func(path, fn);
1177     g_free(path);
1178 }
1179 
1180 void qtest_add_data_func_full(const char *str, void *data,
1181                               void (*fn)(const void *),
1182                               GDestroyNotify data_free_func)
1183 {
1184     gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1185     g_test_add_data_func_full(path, data, fn, data_free_func);
1186     g_free(path);
1187 }
1188 
1189 void qtest_add_data_func(const char *str, const void *data,
1190                          void (*fn)(const void *))
1191 {
1192     gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1193     g_test_add_data_func(path, data, fn);
1194     g_free(path);
1195 }
1196 
1197 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1198 {
1199     gchar *bdata;
1200 
1201     bdata = g_base64_encode(data, size);
1202     qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
1203     s->ops.send(s, bdata);
1204     s->ops.send(s, "\n");
1205     qtest_rsp(s);
1206     g_free(bdata);
1207 }
1208 
1209 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
1210 {
1211     gchar **args;
1212     size_t len;
1213 
1214     qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
1215     args = qtest_rsp_args(s, 2);
1216 
1217     g_base64_decode_inplace(args[1], &len);
1218     if (size != len) {
1219         fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
1220                 size, len);
1221         len = MIN(len, size);
1222     }
1223 
1224     memcpy(data, args[1], len);
1225     g_strfreev(args);
1226 }
1227 
1228 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1229 {
1230     const uint8_t *ptr = data;
1231     size_t i;
1232     char *enc;
1233 
1234     if (!size) {
1235         return;
1236     }
1237 
1238     enc = g_malloc(2 * size + 1);
1239 
1240     for (i = 0; i < size; i++) {
1241         sprintf(&enc[i * 2], "%02x", ptr[i]);
1242     }
1243 
1244     qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
1245     qtest_rsp(s);
1246     g_free(enc);
1247 }
1248 
1249 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
1250 {
1251     qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
1252     qtest_rsp(s);
1253 }
1254 
1255 void qtest_qmp_assert_success(QTestState *qts, const char *fmt, ...)
1256 {
1257     va_list ap;
1258     QDict *response;
1259 
1260     va_start(ap, fmt);
1261     response = qtest_vqmp(qts, fmt, ap);
1262     va_end(ap);
1263 
1264     g_assert(response);
1265     if (!qdict_haskey(response, "return")) {
1266         GString *s = qobject_to_json_pretty(QOBJECT(response), true);
1267         g_test_message("%s", s->str);
1268         g_string_free(s, true);
1269     }
1270     g_assert(qdict_haskey(response, "return"));
1271     qobject_unref(response);
1272 }
1273 
1274 bool qtest_big_endian(QTestState *s)
1275 {
1276     return s->big_endian;
1277 }
1278 
1279 static bool qtest_check_machine_version(const char *mname, const char *basename,
1280                                         int major, int minor)
1281 {
1282     char *newname;
1283     bool is_equal;
1284 
1285     newname = g_strdup_printf("%s-%i.%i", basename, major, minor);
1286     is_equal = g_str_equal(mname, newname);
1287     g_free(newname);
1288 
1289     return is_equal;
1290 }
1291 
1292 static bool qtest_is_old_versioned_machine(const char *mname)
1293 {
1294     const char *dash = strrchr(mname, '-');
1295     const char *dot = strrchr(mname, '.');
1296     const char *chr;
1297     char *bname;
1298     const int major = QEMU_VERSION_MAJOR;
1299     const int minor = QEMU_VERSION_MINOR;
1300     bool res = false;
1301 
1302     if (dash && dot && dot > dash) {
1303         for (chr = dash + 1; *chr; chr++) {
1304             if (!qemu_isdigit(*chr) && *chr != '.') {
1305                 return false;
1306             }
1307         }
1308         /*
1309          * Now check if it is one of the latest versions. Check major + 1
1310          * and minor + 1 versions as well, since they might already exist
1311          * in the development branch.
1312          */
1313         bname = g_strdup(mname);
1314         bname[dash - mname] = 0;
1315         res = !qtest_check_machine_version(mname, bname, major + 1, 0) &&
1316               !qtest_check_machine_version(mname, bname, major, minor + 1) &&
1317               !qtest_check_machine_version(mname, bname, major, minor);
1318         g_free(bname);
1319     }
1320 
1321     return res;
1322 }
1323 
1324 struct MachInfo {
1325     char *name;
1326     char *alias;
1327 };
1328 
1329 /*
1330  * Returns an array with pointers to the available machine names.
1331  * The terminating entry has the name set to NULL.
1332  */
1333 static struct MachInfo *qtest_get_machines(void)
1334 {
1335     static struct MachInfo *machines;
1336     QDict *response, *minfo;
1337     QList *list;
1338     const QListEntry *p;
1339     QObject *qobj;
1340     QString *qstr;
1341     QTestState *qts;
1342     int idx;
1343 
1344     if (machines) {
1345         return machines;
1346     }
1347 
1348     qts = qtest_init("-machine none");
1349     response = qtest_qmp(qts, "{ 'execute': 'query-machines' }");
1350     g_assert(response);
1351     list = qdict_get_qlist(response, "return");
1352     g_assert(list);
1353 
1354     machines = g_new(struct MachInfo, qlist_size(list) + 1);
1355 
1356     for (p = qlist_first(list), idx = 0; p; p = qlist_next(p), idx++) {
1357         minfo = qobject_to(QDict, qlist_entry_obj(p));
1358         g_assert(minfo);
1359 
1360         qobj = qdict_get(minfo, "name");
1361         g_assert(qobj);
1362         qstr = qobject_to(QString, qobj);
1363         g_assert(qstr);
1364         machines[idx].name = g_strdup(qstring_get_str(qstr));
1365 
1366         qobj = qdict_get(minfo, "alias");
1367         if (qobj) {                               /* The alias is optional */
1368             qstr = qobject_to(QString, qobj);
1369             g_assert(qstr);
1370             machines[idx].alias = g_strdup(qstring_get_str(qstr));
1371         } else {
1372             machines[idx].alias = NULL;
1373         }
1374     }
1375 
1376     qtest_quit(qts);
1377     qobject_unref(response);
1378 
1379     memset(&machines[idx], 0, sizeof(struct MachInfo)); /* Terminating entry */
1380     return machines;
1381 }
1382 
1383 void qtest_cb_for_every_machine(void (*cb)(const char *machine),
1384                                 bool skip_old_versioned)
1385 {
1386     struct MachInfo *machines;
1387     int i;
1388 
1389     machines = qtest_get_machines();
1390 
1391     for (i = 0; machines[i].name != NULL; i++) {
1392         /* Ignore machines that cannot be used for qtests */
1393         if (!strncmp("xenfv", machines[i].name, 5) ||
1394             g_str_equal("xenpv", machines[i].name)) {
1395             continue;
1396         }
1397         if (!skip_old_versioned ||
1398             !qtest_is_old_versioned_machine(machines[i].name)) {
1399             cb(machines[i].name);
1400         }
1401     }
1402 }
1403 
1404 bool qtest_has_machine(const char *machine)
1405 {
1406     struct MachInfo *machines;
1407     int i;
1408 
1409     machines = qtest_get_machines();
1410 
1411     for (i = 0; machines[i].name != NULL; i++) {
1412         if (g_str_equal(machine, machines[i].name) ||
1413             (machines[i].alias && g_str_equal(machine, machines[i].alias))) {
1414             return true;
1415         }
1416     }
1417 
1418     return false;
1419 }
1420 
1421 bool qtest_has_device(const char *device)
1422 {
1423     static QList *list;
1424     const QListEntry *p;
1425     QObject *qobj;
1426     QString *qstr;
1427     QDict *devinfo;
1428     int idx;
1429 
1430     if (!list) {
1431         QDict *resp;
1432         QDict *args;
1433         QTestState *qts = qtest_init("-machine none");
1434 
1435         args = qdict_new();
1436         qdict_put_bool(args, "abstract", false);
1437         qdict_put_str(args, "implements", "device");
1438 
1439         resp = qtest_qmp(qts, "{'execute': 'qom-list-types', 'arguments': %p }",
1440                          args);
1441         g_assert(qdict_haskey(resp, "return"));
1442         list = qdict_get_qlist(resp, "return");
1443         qobject_ref(list);
1444         qobject_unref(resp);
1445 
1446         qtest_quit(qts);
1447     }
1448 
1449     for (p = qlist_first(list), idx = 0; p; p = qlist_next(p), idx++) {
1450         devinfo = qobject_to(QDict, qlist_entry_obj(p));
1451         g_assert(devinfo);
1452 
1453         qobj = qdict_get(devinfo, "name");
1454         g_assert(qobj);
1455         qstr = qobject_to(QString, qobj);
1456         g_assert(qstr);
1457         if (g_str_equal(qstring_get_str(qstr), device)) {
1458             return true;
1459         }
1460     }
1461 
1462     return false;
1463 }
1464 
1465 /*
1466  * Generic hot-plugging test via the device_add QMP commands.
1467  */
1468 void qtest_qmp_device_add_qdict(QTestState *qts, const char *drv,
1469                                 const QDict *arguments)
1470 {
1471     QDict *resp;
1472     QDict *args = arguments ? qdict_clone_shallow(arguments) : qdict_new();
1473 
1474     g_assert(!qdict_haskey(args, "driver"));
1475     qdict_put_str(args, "driver", drv);
1476     resp = qtest_qmp(qts, "{'execute': 'device_add', 'arguments': %p}", args);
1477     g_assert(resp);
1478     g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1479     g_assert(!qdict_haskey(resp, "error"));
1480     qobject_unref(resp);
1481 }
1482 
1483 void qtest_qmp_device_add(QTestState *qts, const char *driver, const char *id,
1484                           const char *fmt, ...)
1485 {
1486     QDict *args;
1487     va_list ap;
1488 
1489     va_start(ap, fmt);
1490     args = qdict_from_vjsonf_nofail(fmt, ap);
1491     va_end(ap);
1492 
1493     g_assert(!qdict_haskey(args, "id"));
1494     qdict_put_str(args, "id", id);
1495 
1496     qtest_qmp_device_add_qdict(qts, driver, args);
1497     qobject_unref(args);
1498 }
1499 
1500 void qtest_qmp_add_client(QTestState *qts, const char *protocol, int fd)
1501 {
1502     QDict *resp;
1503 
1504     resp = qtest_qmp_fds(qts, &fd, 1, "{'execute': 'getfd',"
1505                          "'arguments': {'fdname': 'fdname'}}");
1506     g_assert(resp);
1507     g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1508     g_assert(!qdict_haskey(resp, "error"));
1509     qobject_unref(resp);
1510 
1511     resp = qtest_qmp(
1512         qts, "{'execute': 'add_client',"
1513         "'arguments': {'protocol': %s, 'fdname': 'fdname'}}", protocol);
1514     g_assert(resp);
1515     g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1516     g_assert(!qdict_haskey(resp, "error"));
1517     qobject_unref(resp);
1518 }
1519 
1520 /*
1521  * Generic hot-unplugging test via the device_del QMP command.
1522  * Device deletion will get one response and one event. For example:
1523  *
1524  * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1525  *
1526  * will get this one:
1527  *
1528  * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1529  *  "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1530  *  "path": "/machine/peripheral/scsi-hd"}}
1531  *
1532  * and this one:
1533  *
1534  * {"return": {}}
1535  */
1536 void qtest_qmp_device_del(QTestState *qts, const char *id)
1537 {
1538     QDict *rsp;
1539 
1540     rsp = qtest_qmp(qts, "{'execute': 'device_del', 'arguments': {'id': %s}}",
1541                     id);
1542 
1543     g_assert(qdict_haskey(rsp, "return"));
1544     qobject_unref(rsp);
1545     qtest_qmp_eventwait(qts, "DEVICE_DELETED");
1546 }
1547 
1548 bool qmp_rsp_is_err(QDict *rsp)
1549 {
1550     QDict *error = qdict_get_qdict(rsp, "error");
1551     qobject_unref(rsp);
1552     return !!error;
1553 }
1554 
1555 void qmp_expect_error_and_unref(QDict *rsp, const char *class)
1556 {
1557     QDict *error = qdict_get_qdict(rsp, "error");
1558 
1559     g_assert_cmpstr(qdict_get_try_str(error, "class"), ==, class);
1560     g_assert_nonnull(qdict_get_try_str(error, "desc"));
1561     g_assert(!qdict_haskey(rsp, "return"));
1562 
1563     qobject_unref(rsp);
1564 }
1565 
1566 static void qtest_client_set_tx_handler(QTestState *s,
1567                     QTestSendFn send)
1568 {
1569     s->ops.send = send;
1570 }
1571 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv)
1572 {
1573     s->ops.recv_line = recv;
1574 }
1575 /* A type-safe wrapper for s->send() */
1576 static void send_wrapper(QTestState *s, const char *buf)
1577 {
1578     s->ops.external_send(s, buf);
1579 }
1580 
1581 static GString *qtest_client_inproc_recv_line(QTestState *s)
1582 {
1583     GString *line;
1584     size_t offset;
1585     char *eol;
1586 
1587     eol = strchr(s->rx->str, '\n');
1588     offset = eol - s->rx->str;
1589     line = g_string_new_len(s->rx->str, offset);
1590     g_string_erase(s->rx, 0, offset + 1);
1591     return line;
1592 }
1593 
1594 QTestState *qtest_inproc_init(QTestState **s, bool log, const char* arch,
1595                     void (*send)(void*, const char*))
1596 {
1597     QTestState *qts;
1598     qts = g_new0(QTestState, 1);
1599     qts->pending_events = NULL;
1600     *s = qts; /* Expose qts early on, since the query endianness relies on it */
1601     qts->wstatus = 0;
1602     for (int i = 0; i < MAX_IRQ; i++) {
1603         qts->irq_level[i] = false;
1604     }
1605 
1606     qtest_client_set_rx_handler(qts, qtest_client_inproc_recv_line);
1607 
1608     /* send() may not have a matching protoype, so use a type-safe wrapper */
1609     qts->ops.external_send = send;
1610     qtest_client_set_tx_handler(qts, send_wrapper);
1611 
1612     qts->big_endian = qtest_query_target_endianness(qts);
1613 
1614     /*
1615      * Set a dummy path for QTEST_QEMU_BINARY. Doesn't need to exist, but this
1616      * way, qtest_get_arch works for inproc qtest.
1617      */
1618     gchar *bin_path = g_strconcat("/qemu-system-", arch, NULL);
1619     setenv("QTEST_QEMU_BINARY", bin_path, 0);
1620     g_free(bin_path);
1621 
1622     return qts;
1623 }
1624 
1625 void qtest_client_inproc_recv(void *opaque, const char *str)
1626 {
1627     QTestState *qts = *(QTestState **)opaque;
1628 
1629     if (!qts->rx) {
1630         qts->rx = g_string_new(NULL);
1631     }
1632     g_string_append(qts->rx, str);
1633     return;
1634 }
1635