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