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