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