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