xref: /openbmc/qemu/tests/qtest/libqtest.c (revision c79aa350)
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     pid = RETRY_ON_EINTR(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     ret = RETRY_ON_EINTR(bind(sock, (struct sockaddr *)&addr, sizeof(addr)));
693     g_assert_cmpint(ret, !=, -1);
694     ret = listen(sock, 1);
695     g_assert_cmpint(ret, !=, -1);
696 
697     return sock;
698 }
699 
700 #ifndef _WIN32
701 void qtest_qmp_vsend_fds(QTestState *s, int *fds, size_t fds_num,
702                          const char *fmt, va_list ap)
703 {
704     qmp_fd_vsend_fds(s->qmp_fd, fds, fds_num, fmt, ap);
705 }
706 #endif
707 
708 void qtest_qmp_vsend(QTestState *s, const char *fmt, va_list ap)
709 {
710     qmp_fd_vsend(s->qmp_fd, fmt, ap);
711 }
712 
713 #ifndef _WIN32
714 QDict *qtest_vqmp_fds(QTestState *s, int *fds, size_t fds_num,
715                       const char *fmt, va_list ap)
716 {
717     qtest_qmp_vsend_fds(s, fds, fds_num, fmt, ap);
718 
719     /* Receive reply */
720     return qtest_qmp_receive(s);
721 }
722 #endif
723 
724 QDict *qtest_vqmp(QTestState *s, const char *fmt, va_list ap)
725 {
726     qtest_qmp_vsend(s, fmt, ap);
727 
728     /* Receive reply */
729     return qtest_qmp_receive(s);
730 }
731 
732 #ifndef _WIN32
733 QDict *qtest_qmp_fds(QTestState *s, int *fds, size_t fds_num,
734                      const char *fmt, ...)
735 {
736     va_list ap;
737     QDict *response;
738 
739     va_start(ap, fmt);
740     response = qtest_vqmp_fds(s, fds, fds_num, fmt, ap);
741     va_end(ap);
742     return response;
743 }
744 #endif
745 
746 QDict *qtest_qmp(QTestState *s, const char *fmt, ...)
747 {
748     va_list ap;
749     QDict *response;
750 
751     va_start(ap, fmt);
752     response = qtest_vqmp(s, fmt, ap);
753     va_end(ap);
754     return response;
755 }
756 
757 void qtest_qmp_send(QTestState *s, const char *fmt, ...)
758 {
759     va_list ap;
760 
761     va_start(ap, fmt);
762     qtest_qmp_vsend(s, fmt, ap);
763     va_end(ap);
764 }
765 
766 void qtest_qmp_send_raw(QTestState *s, const char *fmt, ...)
767 {
768     va_list ap;
769 
770     va_start(ap, fmt);
771     qmp_fd_vsend_raw(s->qmp_fd, fmt, ap);
772     va_end(ap);
773 }
774 
775 QDict *qtest_qmp_event_ref(QTestState *s, const char *event)
776 {
777     while (s->pending_events) {
778 
779         GList *first = s->pending_events;
780         QDict *response = (QDict *)first->data;
781 
782         s->pending_events = g_list_delete_link(s->pending_events, first);
783 
784         if (!strcmp(qdict_get_str(response, "event"), event)) {
785             return response;
786         }
787         qobject_unref(response);
788     }
789     return NULL;
790 }
791 
792 QDict *qtest_qmp_eventwait_ref(QTestState *s, const char *event)
793 {
794     QDict *response = qtest_qmp_event_ref(s, event);
795 
796     if (response) {
797         return response;
798     }
799 
800     for (;;) {
801         response = qtest_qmp_receive_dict(s);
802         if ((qdict_haskey(response, "event")) &&
803             (strcmp(qdict_get_str(response, "event"), event) == 0)) {
804             return response;
805         }
806         qobject_unref(response);
807     }
808 }
809 
810 void qtest_qmp_eventwait(QTestState *s, const char *event)
811 {
812     QDict *response;
813 
814     response = qtest_qmp_eventwait_ref(s, event);
815     qobject_unref(response);
816 }
817 
818 char *qtest_vhmp(QTestState *s, const char *fmt, va_list ap)
819 {
820     char *cmd;
821     QDict *resp;
822     char *ret;
823 
824     cmd = g_strdup_vprintf(fmt, ap);
825     resp = qtest_qmp(s, "{'execute': 'human-monitor-command',"
826                      " 'arguments': {'command-line': %s}}",
827                      cmd);
828     ret = g_strdup(qdict_get_try_str(resp, "return"));
829     g_assert(ret);
830     qobject_unref(resp);
831     g_free(cmd);
832     return ret;
833 }
834 
835 char *qtest_hmp(QTestState *s, const char *fmt, ...)
836 {
837     va_list ap;
838     char *ret;
839 
840     va_start(ap, fmt);
841     ret = qtest_vhmp(s, fmt, ap);
842     va_end(ap);
843     return ret;
844 }
845 
846 const char *qtest_get_arch(void)
847 {
848     const char *qemu = qtest_qemu_binary();
849     const char *end = strrchr(qemu, '-');
850 
851     if (!end) {
852         fprintf(stderr, "Can't determine architecture from binary name.\n");
853         exit(1);
854     }
855 
856     if (!strstr(qemu, "-system-")) {
857         fprintf(stderr, "QTEST_QEMU_BINARY must end with *-system-<arch> "
858                 "where 'arch' is the target\narchitecture (x86_64, aarch64, "
859                 "etc).\n");
860         exit(1);
861     }
862 
863     return end + 1;
864 }
865 
866 bool qtest_has_accel(const char *accel_name)
867 {
868     if (g_str_equal(accel_name, "tcg")) {
869 #if defined(CONFIG_TCG)
870         return true;
871 #else
872         return false;
873 #endif
874     } else if (g_str_equal(accel_name, "kvm")) {
875         int i;
876         const char *arch = qtest_get_arch();
877         const char *targets[] = { CONFIG_KVM_TARGETS };
878 
879         for (i = 0; i < ARRAY_SIZE(targets); i++) {
880             if (!strncmp(targets[i], arch, strlen(arch))) {
881                 if (!access("/dev/kvm", R_OK | W_OK)) {
882                     return true;
883                 }
884             }
885         }
886     } else {
887         /* not implemented */
888         g_assert_not_reached();
889     }
890     return false;
891 }
892 
893 bool qtest_get_irq(QTestState *s, int num)
894 {
895     /* dummy operation in order to make sure irq is up to date */
896     qtest_inb(s, 0);
897 
898     return s->irq_level[num];
899 }
900 
901 void qtest_module_load(QTestState *s, const char *prefix, const char *libname)
902 {
903     qtest_sendf(s, "module_load %s %s\n", prefix, libname);
904     qtest_rsp(s);
905 }
906 
907 static int64_t qtest_clock_rsp(QTestState *s)
908 {
909     gchar **words;
910     int64_t clock;
911     words = qtest_rsp_args(s, 2);
912     clock = g_ascii_strtoll(words[1], NULL, 0);
913     g_strfreev(words);
914     return clock;
915 }
916 
917 int64_t qtest_clock_step_next(QTestState *s)
918 {
919     qtest_sendf(s, "clock_step\n");
920     return qtest_clock_rsp(s);
921 }
922 
923 int64_t qtest_clock_step(QTestState *s, int64_t step)
924 {
925     qtest_sendf(s, "clock_step %"PRIi64"\n", step);
926     return qtest_clock_rsp(s);
927 }
928 
929 int64_t qtest_clock_set(QTestState *s, int64_t val)
930 {
931     qtest_sendf(s, "clock_set %"PRIi64"\n", val);
932     return qtest_clock_rsp(s);
933 }
934 
935 void qtest_irq_intercept_out(QTestState *s, const char *qom_path)
936 {
937     qtest_sendf(s, "irq_intercept_out %s\n", qom_path);
938     qtest_rsp(s);
939 }
940 
941 void qtest_irq_intercept_in(QTestState *s, const char *qom_path)
942 {
943     qtest_sendf(s, "irq_intercept_in %s\n", qom_path);
944     qtest_rsp(s);
945 }
946 
947 void qtest_set_irq_in(QTestState *s, const char *qom_path, const char *name,
948                       int num, int level)
949 {
950     if (!name) {
951         name = "unnamed-gpio-in";
952     }
953     qtest_sendf(s, "set_irq_in %s %s %d %d\n", qom_path, name, num, level);
954     qtest_rsp(s);
955 }
956 
957 static void qtest_out(QTestState *s, const char *cmd, uint16_t addr, uint32_t value)
958 {
959     qtest_sendf(s, "%s 0x%x 0x%x\n", cmd, addr, value);
960     qtest_rsp(s);
961 }
962 
963 void qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
964 {
965     qtest_out(s, "outb", addr, value);
966 }
967 
968 void qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
969 {
970     qtest_out(s, "outw", addr, value);
971 }
972 
973 void qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
974 {
975     qtest_out(s, "outl", addr, value);
976 }
977 
978 static uint32_t qtest_in(QTestState *s, const char *cmd, uint16_t addr)
979 {
980     gchar **args;
981     int ret;
982     unsigned long value;
983 
984     qtest_sendf(s, "%s 0x%x\n", cmd, addr);
985     args = qtest_rsp_args(s, 2);
986     ret = qemu_strtoul(args[1], NULL, 0, &value);
987     g_assert(!ret && value <= UINT32_MAX);
988     g_strfreev(args);
989 
990     return value;
991 }
992 
993 uint8_t qtest_inb(QTestState *s, uint16_t addr)
994 {
995     return qtest_in(s, "inb", addr);
996 }
997 
998 uint16_t qtest_inw(QTestState *s, uint16_t addr)
999 {
1000     return qtest_in(s, "inw", addr);
1001 }
1002 
1003 uint32_t qtest_inl(QTestState *s, uint16_t addr)
1004 {
1005     return qtest_in(s, "inl", addr);
1006 }
1007 
1008 static void qtest_write(QTestState *s, const char *cmd, uint64_t addr,
1009                         uint64_t value)
1010 {
1011     qtest_sendf(s, "%s 0x%" PRIx64 " 0x%" PRIx64 "\n", cmd, addr, value);
1012     qtest_rsp(s);
1013 }
1014 
1015 void qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
1016 {
1017     qtest_write(s, "writeb", addr, value);
1018 }
1019 
1020 void qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
1021 {
1022     qtest_write(s, "writew", addr, value);
1023 }
1024 
1025 void qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
1026 {
1027     qtest_write(s, "writel", addr, value);
1028 }
1029 
1030 void qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
1031 {
1032     qtest_write(s, "writeq", addr, value);
1033 }
1034 
1035 static uint64_t qtest_read(QTestState *s, const char *cmd, uint64_t addr)
1036 {
1037     gchar **args;
1038     int ret;
1039     uint64_t value;
1040 
1041     qtest_sendf(s, "%s 0x%" PRIx64 "\n", cmd, addr);
1042     args = qtest_rsp_args(s, 2);
1043     ret = qemu_strtou64(args[1], NULL, 0, &value);
1044     g_assert(!ret);
1045     g_strfreev(args);
1046 
1047     return value;
1048 }
1049 
1050 uint8_t qtest_readb(QTestState *s, uint64_t addr)
1051 {
1052     return qtest_read(s, "readb", addr);
1053 }
1054 
1055 uint16_t qtest_readw(QTestState *s, uint64_t addr)
1056 {
1057     return qtest_read(s, "readw", addr);
1058 }
1059 
1060 uint32_t qtest_readl(QTestState *s, uint64_t addr)
1061 {
1062     return qtest_read(s, "readl", addr);
1063 }
1064 
1065 uint64_t qtest_readq(QTestState *s, uint64_t addr)
1066 {
1067     return qtest_read(s, "readq", addr);
1068 }
1069 
1070 static int hex2nib(char ch)
1071 {
1072     if (ch >= '0' && ch <= '9') {
1073         return ch - '0';
1074     } else if (ch >= 'a' && ch <= 'f') {
1075         return 10 + (ch - 'a');
1076     } else if (ch >= 'A' && ch <= 'F') {
1077         return 10 + (ch - 'a');
1078     } else {
1079         return -1;
1080     }
1081 }
1082 
1083 void qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
1084 {
1085     uint8_t *ptr = data;
1086     gchar **args;
1087     size_t i;
1088 
1089     if (!size) {
1090         return;
1091     }
1092 
1093     qtest_sendf(s, "read 0x%" PRIx64 " 0x%zx\n", addr, size);
1094     args = qtest_rsp_args(s, 2);
1095 
1096     for (i = 0; i < size; i++) {
1097         ptr[i] = hex2nib(args[1][2 + (i * 2)]) << 4;
1098         ptr[i] |= hex2nib(args[1][2 + (i * 2) + 1]);
1099     }
1100 
1101     g_strfreev(args);
1102 }
1103 
1104 uint64_t qtest_rtas_call(QTestState *s, const char *name,
1105                          uint32_t nargs, uint64_t args,
1106                          uint32_t nret, uint64_t ret)
1107 {
1108     qtest_sendf(s, "rtas %s %u 0x%"PRIx64" %u 0x%"PRIx64"\n",
1109                 name, nargs, args, nret, ret);
1110     qtest_rsp(s);
1111     return 0;
1112 }
1113 
1114 void qtest_add_func(const char *str, void (*fn)(void))
1115 {
1116     gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1117     g_test_add_func(path, fn);
1118     g_free(path);
1119 }
1120 
1121 void qtest_add_data_func_full(const char *str, void *data,
1122                               void (*fn)(const void *),
1123                               GDestroyNotify data_free_func)
1124 {
1125     gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1126     g_test_add_data_func_full(path, data, fn, data_free_func);
1127     g_free(path);
1128 }
1129 
1130 void qtest_add_data_func(const char *str, const void *data,
1131                          void (*fn)(const void *))
1132 {
1133     gchar *path = g_strdup_printf("/%s/%s", qtest_get_arch(), str);
1134     g_test_add_data_func(path, data, fn);
1135     g_free(path);
1136 }
1137 
1138 void qtest_bufwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1139 {
1140     gchar *bdata;
1141 
1142     bdata = g_base64_encode(data, size);
1143     qtest_sendf(s, "b64write 0x%" PRIx64 " 0x%zx ", addr, size);
1144     s->ops.send(s, bdata);
1145     s->ops.send(s, "\n");
1146     qtest_rsp(s);
1147     g_free(bdata);
1148 }
1149 
1150 void qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
1151 {
1152     gchar **args;
1153     size_t len;
1154 
1155     qtest_sendf(s, "b64read 0x%" PRIx64 " 0x%zx\n", addr, size);
1156     args = qtest_rsp_args(s, 2);
1157 
1158     g_base64_decode_inplace(args[1], &len);
1159     if (size != len) {
1160         fprintf(stderr, "bufread: asked for %zu bytes but decoded %zu\n",
1161                 size, len);
1162         len = MIN(len, size);
1163     }
1164 
1165     memcpy(data, args[1], len);
1166     g_strfreev(args);
1167 }
1168 
1169 void qtest_memwrite(QTestState *s, uint64_t addr, const void *data, size_t size)
1170 {
1171     const uint8_t *ptr = data;
1172     size_t i;
1173     char *enc;
1174 
1175     if (!size) {
1176         return;
1177     }
1178 
1179     enc = g_malloc(2 * size + 1);
1180 
1181     for (i = 0; i < size; i++) {
1182         sprintf(&enc[i * 2], "%02x", ptr[i]);
1183     }
1184 
1185     qtest_sendf(s, "write 0x%" PRIx64 " 0x%zx 0x%s\n", addr, size, enc);
1186     qtest_rsp(s);
1187     g_free(enc);
1188 }
1189 
1190 void qtest_memset(QTestState *s, uint64_t addr, uint8_t pattern, size_t size)
1191 {
1192     qtest_sendf(s, "memset 0x%" PRIx64 " 0x%zx 0x%02x\n", addr, size, pattern);
1193     qtest_rsp(s);
1194 }
1195 
1196 void qtest_qmp_assert_success(QTestState *qts, const char *fmt, ...)
1197 {
1198     va_list ap;
1199     QDict *response;
1200 
1201     va_start(ap, fmt);
1202     response = qtest_vqmp(qts, fmt, ap);
1203     va_end(ap);
1204 
1205     g_assert(response);
1206     if (!qdict_haskey(response, "return")) {
1207         GString *s = qobject_to_json_pretty(QOBJECT(response), true);
1208         g_test_message("%s", s->str);
1209         g_string_free(s, true);
1210     }
1211     g_assert(qdict_haskey(response, "return"));
1212     qobject_unref(response);
1213 }
1214 
1215 bool qtest_big_endian(QTestState *s)
1216 {
1217     return s->big_endian;
1218 }
1219 
1220 static bool qtest_check_machine_version(const char *mname, const char *basename,
1221                                         int major, int minor)
1222 {
1223     char *newname;
1224     bool is_equal;
1225 
1226     newname = g_strdup_printf("%s-%i.%i", basename, major, minor);
1227     is_equal = g_str_equal(mname, newname);
1228     g_free(newname);
1229 
1230     return is_equal;
1231 }
1232 
1233 static bool qtest_is_old_versioned_machine(const char *mname)
1234 {
1235     const char *dash = strrchr(mname, '-');
1236     const char *dot = strrchr(mname, '.');
1237     const char *chr;
1238     char *bname;
1239     const int major = QEMU_VERSION_MAJOR;
1240     const int minor = QEMU_VERSION_MINOR;
1241     bool res = false;
1242 
1243     if (dash && dot && dot > dash) {
1244         for (chr = dash + 1; *chr; chr++) {
1245             if (!qemu_isdigit(*chr) && *chr != '.') {
1246                 return false;
1247             }
1248         }
1249         /*
1250          * Now check if it is one of the latest versions. Check major + 1
1251          * and minor + 1 versions as well, since they might already exist
1252          * in the development branch.
1253          */
1254         bname = g_strdup(mname);
1255         bname[dash - mname] = 0;
1256         res = !qtest_check_machine_version(mname, bname, major + 1, 0) &&
1257               !qtest_check_machine_version(mname, bname, major, minor + 1) &&
1258               !qtest_check_machine_version(mname, bname, major, minor);
1259         g_free(bname);
1260     }
1261 
1262     return res;
1263 }
1264 
1265 struct MachInfo {
1266     char *name;
1267     char *alias;
1268 };
1269 
1270 /*
1271  * Returns an array with pointers to the available machine names.
1272  * The terminating entry has the name set to NULL.
1273  */
1274 static struct MachInfo *qtest_get_machines(void)
1275 {
1276     static struct MachInfo *machines;
1277     QDict *response, *minfo;
1278     QList *list;
1279     const QListEntry *p;
1280     QObject *qobj;
1281     QString *qstr;
1282     QTestState *qts;
1283     int idx;
1284 
1285     if (machines) {
1286         return machines;
1287     }
1288 
1289     qts = qtest_init("-machine none");
1290     response = qtest_qmp(qts, "{ 'execute': 'query-machines' }");
1291     g_assert(response);
1292     list = qdict_get_qlist(response, "return");
1293     g_assert(list);
1294 
1295     machines = g_new(struct MachInfo, qlist_size(list) + 1);
1296 
1297     for (p = qlist_first(list), idx = 0; p; p = qlist_next(p), idx++) {
1298         minfo = qobject_to(QDict, qlist_entry_obj(p));
1299         g_assert(minfo);
1300 
1301         qobj = qdict_get(minfo, "name");
1302         g_assert(qobj);
1303         qstr = qobject_to(QString, qobj);
1304         g_assert(qstr);
1305         machines[idx].name = g_strdup(qstring_get_str(qstr));
1306 
1307         qobj = qdict_get(minfo, "alias");
1308         if (qobj) {                               /* The alias is optional */
1309             qstr = qobject_to(QString, qobj);
1310             g_assert(qstr);
1311             machines[idx].alias = g_strdup(qstring_get_str(qstr));
1312         } else {
1313             machines[idx].alias = NULL;
1314         }
1315     }
1316 
1317     qtest_quit(qts);
1318     qobject_unref(response);
1319 
1320     memset(&machines[idx], 0, sizeof(struct MachInfo)); /* Terminating entry */
1321     return machines;
1322 }
1323 
1324 void qtest_cb_for_every_machine(void (*cb)(const char *machine),
1325                                 bool skip_old_versioned)
1326 {
1327     struct MachInfo *machines;
1328     int i;
1329 
1330     machines = qtest_get_machines();
1331 
1332     for (i = 0; machines[i].name != NULL; i++) {
1333         /* Ignore machines that cannot be used for qtests */
1334         if (!strncmp("xenfv", machines[i].name, 5) ||
1335             g_str_equal("xenpv", machines[i].name)) {
1336             continue;
1337         }
1338         if (!skip_old_versioned ||
1339             !qtest_is_old_versioned_machine(machines[i].name)) {
1340             cb(machines[i].name);
1341         }
1342     }
1343 }
1344 
1345 bool qtest_has_machine(const char *machine)
1346 {
1347     struct MachInfo *machines;
1348     int i;
1349 
1350     machines = qtest_get_machines();
1351 
1352     for (i = 0; machines[i].name != NULL; i++) {
1353         if (g_str_equal(machine, machines[i].name) ||
1354             (machines[i].alias && g_str_equal(machine, machines[i].alias))) {
1355             return true;
1356         }
1357     }
1358 
1359     return false;
1360 }
1361 
1362 bool qtest_has_device(const char *device)
1363 {
1364     static QList *list;
1365     const QListEntry *p;
1366     QObject *qobj;
1367     QString *qstr;
1368     QDict *devinfo;
1369     int idx;
1370 
1371     if (!list) {
1372         QDict *resp;
1373         QDict *args;
1374         QTestState *qts = qtest_init("-machine none");
1375 
1376         args = qdict_new();
1377         qdict_put_bool(args, "abstract", false);
1378         qdict_put_str(args, "implements", "device");
1379 
1380         resp = qtest_qmp(qts, "{'execute': 'qom-list-types', 'arguments': %p }",
1381                          args);
1382         g_assert(qdict_haskey(resp, "return"));
1383         list = qdict_get_qlist(resp, "return");
1384         qobject_ref(list);
1385         qobject_unref(resp);
1386 
1387         qtest_quit(qts);
1388     }
1389 
1390     for (p = qlist_first(list), idx = 0; p; p = qlist_next(p), idx++) {
1391         devinfo = qobject_to(QDict, qlist_entry_obj(p));
1392         g_assert(devinfo);
1393 
1394         qobj = qdict_get(devinfo, "name");
1395         g_assert(qobj);
1396         qstr = qobject_to(QString, qobj);
1397         g_assert(qstr);
1398         if (g_str_equal(qstring_get_str(qstr), device)) {
1399             return true;
1400         }
1401     }
1402 
1403     return false;
1404 }
1405 
1406 /*
1407  * Generic hot-plugging test via the device_add QMP commands.
1408  */
1409 void qtest_qmp_device_add_qdict(QTestState *qts, const char *drv,
1410                                 const QDict *arguments)
1411 {
1412     QDict *resp;
1413     QDict *args = arguments ? qdict_clone_shallow(arguments) : qdict_new();
1414 
1415     g_assert(!qdict_haskey(args, "driver"));
1416     qdict_put_str(args, "driver", drv);
1417     resp = qtest_qmp(qts, "{'execute': 'device_add', 'arguments': %p}", args);
1418     g_assert(resp);
1419     g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1420     g_assert(!qdict_haskey(resp, "error"));
1421     qobject_unref(resp);
1422 }
1423 
1424 void qtest_qmp_device_add(QTestState *qts, const char *driver, const char *id,
1425                           const char *fmt, ...)
1426 {
1427     QDict *args;
1428     va_list ap;
1429 
1430     va_start(ap, fmt);
1431     args = qdict_from_vjsonf_nofail(fmt, ap);
1432     va_end(ap);
1433 
1434     g_assert(!qdict_haskey(args, "id"));
1435     qdict_put_str(args, "id", id);
1436 
1437     qtest_qmp_device_add_qdict(qts, driver, args);
1438     qobject_unref(args);
1439 }
1440 
1441 #ifndef _WIN32
1442 void qtest_qmp_add_client(QTestState *qts, const char *protocol, int fd)
1443 {
1444     QDict *resp;
1445 
1446     resp = qtest_qmp_fds(qts, &fd, 1, "{'execute': 'getfd',"
1447                          "'arguments': {'fdname': 'fdname'}}");
1448     g_assert(resp);
1449     g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1450     g_assert(!qdict_haskey(resp, "error"));
1451     qobject_unref(resp);
1452 
1453     resp = qtest_qmp(
1454         qts, "{'execute': 'add_client',"
1455         "'arguments': {'protocol': %s, 'fdname': 'fdname'}}", protocol);
1456     g_assert(resp);
1457     g_assert(!qdict_haskey(resp, "event")); /* We don't expect any events */
1458     g_assert(!qdict_haskey(resp, "error"));
1459     qobject_unref(resp);
1460 }
1461 #endif
1462 
1463 /*
1464  * Generic hot-unplugging test via the device_del QMP command.
1465  * Device deletion will get one response and one event. For example:
1466  *
1467  * {'execute': 'device_del','arguments': { 'id': 'scsi-hd'}}
1468  *
1469  * will get this one:
1470  *
1471  * {"timestamp": {"seconds": 1505289667, "microseconds": 569862},
1472  *  "event": "DEVICE_DELETED", "data": {"device": "scsi-hd",
1473  *  "path": "/machine/peripheral/scsi-hd"}}
1474  *
1475  * and this one:
1476  *
1477  * {"return": {}}
1478  */
1479 void qtest_qmp_device_del_send(QTestState *qts, const char *id)
1480 {
1481     QDict *rsp = qtest_qmp(qts, "{'execute': 'device_del', "
1482                                 "'arguments': {'id': %s}}", id);
1483     g_assert(rsp);
1484     g_assert(qdict_haskey(rsp, "return"));
1485     g_assert(!qdict_haskey(rsp, "error"));
1486     qobject_unref(rsp);
1487 }
1488 
1489 void qtest_qmp_device_del(QTestState *qts, const char *id)
1490 {
1491     qtest_qmp_device_del_send(qts, id);
1492     qtest_qmp_eventwait(qts, "DEVICE_DELETED");
1493 }
1494 
1495 static void qtest_client_set_tx_handler(QTestState *s,
1496                     QTestSendFn send)
1497 {
1498     s->ops.send = send;
1499 }
1500 static void qtest_client_set_rx_handler(QTestState *s, QTestRecvFn recv)
1501 {
1502     s->ops.recv_line = recv;
1503 }
1504 /* A type-safe wrapper for s->send() */
1505 static void send_wrapper(QTestState *s, const char *buf)
1506 {
1507     s->ops.external_send(s, buf);
1508 }
1509 
1510 static GString *qtest_client_inproc_recv_line(QTestState *s)
1511 {
1512     GString *line;
1513     size_t offset;
1514     char *eol;
1515 
1516     eol = strchr(s->rx->str, '\n');
1517     offset = eol - s->rx->str;
1518     line = g_string_new_len(s->rx->str, offset);
1519     g_string_erase(s->rx, 0, offset + 1);
1520     return line;
1521 }
1522 
1523 QTestState *qtest_inproc_init(QTestState **s, bool log, const char* arch,
1524                     void (*send)(void*, const char*))
1525 {
1526     QTestState *qts;
1527     qts = g_new0(QTestState, 1);
1528     qts->pending_events = NULL;
1529     *s = qts; /* Expose qts early on, since the query endianness relies on it */
1530     qts->wstatus = 0;
1531     for (int i = 0; i < MAX_IRQ; i++) {
1532         qts->irq_level[i] = false;
1533     }
1534 
1535     qtest_client_set_rx_handler(qts, qtest_client_inproc_recv_line);
1536 
1537     /* send() may not have a matching protoype, so use a type-safe wrapper */
1538     qts->ops.external_send = send;
1539     qtest_client_set_tx_handler(qts, send_wrapper);
1540 
1541     qts->big_endian = qtest_query_target_endianness(qts);
1542 
1543     /*
1544      * Set a dummy path for QTEST_QEMU_BINARY. Doesn't need to exist, but this
1545      * way, qtest_get_arch works for inproc qtest.
1546      */
1547     gchar *bin_path = g_strconcat("/qemu-system-", arch, NULL);
1548     g_setenv("QTEST_QEMU_BINARY", bin_path, 0);
1549     g_free(bin_path);
1550 
1551     return qts;
1552 }
1553 
1554 void qtest_client_inproc_recv(void *opaque, const char *str)
1555 {
1556     QTestState *qts = *(QTestState **)opaque;
1557 
1558     if (!qts->rx) {
1559         qts->rx = g_string_new(NULL);
1560     }
1561     g_string_append(qts->rx, str);
1562     return;
1563 }
1564 
1565 void qtest_qom_set_bool(QTestState *s, const char *path, const char *property,
1566                          bool value)
1567 {
1568     QDict *r;
1569 
1570     r = qtest_qmp(s, "{ 'execute': 'qom-set', 'arguments': "
1571                      "{ 'path': %s, 'property': %s, 'value': %i } }",
1572                      path, property, value);
1573     qobject_unref(r);
1574 }
1575 
1576 bool qtest_qom_get_bool(QTestState *s, const char *path, const char *property)
1577 {
1578     QDict *r;
1579     bool b;
1580 
1581     r = qtest_qmp(s, "{ 'execute': 'qom-get', 'arguments': "
1582                      "{ 'path': %s, 'property': %s } }", path, property);
1583     b = qdict_get_bool(r, "return");
1584     qobject_unref(r);
1585 
1586     return b;
1587 }
1588