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