xref: /qemu/system/qtest.c (revision d64db833d6e3cbe9ea5f36342480f920f3675cea)
1 /*
2  * Test Server
3  *
4  * Copyright IBM, Corp. 2011
5  *
6  * Authors:
7  *  Anthony Liguori   <aliguori@us.ibm.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2 or later.
10  * See the COPYING file in the top-level directory.
11  *
12  */
13 
14 #include "qemu/osdep.h"
15 #include "qapi/error.h"
16 #include "system/qtest.h"
17 #include "system/runstate.h"
18 #include "chardev/char-fe.h"
19 #include "system/ioport.h"
20 #include "system/memory.h"
21 #include "exec/tswap.h"
22 #include "hw/qdev-core.h"
23 #include "hw/irq.h"
24 #include "hw/core/cpu.h"
25 #include "qemu/accel.h"
26 #include "system/cpu-timers.h"
27 #include "qemu/config-file.h"
28 #include "qemu/option.h"
29 #include "qemu/error-report.h"
30 #include "qemu/module.h"
31 #include "qemu/cutils.h"
32 #include "qom/object_interfaces.h"
33 
34 #define MAX_IRQ 256
35 
36 #define TYPE_QTEST "qtest"
37 
38 OBJECT_DECLARE_SIMPLE_TYPE(QTest, QTEST)
39 
40 struct QTest {
41     Object parent;
42 
43     bool has_machine_link;
44     char *chr_name;
45     Chardev *chr;
46     CharBackend qtest_chr;
47     char *log;
48 };
49 
50 bool qtest_allowed;
51 
52 static DeviceState *irq_intercept_dev;
53 static FILE *qtest_log_fp;
54 static QTest *qtest;
55 static GString *inbuf;
56 static int irq_levels[MAX_IRQ];
57 static GTimer *timer;
58 static bool qtest_opened;
59 static void (*qtest_server_send)(void*, const char*);
60 static void *qtest_server_send_opaque;
61 
62 #define FMT_timeval "%.06f"
63 
64 /**
65  * DOC: QTest Protocol
66  *
67  * Line based protocol, request/response based.  Server can send async messages
68  * so clients should always handle many async messages before the response
69  * comes in.
70  *
71  * Valid requests
72  * ^^^^^^^^^^^^^^
73  *
74  * Clock management:
75  * """""""""""""""""
76  *
77  * The qtest client is completely in charge of the QEMU_CLOCK_VIRTUAL.  qtest commands
78  * let you adjust the value of the clock (monotonically).  All the commands
79  * return the current value of the clock in nanoseconds.
80  *
81  * If the commands FAIL then time wasn't advanced which is likely
82  * because the machine was in a paused state or no timer events exist
83  * in the future. This will cause qtest to abort and the test will
84  * need to check its assumptions.
85  *
86  * .. code-block:: none
87  *
88  *  > clock_step
89  *  < OK VALUE
90  *
91  * Advance the clock to the next deadline.  Useful when waiting for
92  * asynchronous events.
93  *
94  * .. code-block:: none
95  *
96  *  > clock_step NS
97  *  < OK VALUE
98  *
99  * Advance the clock by NS nanoseconds.
100  *
101  * .. code-block:: none
102  *
103  *  > clock_set NS
104  *  < OK VALUE
105  *
106  * Advance the clock to NS nanoseconds (do nothing if it's already past).
107  *
108  * PIO and memory access:
109  * """"""""""""""""""""""
110  *
111  * .. code-block:: none
112  *
113  *  > outb ADDR VALUE
114  *  < OK
115  *
116  * .. code-block:: none
117  *
118  *  > outw ADDR VALUE
119  *  < OK
120  *
121  * .. code-block:: none
122  *
123  *  > outl ADDR VALUE
124  *  < OK
125  *
126  * .. code-block:: none
127  *
128  *  > inb ADDR
129  *  < OK VALUE
130  *
131  * .. code-block:: none
132  *
133  *  > inw ADDR
134  *  < OK VALUE
135  *
136  * .. code-block:: none
137  *
138  *  > inl ADDR
139  *  < OK VALUE
140  *
141  * .. code-block:: none
142  *
143  *  > writeb ADDR VALUE
144  *  < OK
145  *
146  * .. code-block:: none
147  *
148  *  > writew ADDR VALUE
149  *  < OK
150  *
151  * .. code-block:: none
152  *
153  *  > writel ADDR VALUE
154  *  < OK
155  *
156  * .. code-block:: none
157  *
158  *  > writeq ADDR VALUE
159  *  < OK
160  *
161  * .. code-block:: none
162  *
163  *  > readb ADDR
164  *  < OK VALUE
165  *
166  * .. code-block:: none
167  *
168  *  > readw ADDR
169  *  < OK VALUE
170  *
171  * .. code-block:: none
172  *
173  *  > readl ADDR
174  *  < OK VALUE
175  *
176  * .. code-block:: none
177  *
178  *  > readq ADDR
179  *  < OK VALUE
180  *
181  * .. code-block:: none
182  *
183  *  > read ADDR SIZE
184  *  < OK DATA
185  *
186  * .. code-block:: none
187  *
188  *  > write ADDR SIZE DATA
189  *  < OK
190  *
191  * .. code-block:: none
192  *
193  *  > b64read ADDR SIZE
194  *  < OK B64_DATA
195  *
196  * .. code-block:: none
197  *
198  *  > b64write ADDR SIZE B64_DATA
199  *  < OK
200  *
201  * .. code-block:: none
202  *
203  *  > memset ADDR SIZE VALUE
204  *  < OK
205  *
206  * ADDR, SIZE, VALUE are all integers parsed with strtoul() with a base of 0.
207  * For 'memset' a zero size is permitted and does nothing.
208  *
209  * DATA is an arbitrarily long hex number prefixed with '0x'.  If it's smaller
210  * than the expected size, the value will be zero filled at the end of the data
211  * sequence.
212  *
213  * B64_DATA is an arbitrarily long base64 encoded string.
214  * If the sizes do not match, the data will be truncated.
215  *
216  * IRQ management:
217  * """""""""""""""
218  *
219  * .. code-block:: none
220  *
221  *  > irq_intercept_in QOM-PATH
222  *  < OK
223  *
224  * .. code-block:: none
225  *
226  *  > irq_intercept_out QOM-PATH
227  *  < OK
228  *
229  * Attach to the gpio-in (resp. gpio-out) pins exported by the device at
230  * QOM-PATH.  When the pin is triggered, one of the following async messages
231  * will be printed to the qtest stream::
232  *
233  *  IRQ raise NUM
234  *  IRQ lower NUM
235  *
236  * where NUM is an IRQ number.  For the PC, interrupts can be intercepted
237  * simply with "irq_intercept_in ioapic" (note that IRQ0 comes out with
238  * NUM=0 even though it is remapped to GSI 2).
239  *
240  * Setting interrupt level:
241  * """"""""""""""""""""""""
242  *
243  * .. code-block:: none
244  *
245  *  > set_irq_in QOM-PATH NAME NUM LEVEL
246  *  < OK
247  *
248  * where NAME is the name of the irq/gpio list, NUM is an IRQ number and
249  * LEVEL is an signed integer IRQ level.
250  *
251  * Forcibly set the given interrupt pin to the given level.
252  *
253  */
254 
255 static int hex2nib(char ch)
256 {
257     if (ch >= '0' && ch <= '9') {
258         return ch - '0';
259     } else if (ch >= 'a' && ch <= 'f') {
260         return 10 + (ch - 'a');
261     } else if (ch >= 'A' && ch <= 'F') {
262         return 10 + (ch - 'A');
263     } else {
264         return -1;
265     }
266 }
267 
268 static void qtest_log_timestamp(void)
269 {
270     if (!qtest_log_fp || !qtest_opened) {
271         return;
272     }
273 
274     fprintf(qtest_log_fp, "[S +" FMT_timeval "] ", g_timer_elapsed(timer, NULL));
275 }
276 
277 static void G_GNUC_PRINTF(1, 2) qtest_log_send(const char *fmt, ...)
278 {
279     va_list ap;
280 
281     if (!qtest_log_fp || !qtest_opened) {
282         return;
283     }
284 
285     qtest_log_timestamp();
286 
287     va_start(ap, fmt);
288     vfprintf(qtest_log_fp, fmt, ap);
289     va_end(ap);
290 }
291 
292 static void qtest_server_char_be_send(void *opaque, const char *str)
293 {
294     size_t len = strlen(str);
295     CharBackend* chr = (CharBackend *)opaque;
296     qemu_chr_fe_write_all(chr, (uint8_t *)str, len);
297     if (qtest_log_fp && qtest_opened) {
298         fprintf(qtest_log_fp, "%s", str);
299     }
300 }
301 
302 static void qtest_send(CharBackend *chr, const char *str)
303 {
304     qtest_log_timestamp();
305     qtest_server_send(qtest_server_send_opaque, str);
306 }
307 
308 void qtest_sendf(CharBackend *chr, const char *fmt, ...)
309 {
310     va_list ap;
311     gchar *buffer;
312 
313     va_start(ap, fmt);
314     buffer = g_strdup_vprintf(fmt, ap);
315     qtest_send(chr, buffer);
316     g_free(buffer);
317     va_end(ap);
318 }
319 
320 static void qtest_irq_handler(void *opaque, int n, int level)
321 {
322     qemu_irq old_irq = *(qemu_irq *)opaque;
323     qemu_set_irq(old_irq, level);
324 
325     if (irq_levels[n] != level) {
326         CharBackend *chr = &qtest->qtest_chr;
327         irq_levels[n] = level;
328         qtest_sendf(chr, "IRQ %s %d\n",
329                     level ? "raise" : "lower", n);
330     }
331 }
332 
333 static bool (*process_command_cb)(CharBackend *chr, gchar **words);
334 
335 void qtest_set_command_cb(bool (*pc_cb)(CharBackend *chr, gchar **words))
336 {
337     assert(!process_command_cb);  /* Switch to a list if we need more than one */
338 
339     process_command_cb = pc_cb;
340 }
341 
342 static void qtest_install_gpio_out_intercept(DeviceState *dev, const char *name, int n)
343 {
344     qemu_irq *disconnected = g_new0(qemu_irq, 1);
345     qemu_irq icpt = qemu_allocate_irq(qtest_irq_handler,
346                                       disconnected, n);
347 
348     *disconnected = qdev_intercept_gpio_out(dev, icpt, name, n);
349 }
350 
351 static void qtest_process_command(CharBackend *chr, gchar **words)
352 {
353     const gchar *command;
354 
355     g_assert(words);
356 
357     command = words[0];
358 
359     if (qtest_log_fp) {
360         int i;
361 
362         fprintf(qtest_log_fp, "[R +" FMT_timeval "]", g_timer_elapsed(timer, NULL));
363         for (i = 0; words[i]; i++) {
364             fprintf(qtest_log_fp, " %s", words[i]);
365         }
366         fprintf(qtest_log_fp, "\n");
367     }
368 
369     g_assert(command);
370     if (strcmp(words[0], "irq_intercept_out") == 0
371         || strcmp(words[0], "irq_intercept_in") == 0) {
372         DeviceState *dev;
373         NamedGPIOList *ngl;
374         bool is_named;
375         bool is_outbound;
376         bool interception_succeeded = false;
377 
378         g_assert(words[1]);
379         is_named = words[2] != NULL;
380         is_outbound = words[0][14] == 'o';
381         dev = DEVICE(object_resolve_path(words[1], NULL));
382         if (!dev) {
383             qtest_send(chr, "FAIL Unknown device\n");
384             return;
385         }
386 
387         if (is_named && !is_outbound) {
388             qtest_send(chr, "FAIL Interception of named in-GPIOs not yet supported\n");
389             return;
390         }
391 
392         if (irq_intercept_dev) {
393             if (irq_intercept_dev != dev) {
394                 qtest_send(chr, "FAIL IRQ intercept already enabled\n");
395             } else {
396                 qtest_send(chr, "OK\n");
397             }
398             return;
399         }
400 
401         QLIST_FOREACH(ngl, &dev->gpios, node) {
402             /* We don't support inbound interception of named GPIOs yet */
403             if (is_outbound) {
404                 /* NULL is valid and matchable, for "unnamed GPIO" */
405                 if (g_strcmp0(ngl->name, words[2]) == 0) {
406                     int i;
407                     for (i = 0; i < ngl->num_out; ++i) {
408                         qtest_install_gpio_out_intercept(dev, ngl->name, i);
409                     }
410                     interception_succeeded = true;
411                 }
412             } else {
413                 qemu_irq_intercept_in(ngl->in, qtest_irq_handler,
414                                       ngl->num_in);
415                 interception_succeeded = true;
416             }
417         }
418 
419         if (interception_succeeded) {
420             irq_intercept_dev = dev;
421             qtest_send(chr, "OK\n");
422         } else {
423             qtest_send(chr, "FAIL No intercepts installed\n");
424         }
425     } else if (strcmp(words[0], "set_irq_in") == 0) {
426         DeviceState *dev;
427         qemu_irq irq;
428         char *name;
429         int ret;
430         int num;
431         int level;
432 
433         g_assert(words[1] && words[2] && words[3] && words[4]);
434 
435         dev = DEVICE(object_resolve_path(words[1], NULL));
436         if (!dev) {
437             qtest_send(chr, "FAIL Unknown device\n");
438             return;
439         }
440 
441         if (strcmp(words[2], "unnamed-gpio-in") == 0) {
442             name = NULL;
443         } else {
444             name = words[2];
445         }
446 
447         ret = qemu_strtoi(words[3], NULL, 0, &num);
448         g_assert(!ret);
449         ret = qemu_strtoi(words[4], NULL, 0, &level);
450         g_assert(!ret);
451 
452         irq = qdev_get_gpio_in_named(dev, name, num);
453 
454         qemu_set_irq(irq, level);
455         qtest_send(chr, "OK\n");
456     } else if (strcmp(words[0], "outb") == 0 ||
457                strcmp(words[0], "outw") == 0 ||
458                strcmp(words[0], "outl") == 0) {
459         unsigned long addr;
460         unsigned long value;
461         int ret;
462 
463         g_assert(words[1] && words[2]);
464         ret = qemu_strtoul(words[1], NULL, 0, &addr);
465         g_assert(ret == 0);
466         ret = qemu_strtoul(words[2], NULL, 0, &value);
467         g_assert(ret == 0);
468         g_assert(addr <= 0xffff);
469 
470         if (words[0][3] == 'b') {
471             cpu_outb(addr, value);
472         } else if (words[0][3] == 'w') {
473             cpu_outw(addr, value);
474         } else if (words[0][3] == 'l') {
475             cpu_outl(addr, value);
476         }
477         qtest_send(chr, "OK\n");
478     } else if (strcmp(words[0], "inb") == 0 ||
479         strcmp(words[0], "inw") == 0 ||
480         strcmp(words[0], "inl") == 0) {
481         unsigned long addr;
482         uint32_t value = -1U;
483         int ret;
484 
485         g_assert(words[1]);
486         ret = qemu_strtoul(words[1], NULL, 0, &addr);
487         g_assert(ret == 0);
488         g_assert(addr <= 0xffff);
489 
490         if (words[0][2] == 'b') {
491             value = cpu_inb(addr);
492         } else if (words[0][2] == 'w') {
493             value = cpu_inw(addr);
494         } else if (words[0][2] == 'l') {
495             value = cpu_inl(addr);
496         }
497         qtest_sendf(chr, "OK 0x%04x\n", value);
498     } else if (strcmp(words[0], "writeb") == 0 ||
499                strcmp(words[0], "writew") == 0 ||
500                strcmp(words[0], "writel") == 0 ||
501                strcmp(words[0], "writeq") == 0) {
502         uint64_t addr;
503         uint64_t value;
504         int ret;
505 
506         g_assert(words[1] && words[2]);
507         ret = qemu_strtou64(words[1], NULL, 0, &addr);
508         g_assert(ret == 0);
509         ret = qemu_strtou64(words[2], NULL, 0, &value);
510         g_assert(ret == 0);
511 
512         if (words[0][5] == 'b') {
513             uint8_t data = value;
514             address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
515                                 &data, 1);
516         } else if (words[0][5] == 'w') {
517             uint16_t data = value;
518             tswap16s(&data);
519             address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
520                                 &data, 2);
521         } else if (words[0][5] == 'l') {
522             uint32_t data = value;
523             tswap32s(&data);
524             address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
525                                 &data, 4);
526         } else if (words[0][5] == 'q') {
527             uint64_t data = value;
528             tswap64s(&data);
529             address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
530                                 &data, 8);
531         }
532         qtest_send(chr, "OK\n");
533     } else if (strcmp(words[0], "readb") == 0 ||
534                strcmp(words[0], "readw") == 0 ||
535                strcmp(words[0], "readl") == 0 ||
536                strcmp(words[0], "readq") == 0) {
537         uint64_t addr;
538         uint64_t value = UINT64_C(-1);
539         int ret;
540 
541         g_assert(words[1]);
542         ret = qemu_strtou64(words[1], NULL, 0, &addr);
543         g_assert(ret == 0);
544 
545         if (words[0][4] == 'b') {
546             uint8_t data;
547             address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
548                                &data, 1);
549             value = data;
550         } else if (words[0][4] == 'w') {
551             uint16_t data;
552             address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
553                                &data, 2);
554             value = tswap16(data);
555         } else if (words[0][4] == 'l') {
556             uint32_t data;
557             address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
558                                &data, 4);
559             value = tswap32(data);
560         } else if (words[0][4] == 'q') {
561             address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
562                                &value, 8);
563             tswap64s(&value);
564         }
565         qtest_sendf(chr, "OK 0x%016" PRIx64 "\n", value);
566     } else if (strcmp(words[0], "read") == 0) {
567         g_autoptr(GString) enc = NULL;
568         uint64_t addr, len;
569         uint8_t *data;
570         int ret;
571 
572         g_assert(words[1] && words[2]);
573         ret = qemu_strtou64(words[1], NULL, 0, &addr);
574         g_assert(ret == 0);
575         ret = qemu_strtou64(words[2], NULL, 0, &len);
576         g_assert(ret == 0);
577         /* We'd send garbage to libqtest if len is 0 */
578         g_assert(len);
579 
580         data = g_malloc(len);
581         address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED, data,
582                            len);
583 
584         enc = qemu_hexdump_line(NULL, data, len, 0, 0);
585 
586         qtest_sendf(chr, "OK 0x%s\n", enc->str);
587 
588         g_free(data);
589     } else if (strcmp(words[0], "b64read") == 0) {
590         uint64_t addr, len;
591         uint8_t *data;
592         gchar *b64_data;
593         int ret;
594 
595         g_assert(words[1] && words[2]);
596         ret = qemu_strtou64(words[1], NULL, 0, &addr);
597         g_assert(ret == 0);
598         ret = qemu_strtou64(words[2], NULL, 0, &len);
599         g_assert(ret == 0);
600 
601         data = g_malloc(len);
602         address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED, data,
603                            len);
604         b64_data = g_base64_encode(data, len);
605         qtest_sendf(chr, "OK %s\n", b64_data);
606 
607         g_free(data);
608         g_free(b64_data);
609     } else if (strcmp(words[0], "write") == 0) {
610         uint64_t addr, len, i;
611         uint8_t *data;
612         size_t data_len;
613         int ret;
614 
615         g_assert(words[1] && words[2] && words[3]);
616         ret = qemu_strtou64(words[1], NULL, 0, &addr);
617         g_assert(ret == 0);
618         ret = qemu_strtou64(words[2], NULL, 0, &len);
619         g_assert(ret == 0);
620 
621         data_len = strlen(words[3]);
622         if (data_len < 3) {
623             qtest_send(chr, "ERR invalid argument size\n");
624             return;
625         }
626 
627         data = g_malloc(len);
628         for (i = 0; i < len; i++) {
629             if ((i * 2 + 4) <= data_len) {
630                 data[i] = hex2nib(words[3][i * 2 + 2]) << 4;
631                 data[i] |= hex2nib(words[3][i * 2 + 3]);
632             } else {
633                 data[i] = 0;
634             }
635         }
636         address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED, data,
637                             len);
638         g_free(data);
639 
640         qtest_send(chr, "OK\n");
641     } else if (strcmp(words[0], "memset") == 0) {
642         uint64_t addr, len;
643         uint8_t *data;
644         unsigned long pattern;
645         int ret;
646 
647         g_assert(words[1] && words[2] && words[3]);
648         ret = qemu_strtou64(words[1], NULL, 0, &addr);
649         g_assert(ret == 0);
650         ret = qemu_strtou64(words[2], NULL, 0, &len);
651         g_assert(ret == 0);
652         ret = qemu_strtoul(words[3], NULL, 0, &pattern);
653         g_assert(ret == 0);
654 
655         if (len) {
656             data = g_malloc(len);
657             memset(data, pattern, len);
658             address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
659                                 data, len);
660             g_free(data);
661         }
662 
663         qtest_send(chr, "OK\n");
664     }  else if (strcmp(words[0], "b64write") == 0) {
665         uint64_t addr, len;
666         uint8_t *data;
667         size_t data_len;
668         gsize out_len;
669         int ret;
670 
671         g_assert(words[1] && words[2] && words[3]);
672         ret = qemu_strtou64(words[1], NULL, 0, &addr);
673         g_assert(ret == 0);
674         ret = qemu_strtou64(words[2], NULL, 0, &len);
675         g_assert(ret == 0);
676 
677         data_len = strlen(words[3]);
678         if (data_len < 3) {
679             qtest_send(chr, "ERR invalid argument size\n");
680             return;
681         }
682 
683         data = g_base64_decode_inplace(words[3], &out_len);
684         if (out_len != len) {
685             qtest_log_send("b64write: data length mismatch (told %"PRIu64", "
686                            "found %zu)\n",
687                            len, out_len);
688             out_len = MIN(out_len, len);
689         }
690 
691         address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED, data,
692                             len);
693 
694         qtest_send(chr, "OK\n");
695     } else if (strcmp(words[0], "endianness") == 0) {
696         if (target_big_endian()) {
697             qtest_sendf(chr, "OK big\n");
698         } else {
699             qtest_sendf(chr, "OK little\n");
700         }
701     } else if (qtest_enabled() && strcmp(words[0], "clock_step") == 0) {
702         int64_t old_ns = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
703         int64_t ns, new_ns;
704 
705         if (words[1]) {
706             int ret = qemu_strtoi64(words[1], NULL, 0, &ns);
707             g_assert(ret == 0);
708         } else {
709             ns = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL,
710                                             QEMU_TIMER_ATTR_ALL);
711             if (ns < 0) {
712                 qtest_send(chr, "FAIL "
713                            "cannot advance clock to the next deadline "
714                            "because there is no pending deadline\n");
715                 return;
716             }
717         }
718         new_ns = qemu_clock_advance_virtual_time(old_ns + ns);
719         if (new_ns > old_ns) {
720             qtest_sendf(chr, "OK %"PRIi64"\n", new_ns);
721         } else {
722             qtest_sendf(chr, "FAIL could not advance time\n");
723         }
724     } else if (strcmp(words[0], "module_load") == 0) {
725         Error *local_err = NULL;
726         int rv;
727         g_assert(words[1] && words[2]);
728 
729         rv = module_load(words[1], words[2], &local_err);
730         if (rv > 0) {
731             qtest_sendf(chr, "OK\n");
732         } else {
733             if (rv < 0) {
734                 error_report_err(local_err);
735             }
736             qtest_sendf(chr, "FAIL\n");
737         }
738     } else if (qtest_enabled() && strcmp(words[0], "clock_set") == 0) {
739         int64_t ns, new_ns;
740         int ret;
741 
742         g_assert(words[1]);
743         ret = qemu_strtoi64(words[1], NULL, 0, &ns);
744         g_assert(ret == 0);
745         new_ns = qemu_clock_advance_virtual_time(ns);
746         qtest_sendf(chr, "%s %"PRIi64"\n",
747                     new_ns == ns ? "OK" : "FAIL", new_ns);
748     } else if (process_command_cb && process_command_cb(chr, words)) {
749         /* Command got consumed by the callback handler */
750     } else {
751         qtest_sendf(chr, "FAIL Unknown command '%s'\n", words[0]);
752     }
753 }
754 
755 /*
756  * Process as much of @inbuf as we can in newline terminated chunks.
757  * Remove the processed commands from @inbuf as we go.
758  */
759 static void qtest_process_inbuf(CharBackend *chr, GString *inbuf)
760 {
761     char *end;
762 
763     while ((end = strchr(inbuf->str, '\n')) != NULL) {
764         size_t len = end - inbuf->str;
765         g_autofree char *cmd = g_strndup(inbuf->str, len);
766         g_auto(GStrv) words = g_strsplit(cmd, " ", 0);
767 
768         g_string_erase(inbuf, 0, len + 1);
769         qtest_process_command(chr, words);
770     }
771 }
772 
773 static void qtest_read(void *opaque, const uint8_t *buf, int size)
774 {
775     CharBackend *chr = opaque;
776 
777     g_string_append_len(inbuf, (const gchar *)buf, size);
778     qtest_process_inbuf(chr, inbuf);
779 }
780 
781 static int qtest_can_read(void *opaque)
782 {
783     return 1024;
784 }
785 
786 static void qtest_event(void *opaque, QEMUChrEvent event)
787 {
788     int i;
789 
790     switch (event) {
791     case CHR_EVENT_OPENED:
792         /*
793          * We used to call qemu_system_reset() here, hoping we could
794          * use the same process for multiple tests that way.  Never
795          * used.  Injects an extra reset even when it's not used, and
796          * that can mess up tests, e.g. -boot once.
797          */
798         for (i = 0; i < ARRAY_SIZE(irq_levels); i++) {
799             irq_levels[i] = 0;
800         }
801 
802         g_clear_pointer(&timer, g_timer_destroy);
803         timer = g_timer_new();
804         qtest_opened = true;
805         if (qtest_log_fp) {
806             fprintf(qtest_log_fp, "[I " FMT_timeval "] OPENED\n", g_timer_elapsed(timer, NULL));
807         }
808         break;
809     case CHR_EVENT_CLOSED:
810         qtest_opened = false;
811         if (qtest_log_fp) {
812             fprintf(qtest_log_fp, "[I +" FMT_timeval "] CLOSED\n", g_timer_elapsed(timer, NULL));
813         }
814         g_clear_pointer(&timer, g_timer_destroy);
815         break;
816     default:
817         break;
818     }
819 }
820 
821 void qtest_server_init(const char *qtest_chrdev, const char *qtest_log, Error **errp)
822 {
823     ERRP_GUARD();
824     Chardev *chr;
825     Object *qobj;
826 
827     chr = qemu_chr_new("qtest", qtest_chrdev, NULL);
828     if (chr == NULL) {
829         error_setg(errp, "Failed to initialize device for qtest: \"%s\"",
830                    qtest_chrdev);
831         return;
832     }
833 
834     qobj = object_new(TYPE_QTEST);
835     object_property_set_str(qobj, "chardev", chr->label, &error_abort);
836     if (qtest_log) {
837         object_property_set_str(qobj, "log", qtest_log, &error_abort);
838     }
839     object_property_add_child(qdev_get_machine(), "qtest", qobj);
840     user_creatable_complete(USER_CREATABLE(qobj), errp);
841     if (*errp) {
842         object_unparent(qobj);
843     }
844     object_unref(OBJECT(chr));
845     object_unref(qobj);
846 }
847 
848 static bool qtest_server_start(QTest *q, Error **errp)
849 {
850     Chardev *chr = q->chr;
851     const char *qtest_log = q->log;
852 
853     if (qtest_log) {
854         if (strcmp(qtest_log, "none") != 0) {
855             qtest_log_fp = fopen(qtest_log, "w+");
856         }
857     } else {
858         qtest_log_fp = stderr;
859     }
860 
861     if (!qemu_chr_fe_init(&q->qtest_chr, chr, errp)) {
862         return false;
863     }
864     qemu_chr_fe_set_handlers(&q->qtest_chr, qtest_can_read, qtest_read,
865                              qtest_event, NULL, &q->qtest_chr, NULL, true);
866     qemu_chr_fe_set_echo(&q->qtest_chr, true);
867 
868     inbuf = g_string_new("");
869 
870     if (!qtest_server_send) {
871         qtest_server_set_send_handler(qtest_server_char_be_send, &q->qtest_chr);
872     }
873     qtest = q;
874     return true;
875 }
876 
877 void qtest_server_set_send_handler(void (*send)(void*, const char*),
878                                    void *opaque)
879 {
880     qtest_server_send = send;
881     qtest_server_send_opaque = opaque;
882 }
883 
884 bool qtest_driver(void)
885 {
886     return qtest && qtest->qtest_chr.chr != NULL;
887 }
888 
889 void qtest_server_inproc_recv(void *dummy, const char *buf)
890 {
891     static GString *gstr;
892     if (!gstr) {
893         gstr = g_string_new(NULL);
894     }
895     g_string_append(gstr, buf);
896     if (gstr->str[gstr->len - 1] == '\n') {
897         qtest_process_inbuf(NULL, gstr);
898         g_string_truncate(gstr, 0);
899     }
900 }
901 
902 static void qtest_complete(UserCreatable *uc, Error **errp)
903 {
904     QTest *q = QTEST(uc);
905     if (qtest) {
906         error_setg(errp, "Only one instance of qtest can be created");
907         return;
908     }
909     if (!q->chr_name) {
910         error_setg(errp, "No backend specified");
911         return;
912     }
913 
914     if (OBJECT(uc)->parent != qdev_get_machine()) {
915         q->has_machine_link = true;
916         object_property_add_const_link(qdev_get_machine(), "qtest", OBJECT(uc));
917     } else {
918         /* -qtest was used.  */
919     }
920 
921     qtest_server_start(q, errp);
922 }
923 
924 static void qtest_unparent(Object *obj)
925 {
926     QTest *q = QTEST(obj);
927 
928     if (qtest == q) {
929         qemu_chr_fe_disconnect(&q->qtest_chr);
930         assert(!qtest_opened);
931         qemu_chr_fe_deinit(&q->qtest_chr, false);
932         if (qtest_log_fp) {
933             fclose(qtest_log_fp);
934             qtest_log_fp = NULL;
935         }
936         qtest = NULL;
937     }
938 
939     if (q->has_machine_link) {
940         object_property_del(qdev_get_machine(), "qtest");
941         q->has_machine_link = false;
942     }
943 }
944 
945 static void qtest_set_log(Object *obj, const char *value, Error **errp)
946 {
947     QTest *q = QTEST(obj);
948 
949     if (qtest == q) {
950         error_setg(errp, "Property 'log' can not be set now");
951     } else {
952         g_free(q->log);
953         q->log = g_strdup(value);
954     }
955 }
956 
957 static char *qtest_get_log(Object *obj, Error **errp)
958 {
959     QTest *q = QTEST(obj);
960 
961     return g_strdup(q->log);
962 }
963 
964 static void qtest_set_chardev(Object *obj, const char *value, Error **errp)
965 {
966     QTest *q = QTEST(obj);
967     Chardev *chr;
968 
969     if (qtest == q) {
970         error_setg(errp, "Property 'chardev' can not be set now");
971         return;
972     }
973 
974     chr = qemu_chr_find(value);
975     if (!chr) {
976         error_setg(errp, "Cannot find character device '%s'", value);
977         return;
978     }
979 
980     g_free(q->chr_name);
981     q->chr_name = g_strdup(value);
982 
983     if (q->chr) {
984         object_unref(q->chr);
985     }
986     q->chr = chr;
987     object_ref(chr);
988 }
989 
990 static char *qtest_get_chardev(Object *obj, Error **errp)
991 {
992     QTest *q = QTEST(obj);
993 
994     return g_strdup(q->chr_name);
995 }
996 
997 static void qtest_class_init(ObjectClass *oc, const void *data)
998 {
999     UserCreatableClass *ucc = USER_CREATABLE_CLASS(oc);
1000 
1001     oc->unparent = qtest_unparent;
1002     ucc->complete = qtest_complete;
1003 
1004     object_class_property_add_str(oc, "chardev",
1005                                   qtest_get_chardev, qtest_set_chardev);
1006     object_class_property_add_str(oc, "log",
1007                                   qtest_get_log, qtest_set_log);
1008 }
1009 
1010 static const TypeInfo qtest_info = {
1011     .name = TYPE_QTEST,
1012     .parent = TYPE_OBJECT,
1013     .class_init = qtest_class_init,
1014     .instance_size = sizeof(QTest),
1015     .interfaces = (const InterfaceInfo[]) {
1016         { TYPE_USER_CREATABLE },
1017         { }
1018     }
1019 };
1020 
1021 static void register_types(void)
1022 {
1023     type_register_static(&qtest_info);
1024 }
1025 
1026 type_init(register_types);
1027