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