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