xref: /openbmc/qemu/system/qtest.c (revision 31ef3c333db3b1293b65da0e8fe602ad5ebcd698)
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 "exec/ioport.h"
20 #include "exec/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_words_bigendian()) {
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         }
712         new_ns = qemu_clock_advance_virtual_time(old_ns + ns);
713         qtest_sendf(chr, "%s %"PRIi64"\n",
714                     new_ns > old_ns ? "OK" : "FAIL", new_ns);
715     } else if (strcmp(words[0], "module_load") == 0) {
716         Error *local_err = NULL;
717         int rv;
718         g_assert(words[1] && words[2]);
719 
720         rv = module_load(words[1], words[2], &local_err);
721         if (rv > 0) {
722             qtest_sendf(chr, "OK\n");
723         } else {
724             if (rv < 0) {
725                 error_report_err(local_err);
726             }
727             qtest_sendf(chr, "FAIL\n");
728         }
729     } else if (qtest_enabled() && strcmp(words[0], "clock_set") == 0) {
730         int64_t ns, new_ns;
731         int ret;
732 
733         g_assert(words[1]);
734         ret = qemu_strtoi64(words[1], NULL, 0, &ns);
735         g_assert(ret == 0);
736         new_ns = qemu_clock_advance_virtual_time(ns);
737         qtest_sendf(chr, "%s %"PRIi64"\n",
738                     new_ns == ns ? "OK" : "FAIL", new_ns);
739     } else if (process_command_cb && process_command_cb(chr, words)) {
740         /* Command got consumed by the callback handler */
741     } else {
742         qtest_sendf(chr, "FAIL Unknown command '%s'\n", words[0]);
743     }
744 }
745 
746 /*
747  * Process as much of @inbuf as we can in newline terminated chunks.
748  * Remove the processed commands from @inbuf as we go.
749  */
750 static void qtest_process_inbuf(CharBackend *chr, GString *inbuf)
751 {
752     char *end;
753 
754     while ((end = strchr(inbuf->str, '\n')) != NULL) {
755         size_t len = end - inbuf->str;
756         g_autofree char *cmd = g_strndup(inbuf->str, len);
757         g_auto(GStrv) words = g_strsplit(cmd, " ", 0);
758 
759         g_string_erase(inbuf, 0, len + 1);
760         qtest_process_command(chr, words);
761     }
762 }
763 
764 static void qtest_read(void *opaque, const uint8_t *buf, int size)
765 {
766     CharBackend *chr = opaque;
767 
768     g_string_append_len(inbuf, (const gchar *)buf, size);
769     qtest_process_inbuf(chr, inbuf);
770 }
771 
772 static int qtest_can_read(void *opaque)
773 {
774     return 1024;
775 }
776 
777 static void qtest_event(void *opaque, QEMUChrEvent event)
778 {
779     int i;
780 
781     switch (event) {
782     case CHR_EVENT_OPENED:
783         /*
784          * We used to call qemu_system_reset() here, hoping we could
785          * use the same process for multiple tests that way.  Never
786          * used.  Injects an extra reset even when it's not used, and
787          * that can mess up tests, e.g. -boot once.
788          */
789         for (i = 0; i < ARRAY_SIZE(irq_levels); i++) {
790             irq_levels[i] = 0;
791         }
792 
793         g_clear_pointer(&timer, g_timer_destroy);
794         timer = g_timer_new();
795         qtest_opened = true;
796         if (qtest_log_fp) {
797             fprintf(qtest_log_fp, "[I " FMT_timeval "] OPENED\n", g_timer_elapsed(timer, NULL));
798         }
799         break;
800     case CHR_EVENT_CLOSED:
801         qtest_opened = false;
802         if (qtest_log_fp) {
803             fprintf(qtest_log_fp, "[I +" FMT_timeval "] CLOSED\n", g_timer_elapsed(timer, NULL));
804         }
805         g_clear_pointer(&timer, g_timer_destroy);
806         break;
807     default:
808         break;
809     }
810 }
811 
812 void qtest_server_init(const char *qtest_chrdev, const char *qtest_log, Error **errp)
813 {
814     ERRP_GUARD();
815     Chardev *chr;
816     Object *qobj;
817 
818     chr = qemu_chr_new("qtest", qtest_chrdev, NULL);
819     if (chr == NULL) {
820         error_setg(errp, "Failed to initialize device for qtest: \"%s\"",
821                    qtest_chrdev);
822         return;
823     }
824 
825     qobj = object_new(TYPE_QTEST);
826     object_property_set_str(qobj, "chardev", chr->label, &error_abort);
827     if (qtest_log) {
828         object_property_set_str(qobj, "log", qtest_log, &error_abort);
829     }
830     object_property_add_child(qdev_get_machine(), "qtest", qobj);
831     user_creatable_complete(USER_CREATABLE(qobj), errp);
832     if (*errp) {
833         object_unparent(qobj);
834     }
835     object_unref(OBJECT(chr));
836     object_unref(qobj);
837 }
838 
839 static bool qtest_server_start(QTest *q, Error **errp)
840 {
841     Chardev *chr = q->chr;
842     const char *qtest_log = q->log;
843 
844     if (qtest_log) {
845         if (strcmp(qtest_log, "none") != 0) {
846             qtest_log_fp = fopen(qtest_log, "w+");
847         }
848     } else {
849         qtest_log_fp = stderr;
850     }
851 
852     if (!qemu_chr_fe_init(&q->qtest_chr, chr, errp)) {
853         return false;
854     }
855     qemu_chr_fe_set_handlers(&q->qtest_chr, qtest_can_read, qtest_read,
856                              qtest_event, NULL, &q->qtest_chr, NULL, true);
857     qemu_chr_fe_set_echo(&q->qtest_chr, true);
858 
859     inbuf = g_string_new("");
860 
861     if (!qtest_server_send) {
862         qtest_server_set_send_handler(qtest_server_char_be_send, &q->qtest_chr);
863     }
864     qtest = q;
865     return true;
866 }
867 
868 void qtest_server_set_send_handler(void (*send)(void*, const char*),
869                                    void *opaque)
870 {
871     qtest_server_send = send;
872     qtest_server_send_opaque = opaque;
873 }
874 
875 bool qtest_driver(void)
876 {
877     return qtest && qtest->qtest_chr.chr != NULL;
878 }
879 
880 void qtest_server_inproc_recv(void *dummy, const char *buf)
881 {
882     static GString *gstr;
883     if (!gstr) {
884         gstr = g_string_new(NULL);
885     }
886     g_string_append(gstr, buf);
887     if (gstr->str[gstr->len - 1] == '\n') {
888         qtest_process_inbuf(NULL, gstr);
889         g_string_truncate(gstr, 0);
890     }
891 }
892 
893 static void qtest_complete(UserCreatable *uc, Error **errp)
894 {
895     QTest *q = QTEST(uc);
896     if (qtest) {
897         error_setg(errp, "Only one instance of qtest can be created");
898         return;
899     }
900     if (!q->chr_name) {
901         error_setg(errp, "No backend specified");
902         return;
903     }
904 
905     if (OBJECT(uc)->parent != qdev_get_machine()) {
906         q->has_machine_link = true;
907         object_property_add_const_link(qdev_get_machine(), "qtest", OBJECT(uc));
908     } else {
909         /* -qtest was used.  */
910     }
911 
912     qtest_server_start(q, errp);
913 }
914 
915 static void qtest_unparent(Object *obj)
916 {
917     QTest *q = QTEST(obj);
918 
919     if (qtest == q) {
920         qemu_chr_fe_disconnect(&q->qtest_chr);
921         assert(!qtest_opened);
922         qemu_chr_fe_deinit(&q->qtest_chr, false);
923         if (qtest_log_fp) {
924             fclose(qtest_log_fp);
925             qtest_log_fp = NULL;
926         }
927         qtest = NULL;
928     }
929 
930     if (q->has_machine_link) {
931         object_property_del(qdev_get_machine(), "qtest");
932         q->has_machine_link = false;
933     }
934 }
935 
936 static void qtest_set_log(Object *obj, const char *value, Error **errp)
937 {
938     QTest *q = QTEST(obj);
939 
940     if (qtest == q) {
941         error_setg(errp, "Property 'log' can not be set now");
942     } else {
943         g_free(q->log);
944         q->log = g_strdup(value);
945     }
946 }
947 
948 static char *qtest_get_log(Object *obj, Error **errp)
949 {
950     QTest *q = QTEST(obj);
951 
952     return g_strdup(q->log);
953 }
954 
955 static void qtest_set_chardev(Object *obj, const char *value, Error **errp)
956 {
957     QTest *q = QTEST(obj);
958     Chardev *chr;
959 
960     if (qtest == q) {
961         error_setg(errp, "Property 'chardev' can not be set now");
962         return;
963     }
964 
965     chr = qemu_chr_find(value);
966     if (!chr) {
967         error_setg(errp, "Cannot find character device '%s'", value);
968         return;
969     }
970 
971     g_free(q->chr_name);
972     q->chr_name = g_strdup(value);
973 
974     if (q->chr) {
975         object_unref(q->chr);
976     }
977     q->chr = chr;
978     object_ref(chr);
979 }
980 
981 static char *qtest_get_chardev(Object *obj, Error **errp)
982 {
983     QTest *q = QTEST(obj);
984 
985     return g_strdup(q->chr_name);
986 }
987 
988 static void qtest_class_init(ObjectClass *oc, void *data)
989 {
990     UserCreatableClass *ucc = USER_CREATABLE_CLASS(oc);
991 
992     oc->unparent = qtest_unparent;
993     ucc->complete = qtest_complete;
994 
995     object_class_property_add_str(oc, "chardev",
996                                   qtest_get_chardev, qtest_set_chardev);
997     object_class_property_add_str(oc, "log",
998                                   qtest_get_log, qtest_set_log);
999 }
1000 
1001 static const TypeInfo qtest_info = {
1002     .name = TYPE_QTEST,
1003     .parent = TYPE_OBJECT,
1004     .class_init = qtest_class_init,
1005     .instance_size = sizeof(QTest),
1006     .interfaces = (InterfaceInfo[]) {
1007         { TYPE_USER_CREATABLE },
1008         { }
1009     }
1010 };
1011 
1012 static void register_types(void)
1013 {
1014     type_register_static(&qtest_info);
1015 }
1016 
1017 type_init(register_types);
1018