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