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