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