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