xref: /openbmc/qemu/tests/qtest/fuzz/generic_fuzz.c (revision 284d697c)
1 /*
2  * Generic Virtual-Device Fuzzing Target
3  *
4  * Copyright Red Hat Inc., 2020
5  *
6  * Authors:
7  *  Alexander Bulekov   <alxndr@bu.edu>
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 #include "qemu/osdep.h"
14 
15 #include <wordexp.h>
16 
17 #include "hw/core/cpu.h"
18 #include "tests/qtest/libqos/libqtest.h"
19 #include "fuzz.h"
20 #include "fork_fuzz.h"
21 #include "exec/address-spaces.h"
22 #include "string.h"
23 #include "exec/memory.h"
24 #include "exec/ramblock.h"
25 #include "exec/address-spaces.h"
26 #include "hw/qdev-core.h"
27 #include "hw/pci/pci.h"
28 #include "hw/boards.h"
29 #include "generic_fuzz_configs.h"
30 
31 /*
32  * SEPARATOR is used to separate "operations" in the fuzz input
33  */
34 #define SEPARATOR "FUZZ"
35 
36 enum cmds {
37     OP_IN,
38     OP_OUT,
39     OP_READ,
40     OP_WRITE,
41     OP_PCI_READ,
42     OP_PCI_WRITE,
43     OP_DISABLE_PCI,
44     OP_ADD_DMA_PATTERN,
45     OP_CLEAR_DMA_PATTERNS,
46     OP_CLOCK_STEP,
47 };
48 
49 #define DEFAULT_TIMEOUT_US 100000
50 #define USEC_IN_SEC 1000000000
51 
52 #define MAX_DMA_FILL_SIZE 0x10000
53 
54 #define PCI_HOST_BRIDGE_CFG 0xcf8
55 #define PCI_HOST_BRIDGE_DATA 0xcfc
56 
57 typedef struct {
58     ram_addr_t addr;
59     ram_addr_t size; /* The number of bytes until the end of the I/O region */
60 } address_range;
61 
62 static useconds_t timeout = DEFAULT_TIMEOUT_US;
63 
64 static bool qtest_log_enabled;
65 
66 /*
67  * A pattern used to populate a DMA region or perform a memwrite. This is
68  * useful for e.g. populating tables of unique addresses.
69  * Example {.index = 1; .stride = 2; .len = 3; .data = "\x00\x01\x02"}
70  * Renders as: 00 01 02   00 03 02   00 05 02   00 07 02 ...
71  */
72 typedef struct {
73     uint8_t index;      /* Index of a byte to increment by stride */
74     uint8_t stride;     /* Increment each index'th byte by this amount */
75     size_t len;
76     const uint8_t *data;
77 } pattern;
78 
79 /* Avoid filling the same DMA region between MMIO/PIO commands ? */
80 static bool avoid_double_fetches;
81 
82 static QTestState *qts_global; /* Need a global for the DMA callback */
83 
84 /*
85  * List of memory regions that are children of QOM objects specified by the
86  * user for fuzzing.
87  */
88 static GHashTable *fuzzable_memoryregions;
89 static GPtrArray *fuzzable_pci_devices;
90 
91 struct get_io_cb_info {
92     int index;
93     int found;
94     address_range result;
95 };
96 
97 static int get_io_address_cb(Int128 start, Int128 size,
98                           const MemoryRegion *mr, void *opaque) {
99     struct get_io_cb_info *info = opaque;
100     if (g_hash_table_lookup(fuzzable_memoryregions, mr)) {
101         if (info->index == 0) {
102             info->result.addr = (ram_addr_t)start;
103             info->result.size = (ram_addr_t)size;
104             info->found = 1;
105             return 1;
106         }
107         info->index--;
108     }
109     return 0;
110 }
111 
112 /*
113  * List of dma regions populated since the last fuzzing command. Used to ensure
114  * that we only write to each DMA address once, to avoid race conditions when
115  * building reproducers.
116  */
117 static GArray *dma_regions;
118 
119 static GArray *dma_patterns;
120 static int dma_pattern_index;
121 static bool pci_disabled;
122 
123 /*
124  * Allocate a block of memory and populate it with a pattern.
125  */
126 static void *pattern_alloc(pattern p, size_t len)
127 {
128     int i;
129     uint8_t *buf = g_malloc(len);
130     uint8_t sum = 0;
131 
132     for (i = 0; i < len; ++i) {
133         buf[i] = p.data[i % p.len];
134         if ((i % p.len) == p.index) {
135             buf[i] += sum;
136             sum += p.stride;
137         }
138     }
139     return buf;
140 }
141 
142 static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
143 {
144     unsigned access_size_max = mr->ops->valid.max_access_size;
145 
146     /*
147      * Regions are assumed to support 1-4 byte accesses unless
148      * otherwise specified.
149      */
150     if (access_size_max == 0) {
151         access_size_max = 4;
152     }
153 
154     /* Bound the maximum access by the alignment of the address.  */
155     if (!mr->ops->impl.unaligned) {
156         unsigned align_size_max = addr & -addr;
157         if (align_size_max != 0 && align_size_max < access_size_max) {
158             access_size_max = align_size_max;
159         }
160     }
161 
162     /* Don't attempt accesses larger than the maximum.  */
163     if (l > access_size_max) {
164         l = access_size_max;
165     }
166     l = pow2floor(l);
167 
168     return l;
169 }
170 
171 /*
172  * Call-back for functions that perform DMA reads from guest memory. Confirm
173  * that the region has not already been populated since the last loop in
174  * generic_fuzz(), avoiding potential race-conditions, which we don't have
175  * a good way for reproducing right now.
176  */
177 void fuzz_dma_read_cb(size_t addr, size_t len, MemoryRegion *mr, bool is_write)
178 {
179     /* Are we in the generic-fuzzer or are we using another fuzz-target? */
180     if (!qts_global) {
181         return;
182     }
183 
184     /*
185      * Return immediately if:
186      * - We have no DMA patterns defined
187      * - The length of the DMA read request is zero
188      * - The DMA read is hitting an MR other than the machine's main RAM
189      * - The DMA request is not a read (what happens for a address_space_map
190      *   with is_write=True? Can the device use the same pointer to do reads?)
191      * - The DMA request hits past the bounds of our RAM
192      */
193     if (dma_patterns->len == 0
194         || len == 0
195         /* || mr != MACHINE(qdev_get_machine())->ram */
196         || is_write
197         || addr > current_machine->ram_size) {
198         return;
199     }
200 
201     /*
202      * If we overlap with any existing dma_regions, split the range and only
203      * populate the non-overlapping parts.
204      */
205     address_range region;
206     bool double_fetch = false;
207     for (int i = 0;
208          i < dma_regions->len && (avoid_double_fetches || qtest_log_enabled);
209          ++i) {
210         region = g_array_index(dma_regions, address_range, i);
211         if (addr < region.addr + region.size && addr + len > region.addr) {
212             double_fetch = true;
213             if (addr < region.addr
214                 && avoid_double_fetches) {
215                 fuzz_dma_read_cb(addr, region.addr - addr, mr, is_write);
216             }
217             if (addr + len > region.addr + region.size
218                 && avoid_double_fetches) {
219                 fuzz_dma_read_cb(region.addr + region.size,
220                         addr + len - (region.addr + region.size), mr, is_write);
221             }
222             return;
223         }
224     }
225 
226     /* Cap the length of the DMA access to something reasonable */
227     len = MIN(len, MAX_DMA_FILL_SIZE);
228 
229     address_range ar = {addr, len};
230     g_array_append_val(dma_regions, ar);
231     pattern p = g_array_index(dma_patterns, pattern, dma_pattern_index);
232     void *buf = pattern_alloc(p, ar.size);
233     hwaddr l, addr1;
234     MemoryRegion *mr1;
235     uint8_t *ram_ptr;
236     while (len > 0) {
237         l = len;
238         mr1 = address_space_translate(first_cpu->as,
239                                       addr, &addr1, &l, true,
240                                       MEMTXATTRS_UNSPECIFIED);
241 
242         if (!(memory_region_is_ram(mr1) ||
243               memory_region_is_romd(mr1))) {
244             l = memory_access_size(mr1, l, addr1);
245         } else {
246             /* ROM/RAM case */
247             ram_ptr = qemu_map_ram_ptr(mr1->ram_block, addr1);
248             memcpy(ram_ptr, buf, l);
249             break;
250         }
251         len -= l;
252         buf += l;
253         addr += l;
254 
255     }
256     if (qtest_log_enabled) {
257         /*
258          * With QTEST_LOG, use a normal, slow QTest memwrite. Prefix the log
259          * that will be written by qtest.c with a DMA tag, so we can reorder
260          * the resulting QTest trace so the DMA fills precede the last PIO/MMIO
261          * command.
262          */
263         fprintf(stderr, "[DMA] ");
264         if (double_fetch) {
265             fprintf(stderr, "[DOUBLE-FETCH] ");
266         }
267         fflush(stderr);
268     }
269     qtest_memwrite(qts_global, ar.addr, buf, ar.size);
270     g_free(buf);
271 
272     /* Increment the index of the pattern for the next DMA access */
273     dma_pattern_index = (dma_pattern_index + 1) % dma_patterns->len;
274 }
275 
276 /*
277  * Here we want to convert a fuzzer-provided [io-region-index, offset] to
278  * a physical address. To do this, we iterate over all of the matched
279  * MemoryRegions. Check whether each region exists within the particular io
280  * space. Return the absolute address of the offset within the index'th region
281  * that is a subregion of the io_space and the distance until the end of the
282  * memory region.
283  */
284 static bool get_io_address(address_range *result, AddressSpace *as,
285                             uint8_t index,
286                             uint32_t offset) {
287     FlatView *view;
288     view = as->current_map;
289     g_assert(view);
290     struct get_io_cb_info cb_info = {};
291 
292     cb_info.index = index;
293 
294     /*
295      * Loop around the FlatView until we match "index" number of
296      * fuzzable_memoryregions, or until we know that there are no matching
297      * memory_regions.
298      */
299     do {
300         flatview_for_each_range(view, get_io_address_cb , &cb_info);
301     } while (cb_info.index != index && !cb_info.found);
302 
303     *result = cb_info.result;
304     return cb_info.found;
305 }
306 
307 static bool get_pio_address(address_range *result,
308                             uint8_t index, uint16_t offset)
309 {
310     /*
311      * PIO BARs can be set past the maximum port address (0xFFFF). Thus, result
312      * can contain an addr that extends past the PIO space. When we pass this
313      * address to qtest_in/qtest_out, it is cast to a uint16_t, so we might end
314      * up fuzzing a completely different MemoryRegion/Device. Therefore, check
315      * that the address here is within the PIO space limits.
316      */
317     bool found = get_io_address(result, &address_space_io, index, offset);
318     return result->addr <= 0xFFFF ? found : false;
319 }
320 
321 static bool get_mmio_address(address_range *result,
322                              uint8_t index, uint32_t offset)
323 {
324     return get_io_address(result, &address_space_memory, index, offset);
325 }
326 
327 static void op_in(QTestState *s, const unsigned char * data, size_t len)
328 {
329     enum Sizes {Byte, Word, Long, end_sizes};
330     struct {
331         uint8_t size;
332         uint8_t base;
333         uint16_t offset;
334     } a;
335     address_range abs;
336 
337     if (len < sizeof(a)) {
338         return;
339     }
340     memcpy(&a, data, sizeof(a));
341     if (get_pio_address(&abs, a.base, a.offset) == 0) {
342         return;
343     }
344 
345     switch (a.size %= end_sizes) {
346     case Byte:
347         qtest_inb(s, abs.addr);
348         break;
349     case Word:
350         if (abs.size >= 2) {
351             qtest_inw(s, abs.addr);
352         }
353         break;
354     case Long:
355         if (abs.size >= 4) {
356             qtest_inl(s, abs.addr);
357         }
358         break;
359     }
360 }
361 
362 static void op_out(QTestState *s, const unsigned char * data, size_t len)
363 {
364     enum Sizes {Byte, Word, Long, end_sizes};
365     struct {
366         uint8_t size;
367         uint8_t base;
368         uint16_t offset;
369         uint32_t value;
370     } a;
371     address_range abs;
372 
373     if (len < sizeof(a)) {
374         return;
375     }
376     memcpy(&a, data, sizeof(a));
377 
378     if (get_pio_address(&abs, a.base, a.offset) == 0) {
379         return;
380     }
381 
382     switch (a.size %= end_sizes) {
383     case Byte:
384         qtest_outb(s, abs.addr, a.value & 0xFF);
385         break;
386     case Word:
387         if (abs.size >= 2) {
388             qtest_outw(s, abs.addr, a.value & 0xFFFF);
389         }
390         break;
391     case Long:
392         if (abs.size >= 4) {
393             qtest_outl(s, abs.addr, a.value);
394         }
395         break;
396     }
397 }
398 
399 static void op_read(QTestState *s, const unsigned char * data, size_t len)
400 {
401     enum Sizes {Byte, Word, Long, Quad, end_sizes};
402     struct {
403         uint8_t size;
404         uint8_t base;
405         uint32_t offset;
406     } a;
407     address_range abs;
408 
409     if (len < sizeof(a)) {
410         return;
411     }
412     memcpy(&a, data, sizeof(a));
413 
414     if (get_mmio_address(&abs, a.base, a.offset) == 0) {
415         return;
416     }
417 
418     switch (a.size %= end_sizes) {
419     case Byte:
420         qtest_readb(s, abs.addr);
421         break;
422     case Word:
423         if (abs.size >= 2) {
424             qtest_readw(s, abs.addr);
425         }
426         break;
427     case Long:
428         if (abs.size >= 4) {
429             qtest_readl(s, abs.addr);
430         }
431         break;
432     case Quad:
433         if (abs.size >= 8) {
434             qtest_readq(s, abs.addr);
435         }
436         break;
437     }
438 }
439 
440 static void op_write(QTestState *s, const unsigned char * data, size_t len)
441 {
442     enum Sizes {Byte, Word, Long, Quad, end_sizes};
443     struct {
444         uint8_t size;
445         uint8_t base;
446         uint32_t offset;
447         uint64_t value;
448     } a;
449     address_range abs;
450 
451     if (len < sizeof(a)) {
452         return;
453     }
454     memcpy(&a, data, sizeof(a));
455 
456     if (get_mmio_address(&abs, a.base, a.offset) == 0) {
457         return;
458     }
459 
460     switch (a.size %= end_sizes) {
461     case Byte:
462             qtest_writeb(s, abs.addr, a.value & 0xFF);
463         break;
464     case Word:
465         if (abs.size >= 2) {
466             qtest_writew(s, abs.addr, a.value & 0xFFFF);
467         }
468         break;
469     case Long:
470         if (abs.size >= 4) {
471             qtest_writel(s, abs.addr, a.value & 0xFFFFFFFF);
472         }
473         break;
474     case Quad:
475         if (abs.size >= 8) {
476             qtest_writeq(s, abs.addr, a.value);
477         }
478         break;
479     }
480 }
481 
482 static void op_pci_read(QTestState *s, const unsigned char * data, size_t len)
483 {
484     enum Sizes {Byte, Word, Long, end_sizes};
485     struct {
486         uint8_t size;
487         uint8_t base;
488         uint8_t offset;
489     } a;
490     if (len < sizeof(a) || fuzzable_pci_devices->len == 0 || pci_disabled) {
491         return;
492     }
493     memcpy(&a, data, sizeof(a));
494     PCIDevice *dev = g_ptr_array_index(fuzzable_pci_devices,
495                                   a.base % fuzzable_pci_devices->len);
496     int devfn = dev->devfn;
497     qtest_outl(s, PCI_HOST_BRIDGE_CFG, (1U << 31) | (devfn << 8) | a.offset);
498     switch (a.size %= end_sizes) {
499     case Byte:
500         qtest_inb(s, PCI_HOST_BRIDGE_DATA);
501         break;
502     case Word:
503         qtest_inw(s, PCI_HOST_BRIDGE_DATA);
504         break;
505     case Long:
506         qtest_inl(s, PCI_HOST_BRIDGE_DATA);
507         break;
508     }
509 }
510 
511 static void op_pci_write(QTestState *s, const unsigned char * data, size_t len)
512 {
513     enum Sizes {Byte, Word, Long, end_sizes};
514     struct {
515         uint8_t size;
516         uint8_t base;
517         uint8_t offset;
518         uint32_t value;
519     } a;
520     if (len < sizeof(a) || fuzzable_pci_devices->len == 0 || pci_disabled) {
521         return;
522     }
523     memcpy(&a, data, sizeof(a));
524     PCIDevice *dev = g_ptr_array_index(fuzzable_pci_devices,
525                                   a.base % fuzzable_pci_devices->len);
526     int devfn = dev->devfn;
527     qtest_outl(s, PCI_HOST_BRIDGE_CFG, (1U << 31) | (devfn << 8) | a.offset);
528     switch (a.size %= end_sizes) {
529     case Byte:
530         qtest_outb(s, PCI_HOST_BRIDGE_DATA, a.value & 0xFF);
531         break;
532     case Word:
533         qtest_outw(s, PCI_HOST_BRIDGE_DATA, a.value & 0xFFFF);
534         break;
535     case Long:
536         qtest_outl(s, PCI_HOST_BRIDGE_DATA, a.value & 0xFFFFFFFF);
537         break;
538     }
539 }
540 
541 static void op_add_dma_pattern(QTestState *s,
542                                const unsigned char *data, size_t len)
543 {
544     struct {
545         /*
546          * index and stride can be used to increment the index-th byte of the
547          * pattern by the value stride, for each loop of the pattern.
548          */
549         uint8_t index;
550         uint8_t stride;
551     } a;
552 
553     if (len < sizeof(a) + 1) {
554         return;
555     }
556     memcpy(&a, data, sizeof(a));
557     pattern p = {a.index, a.stride, len - sizeof(a), data + sizeof(a)};
558     p.index = a.index % p.len;
559     g_array_append_val(dma_patterns, p);
560     return;
561 }
562 
563 static void op_clear_dma_patterns(QTestState *s,
564                                   const unsigned char *data, size_t len)
565 {
566     g_array_set_size(dma_patterns, 0);
567     dma_pattern_index = 0;
568 }
569 
570 static void op_clock_step(QTestState *s, const unsigned char *data, size_t len)
571 {
572     qtest_clock_step_next(s);
573 }
574 
575 static void op_disable_pci(QTestState *s, const unsigned char *data, size_t len)
576 {
577     pci_disabled = true;
578 }
579 
580 static void handle_timeout(int sig)
581 {
582     if (qtest_log_enabled) {
583         fprintf(stderr, "[Timeout]\n");
584         fflush(stderr);
585     }
586     _Exit(0);
587 }
588 
589 /*
590  * Here, we interpret random bytes from the fuzzer, as a sequence of commands.
591  * Some commands can be variable-width, so we use a separator, SEPARATOR, to
592  * specify the boundaries between commands. SEPARATOR is used to separate
593  * "operations" in the fuzz input. Why use a separator, instead of just using
594  * the operations' length to identify operation boundaries?
595  *   1. This is a simple way to support variable-length operations
596  *   2. This adds "stability" to the input.
597  *      For example take the input "AbBcgDefg", where there is no separator and
598  *      Opcodes are capitalized.
599  *      Simply, by removing the first byte, we end up with a very different
600  *      sequence:
601  *      BbcGdefg...
602  *      By adding a separator, we avoid this problem:
603  *      Ab SEP Bcg SEP Defg -> B SEP Bcg SEP Defg
604  *      Since B uses two additional bytes as operands, the first "B" will be
605  *      ignored. The fuzzer actively tries to reduce inputs, so such unused
606  *      bytes are likely to be pruned, eventually.
607  *
608  *  SEPARATOR is trivial for the fuzzer to discover when using ASan. Optionally,
609  *  SEPARATOR can be manually specified as a dictionary value (see libfuzzer's
610  *  -dict), though this should not be necessary.
611  *
612  * As a result, the stream of bytes is converted into a sequence of commands.
613  * In a simplified example where SEPARATOR is 0xFF:
614  * 00 01 02 FF 03 04 05 06 FF 01 FF ...
615  * becomes this sequence of commands:
616  * 00 01 02    -> op00 (0102)   -> in (0102, 2)
617  * 03 04 05 06 -> op03 (040506) -> write (040506, 3)
618  * 01          -> op01 (-,0)    -> out (-,0)
619  * ...
620  *
621  * Note here that it is the job of the individual opcode functions to check
622  * that enough data was provided. I.e. in the last command out (,0), out needs
623  * to check that there is not enough data provided to select an address/value
624  * for the operation.
625  */
626 static void generic_fuzz(QTestState *s, const unsigned char *Data, size_t Size)
627 {
628     void (*ops[]) (QTestState *s, const unsigned char* , size_t) = {
629         [OP_IN]                 = op_in,
630         [OP_OUT]                = op_out,
631         [OP_READ]               = op_read,
632         [OP_WRITE]              = op_write,
633         [OP_PCI_READ]           = op_pci_read,
634         [OP_PCI_WRITE]          = op_pci_write,
635         [OP_DISABLE_PCI]        = op_disable_pci,
636         [OP_ADD_DMA_PATTERN]    = op_add_dma_pattern,
637         [OP_CLEAR_DMA_PATTERNS] = op_clear_dma_patterns,
638         [OP_CLOCK_STEP]         = op_clock_step,
639     };
640     const unsigned char *cmd = Data;
641     const unsigned char *nextcmd;
642     size_t cmd_len;
643     uint8_t op;
644 
645     if (fork() == 0) {
646         /*
647          * Sometimes the fuzzer will find inputs that take quite a long time to
648          * process. Often times, these inputs do not result in new coverage.
649          * Even if these inputs might be interesting, they can slow down the
650          * fuzzer, overall. Set a timeout to avoid hurting performance, too much
651          */
652         if (timeout) {
653             struct sigaction sact;
654             struct itimerval timer;
655 
656             sigemptyset(&sact.sa_mask);
657             sact.sa_flags   = SA_NODEFER;
658             sact.sa_handler = handle_timeout;
659             sigaction(SIGALRM, &sact, NULL);
660 
661             memset(&timer, 0, sizeof(timer));
662             timer.it_value.tv_sec = timeout / USEC_IN_SEC;
663             timer.it_value.tv_usec = timeout % USEC_IN_SEC;
664             setitimer(ITIMER_VIRTUAL, &timer, NULL);
665         }
666 
667         op_clear_dma_patterns(s, NULL, 0);
668         pci_disabled = false;
669 
670         while (cmd && Size) {
671             /* Get the length until the next command or end of input */
672             nextcmd = memmem(cmd, Size, SEPARATOR, strlen(SEPARATOR));
673             cmd_len = nextcmd ? nextcmd - cmd : Size;
674 
675             if (cmd_len > 0) {
676                 /* Interpret the first byte of the command as an opcode */
677                 op = *cmd % (sizeof(ops) / sizeof((ops)[0]));
678                 ops[op](s, cmd + 1, cmd_len - 1);
679 
680                 /* Run the main loop */
681                 flush_events(s);
682             }
683             /* Advance to the next command */
684             cmd = nextcmd ? nextcmd + sizeof(SEPARATOR) - 1 : nextcmd;
685             Size = Size - (cmd_len + sizeof(SEPARATOR) - 1);
686             g_array_set_size(dma_regions, 0);
687         }
688         _Exit(0);
689     } else {
690         flush_events(s);
691         wait(0);
692     }
693 }
694 
695 static void usage(void)
696 {
697     printf("Please specify the following environment variables:\n");
698     printf("QEMU_FUZZ_ARGS= the command line arguments passed to qemu\n");
699     printf("QEMU_FUZZ_OBJECTS= "
700             "a space separated list of QOM type names for objects to fuzz\n");
701     printf("Optionally: QEMU_AVOID_DOUBLE_FETCH= "
702             "Try to avoid racy DMA double fetch bugs? %d by default\n",
703             avoid_double_fetches);
704     printf("Optionally: QEMU_FUZZ_TIMEOUT= Specify a custom timeout (us). "
705             "0 to disable. %d by default\n", timeout);
706     exit(0);
707 }
708 
709 static int locate_fuzz_memory_regions(Object *child, void *opaque)
710 {
711     const char *name;
712     MemoryRegion *mr;
713     if (object_dynamic_cast(child, TYPE_MEMORY_REGION)) {
714         mr = MEMORY_REGION(child);
715         if ((memory_region_is_ram(mr) ||
716             memory_region_is_ram_device(mr) ||
717             memory_region_is_rom(mr)) == false) {
718             name = object_get_canonical_path_component(child);
719             /*
720              * We don't want duplicate pointers to the same MemoryRegion, so
721              * try to remove copies of the pointer, before adding it.
722              */
723             g_hash_table_insert(fuzzable_memoryregions, mr, (gpointer)true);
724         }
725     }
726     return 0;
727 }
728 
729 static int locate_fuzz_objects(Object *child, void *opaque)
730 {
731     char *pattern = opaque;
732     if (g_pattern_match_simple(pattern, object_get_typename(child))) {
733         /* Find and save ptrs to any child MemoryRegions */
734         object_child_foreach_recursive(child, locate_fuzz_memory_regions, NULL);
735 
736         /*
737          * We matched an object. If its a PCI device, store a pointer to it so
738          * we can map BARs and fuzz its config space.
739          */
740         if (object_dynamic_cast(OBJECT(child), TYPE_PCI_DEVICE)) {
741             /*
742              * Don't want duplicate pointers to the same PCIDevice, so remove
743              * copies of the pointer, before adding it.
744              */
745             g_ptr_array_remove_fast(fuzzable_pci_devices, PCI_DEVICE(child));
746             g_ptr_array_add(fuzzable_pci_devices, PCI_DEVICE(child));
747         }
748     } else if (object_dynamic_cast(OBJECT(child), TYPE_MEMORY_REGION)) {
749         if (g_pattern_match_simple(pattern,
750             object_get_canonical_path_component(child))) {
751             MemoryRegion *mr;
752             mr = MEMORY_REGION(child);
753             if ((memory_region_is_ram(mr) ||
754                  memory_region_is_ram_device(mr) ||
755                  memory_region_is_rom(mr)) == false) {
756                 g_hash_table_insert(fuzzable_memoryregions, mr, (gpointer)true);
757             }
758         }
759     }
760     return 0;
761 }
762 
763 static void generic_pre_fuzz(QTestState *s)
764 {
765     GHashTableIter iter;
766     MemoryRegion *mr;
767     char **result;
768 
769     if (!getenv("QEMU_FUZZ_OBJECTS")) {
770         usage();
771     }
772     if (getenv("QTEST_LOG")) {
773         qtest_log_enabled = 1;
774     }
775     if (getenv("QEMU_AVOID_DOUBLE_FETCH")) {
776         avoid_double_fetches = 1;
777     }
778     if (getenv("QEMU_FUZZ_TIMEOUT")) {
779         timeout = g_ascii_strtoll(getenv("QEMU_FUZZ_TIMEOUT"), NULL, 0);
780     }
781     qts_global = s;
782 
783     dma_regions = g_array_new(false, false, sizeof(address_range));
784     dma_patterns = g_array_new(false, false, sizeof(pattern));
785 
786     fuzzable_memoryregions = g_hash_table_new(NULL, NULL);
787     fuzzable_pci_devices   = g_ptr_array_new();
788 
789     result = g_strsplit(getenv("QEMU_FUZZ_OBJECTS"), " ", -1);
790     for (int i = 0; result[i] != NULL; i++) {
791         printf("Matching objects by name %s\n", result[i]);
792         object_child_foreach_recursive(qdev_get_machine(),
793                                     locate_fuzz_objects,
794                                     result[i]);
795     }
796     g_strfreev(result);
797     printf("This process will try to fuzz the following MemoryRegions:\n");
798 
799     g_hash_table_iter_init(&iter, fuzzable_memoryregions);
800     while (g_hash_table_iter_next(&iter, (gpointer)&mr, NULL)) {
801         printf("  * %s (size %lx)\n",
802                object_get_canonical_path_component(&(mr->parent_obj)),
803                (uint64_t)mr->size);
804     }
805 
806     if (!g_hash_table_size(fuzzable_memoryregions)) {
807         printf("No fuzzable memory regions found...\n");
808         exit(1);
809     }
810 
811     counter_shm_init();
812 }
813 
814 /*
815  * When libfuzzer gives us two inputs to combine, return a new input with the
816  * following structure:
817  *
818  * Input 1 (data1)
819  * SEPARATOR
820  * Clear out the DMA Patterns
821  * SEPARATOR
822  * Disable the pci_read/write instructions
823  * SEPARATOR
824  * Input 2 (data2)
825  *
826  * The idea is to collate the core behaviors of the two inputs.
827  * For example:
828  * Input 1: maps a device's BARs, sets up three DMA patterns, and triggers
829  *          device functionality A
830  * Input 2: maps a device's BARs, sets up one DMA pattern, and triggers device
831  *          functionality B
832  *
833  * This function attempts to produce an input that:
834  * Ouptut: maps a device's BARs, set up three DMA patterns, triggers
835  *          functionality A device, replaces the DMA patterns with a single
836  *          patten, and triggers device functionality B.
837  */
838 static size_t generic_fuzz_crossover(const uint8_t *data1, size_t size1, const
839                                      uint8_t *data2, size_t size2, uint8_t *out,
840                                      size_t max_out_size, unsigned int seed)
841 {
842     size_t copy_len = 0, size = 0;
843 
844     /* Check that we have enough space for data1 and at least part of data2 */
845     if (max_out_size <= size1 + strlen(SEPARATOR) * 3 + 2) {
846         return 0;
847     }
848 
849     /* Copy_Len in the first input */
850     copy_len = size1;
851     memcpy(out + size, data1, copy_len);
852     size += copy_len;
853     max_out_size -= copy_len;
854 
855     /* Append a separator */
856     copy_len = strlen(SEPARATOR);
857     memcpy(out + size, SEPARATOR, copy_len);
858     size += copy_len;
859     max_out_size -= copy_len;
860 
861     /* Clear out the DMA Patterns */
862     copy_len = 1;
863     if (copy_len) {
864         out[size] = OP_CLEAR_DMA_PATTERNS;
865     }
866     size += copy_len;
867     max_out_size -= copy_len;
868 
869     /* Append a separator */
870     copy_len = strlen(SEPARATOR);
871     memcpy(out + size, SEPARATOR, copy_len);
872     size += copy_len;
873     max_out_size -= copy_len;
874 
875     /* Disable PCI ops. Assume data1 took care of setting up PCI */
876     copy_len = 1;
877     if (copy_len) {
878         out[size] = OP_DISABLE_PCI;
879     }
880     size += copy_len;
881     max_out_size -= copy_len;
882 
883     /* Append a separator */
884     copy_len = strlen(SEPARATOR);
885     memcpy(out + size, SEPARATOR, copy_len);
886     size += copy_len;
887     max_out_size -= copy_len;
888 
889     /* Copy_Len over the second input */
890     copy_len = MIN(size2, max_out_size);
891     memcpy(out + size, data2, copy_len);
892     size += copy_len;
893     max_out_size -= copy_len;
894 
895     return  size;
896 }
897 
898 
899 static GString *generic_fuzz_cmdline(FuzzTarget *t)
900 {
901     GString *cmd_line = g_string_new(TARGET_NAME);
902     if (!getenv("QEMU_FUZZ_ARGS")) {
903         usage();
904     }
905     g_string_append_printf(cmd_line, " -display none \
906                                       -machine accel=qtest, \
907                                       -m 512M %s ", getenv("QEMU_FUZZ_ARGS"));
908     return cmd_line;
909 }
910 
911 static GString *generic_fuzz_predefined_config_cmdline(FuzzTarget *t)
912 {
913     const generic_fuzz_config *config;
914     g_assert(t->opaque);
915 
916     config = t->opaque;
917     setenv("QEMU_FUZZ_ARGS", config->args, 1);
918     setenv("QEMU_FUZZ_OBJECTS", config->objects, 1);
919     return generic_fuzz_cmdline(t);
920 }
921 
922 static void register_generic_fuzz_targets(void)
923 {
924     fuzz_add_target(&(FuzzTarget){
925             .name = "generic-fuzz",
926             .description = "Fuzz based on any qemu command-line args. ",
927             .get_init_cmdline = generic_fuzz_cmdline,
928             .pre_fuzz = generic_pre_fuzz,
929             .fuzz = generic_fuzz,
930             .crossover = generic_fuzz_crossover
931     });
932 
933     GString *name;
934     const generic_fuzz_config *config;
935 
936     for (int i = 0;
937          i < sizeof(predefined_configs) / sizeof(generic_fuzz_config);
938          i++) {
939         config = predefined_configs + i;
940         name = g_string_new("generic-fuzz");
941         g_string_append_printf(name, "-%s", config->name);
942         fuzz_add_target(&(FuzzTarget){
943                 .name = name->str,
944                 .description = "Predefined generic-fuzz config.",
945                 .get_init_cmdline = generic_fuzz_predefined_config_cmdline,
946                 .pre_fuzz = generic_pre_fuzz,
947                 .fuzz = generic_fuzz,
948                 .crossover = generic_fuzz_crossover,
949                 .opaque = (void *)config
950         });
951     }
952 }
953 
954 fuzz_target_init(register_generic_fuzz_targets);
955