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