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