aboutsummaryrefslogtreecommitdiffstats
path: root/tests/qtest/fuzz
diff options
context:
space:
mode:
Diffstat (limited to 'tests/qtest/fuzz')
-rw-r--r--tests/qtest/fuzz/fork_fuzz.c41
-rw-r--r--tests/qtest/fuzz/fork_fuzz.h23
-rw-r--r--tests/qtest/fuzz/fork_fuzz.ld56
-rw-r--r--tests/qtest/fuzz/fuzz.c252
-rw-r--r--tests/qtest/fuzz/fuzz.h125
-rw-r--r--tests/qtest/fuzz/generic_fuzz.c1043
-rw-r--r--tests/qtest/fuzz/generic_fuzz_configs.h245
-rw-r--r--tests/qtest/fuzz/i440fx_fuzz.c207
-rw-r--r--tests/qtest/fuzz/meson.build38
-rw-r--r--tests/qtest/fuzz/qos_fuzz.c217
-rw-r--r--tests/qtest/fuzz/qos_fuzz.h33
-rw-r--r--tests/qtest/fuzz/qtest_wrappers.c252
-rw-r--r--tests/qtest/fuzz/virtio_blk_fuzz.c234
-rw-r--r--tests/qtest/fuzz/virtio_net_fuzz.c201
-rw-r--r--tests/qtest/fuzz/virtio_scsi_fuzz.c215
15 files changed, 3182 insertions, 0 deletions
diff --git a/tests/qtest/fuzz/fork_fuzz.c b/tests/qtest/fuzz/fork_fuzz.c
new file mode 100644
index 000000000..6ffb2a793
--- /dev/null
+++ b/tests/qtest/fuzz/fork_fuzz.c
@@ -0,0 +1,41 @@
+/*
+ * Fork-based fuzzing helpers
+ *
+ * Copyright Red Hat Inc., 2019
+ *
+ * Authors:
+ * Alexander Bulekov <alxndr@bu.edu>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ */
+
+#include "qemu/osdep.h"
+#include "fork_fuzz.h"
+
+
+void counter_shm_init(void)
+{
+ /* Copy what's in the counter region to a temporary buffer.. */
+ void *copy = malloc(&__FUZZ_COUNTERS_END - &__FUZZ_COUNTERS_START);
+ memcpy(copy,
+ &__FUZZ_COUNTERS_START,
+ &__FUZZ_COUNTERS_END - &__FUZZ_COUNTERS_START);
+
+ /* Map a shared region over the counter region */
+ if (mmap(&__FUZZ_COUNTERS_START,
+ &__FUZZ_COUNTERS_END - &__FUZZ_COUNTERS_START,
+ PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED | MAP_ANONYMOUS,
+ 0, 0) == MAP_FAILED) {
+ perror("Error: ");
+ exit(1);
+ }
+
+ /* Copy the original data back to the counter-region */
+ memcpy(&__FUZZ_COUNTERS_START, copy,
+ &__FUZZ_COUNTERS_END - &__FUZZ_COUNTERS_START);
+ free(copy);
+}
+
+
diff --git a/tests/qtest/fuzz/fork_fuzz.h b/tests/qtest/fuzz/fork_fuzz.h
new file mode 100644
index 000000000..9ecb8b58e
--- /dev/null
+++ b/tests/qtest/fuzz/fork_fuzz.h
@@ -0,0 +1,23 @@
+/*
+ * Fork-based fuzzing helpers
+ *
+ * Copyright Red Hat Inc., 2019
+ *
+ * Authors:
+ * Alexander Bulekov <alxndr@bu.edu>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ */
+
+#ifndef FORK_FUZZ_H
+#define FORK_FUZZ_H
+
+extern uint8_t __FUZZ_COUNTERS_START;
+extern uint8_t __FUZZ_COUNTERS_END;
+
+void counter_shm_init(void);
+
+#endif
+
diff --git a/tests/qtest/fuzz/fork_fuzz.ld b/tests/qtest/fuzz/fork_fuzz.ld
new file mode 100644
index 000000000..cfb88b7fd
--- /dev/null
+++ b/tests/qtest/fuzz/fork_fuzz.ld
@@ -0,0 +1,56 @@
+/*
+ * We adjust linker script modification to place all of the stuff that needs to
+ * persist across fuzzing runs into a contiguous section of memory. Then, it is
+ * easy to re-map the counter-related memory as shared.
+ */
+
+SECTIONS
+{
+ .data.fuzz_start : ALIGN(4K)
+ {
+ __FUZZ_COUNTERS_START = .;
+ __start___sancov_cntrs = .;
+ *(_*sancov_cntrs);
+ __stop___sancov_cntrs = .;
+
+ /* Lowest stack counter */
+ *(__sancov_lowest_stack);
+ }
+}
+INSERT AFTER .data;
+
+SECTIONS
+{
+ .data.fuzz_ordered :
+ {
+ /*
+ * Coverage counters. They're not necessary for fuzzing, but are useful
+ * for analyzing the fuzzing performance
+ */
+ __start___llvm_prf_cnts = .;
+ *(*llvm_prf_cnts);
+ __stop___llvm_prf_cnts = .;
+
+ /* Internal Libfuzzer TracePC object which contains the ValueProfileMap */
+ FuzzerTracePC*(.bss*);
+ /*
+ * In case the above line fails, explicitly specify the (mangled) name of
+ * the object we care about
+ */
+ *(.bss._ZN6fuzzer3TPCE);
+ }
+}
+INSERT AFTER .data.fuzz_start;
+
+SECTIONS
+{
+ .data.fuzz_end : ALIGN(4K)
+ {
+ __FUZZ_COUNTERS_END = .;
+ }
+}
+/*
+ * Don't overwrite the SECTIONS in the default linker script. Instead insert the
+ * above into the default script
+ */
+INSERT AFTER .data.fuzz_ordered;
diff --git a/tests/qtest/fuzz/fuzz.c b/tests/qtest/fuzz/fuzz.c
new file mode 100644
index 000000000..5f77c8498
--- /dev/null
+++ b/tests/qtest/fuzz/fuzz.c
@@ -0,0 +1,252 @@
+/*
+ * fuzzing driver
+ *
+ * Copyright Red Hat Inc., 2019
+ *
+ * Authors:
+ * Alexander Bulekov <alxndr@bu.edu>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ */
+
+#include "qemu/osdep.h"
+
+#include <wordexp.h>
+
+#include "qemu/datadir.h"
+#include "sysemu/sysemu.h"
+#include "sysemu/qtest.h"
+#include "sysemu/runstate.h"
+#include "qemu/main-loop.h"
+#include "qemu/rcu.h"
+#include "tests/qtest/libqos/libqtest.h"
+#include "tests/qtest/libqos/qgraph.h"
+#include "fuzz.h"
+
+#define MAX_EVENT_LOOPS 10
+
+typedef struct FuzzTargetState {
+ FuzzTarget *target;
+ QSLIST_ENTRY(FuzzTargetState) target_list;
+} FuzzTargetState;
+
+typedef QSLIST_HEAD(, FuzzTargetState) FuzzTargetList;
+
+static const char *fuzz_arch = TARGET_NAME;
+
+static FuzzTargetList *fuzz_target_list;
+static FuzzTarget *fuzz_target;
+static QTestState *fuzz_qts;
+
+
+
+void flush_events(QTestState *s)
+{
+ int i = MAX_EVENT_LOOPS;
+ while (g_main_context_pending(NULL) && i-- > 0) {
+ main_loop_wait(false);
+ }
+}
+
+static QTestState *qtest_setup(void)
+{
+ qtest_server_set_send_handler(&qtest_client_inproc_recv, &fuzz_qts);
+ return qtest_inproc_init(&fuzz_qts, false, fuzz_arch,
+ &qtest_server_inproc_recv);
+}
+
+void fuzz_add_target(const FuzzTarget *target)
+{
+ FuzzTargetState *tmp;
+ FuzzTargetState *target_state;
+ if (!fuzz_target_list) {
+ fuzz_target_list = g_new0(FuzzTargetList, 1);
+ }
+
+ QSLIST_FOREACH(tmp, fuzz_target_list, target_list) {
+ if (g_strcmp0(tmp->target->name, target->name) == 0) {
+ fprintf(stderr, "Error: Fuzz target name %s already in use\n",
+ target->name);
+ abort();
+ }
+ }
+ target_state = g_new0(FuzzTargetState, 1);
+ target_state->target = g_new0(FuzzTarget, 1);
+ *(target_state->target) = *target;
+ QSLIST_INSERT_HEAD(fuzz_target_list, target_state, target_list);
+}
+
+
+
+static void usage(char *path)
+{
+ printf("Usage: %s --fuzz-target=FUZZ_TARGET [LIBFUZZER ARGUMENTS]\n", path);
+ printf("where FUZZ_TARGET is one of:\n");
+ FuzzTargetState *tmp;
+ if (!fuzz_target_list) {
+ fprintf(stderr, "Fuzz target list not initialized\n");
+ abort();
+ }
+ QSLIST_FOREACH(tmp, fuzz_target_list, target_list) {
+ printf(" * %s : %s\n", tmp->target->name,
+ tmp->target->description);
+ }
+ printf("Alternatively, add -target-FUZZ_TARGET to the executable name\n\n"
+ "Set the environment variable FUZZ_SERIALIZE_QTEST=1 to serialize\n"
+ "QTest commands into an ASCII protocol. Useful for building crash\n"
+ "reproducers, but slows down execution.\n\n"
+ "Set the environment variable QTEST_LOG=1 to log all qtest commands"
+ "\n");
+ exit(0);
+}
+
+static FuzzTarget *fuzz_get_target(char* name)
+{
+ FuzzTargetState *tmp;
+ if (!fuzz_target_list) {
+ fprintf(stderr, "Fuzz target list not initialized\n");
+ abort();
+ }
+
+ QSLIST_FOREACH(tmp, fuzz_target_list, target_list) {
+ if (strcmp(tmp->target->name, name) == 0) {
+ return tmp->target;
+ }
+ }
+ return NULL;
+}
+
+
+/* Sometimes called by libfuzzer to mutate two inputs into one */
+size_t LLVMFuzzerCustomCrossOver(const uint8_t *data1, size_t size1,
+ const uint8_t *data2, size_t size2,
+ uint8_t *out, size_t max_out_size,
+ unsigned int seed)
+{
+ if (fuzz_target->crossover) {
+ return fuzz_target->crossover(data1, size1, data2, size2, out,
+ max_out_size, seed);
+ }
+ return 0;
+}
+
+/* Executed for each fuzzing-input */
+int LLVMFuzzerTestOneInput(const unsigned char *Data, size_t Size)
+{
+ /*
+ * Do the pre-fuzz-initialization before the first fuzzing iteration,
+ * instead of before the actual fuzz loop. This is needed since libfuzzer
+ * may fork off additional workers, prior to the fuzzing loop, and if
+ * pre_fuzz() sets up e.g. shared memory, this should be done for the
+ * individual worker processes
+ */
+ static int pre_fuzz_done;
+ if (!pre_fuzz_done && fuzz_target->pre_fuzz) {
+ fuzz_target->pre_fuzz(fuzz_qts);
+ pre_fuzz_done = true;
+ }
+
+ fuzz_target->fuzz(fuzz_qts, Data, Size);
+ return 0;
+}
+
+/* Executed once, prior to fuzzing */
+int LLVMFuzzerInitialize(int *argc, char ***argv, char ***envp)
+{
+
+ char *target_name;
+ const char *bindir;
+ char *datadir;
+ GString *cmd_line;
+ gchar *pretty_cmd_line;
+ bool serialize = false;
+
+ /* Initialize qgraph and modules */
+ qos_graph_init();
+ module_call_init(MODULE_INIT_FUZZ_TARGET);
+ module_call_init(MODULE_INIT_QOM);
+ module_call_init(MODULE_INIT_LIBQOS);
+
+ qemu_init_exec_dir(**argv);
+ target_name = strstr(**argv, "-target-");
+ if (target_name) { /* The binary name specifies the target */
+ target_name += strlen("-target-");
+ /*
+ * With oss-fuzz, the executable is kept in the root of a directory (we
+ * cannot assume the path). All data (including bios binaries) must be
+ * in the same dir, or a subdir. Thus, we cannot place the pc-bios so
+ * that it would be in exec_dir/../pc-bios.
+ * As a workaround, oss-fuzz allows us to use argv[0] to get the
+ * location of the executable. Using this we add exec_dir/pc-bios to
+ * the datadirs.
+ */
+ bindir = qemu_get_exec_dir();
+ datadir = g_build_filename(bindir, "pc-bios", NULL);
+ if (g_file_test(datadir, G_FILE_TEST_IS_DIR)) {
+ qemu_add_data_dir(datadir);
+ } else {
+ g_free(datadir);
+ }
+ } else if (*argc > 1) { /* The target is specified as an argument */
+ target_name = (*argv)[1];
+ if (!strstr(target_name, "--fuzz-target=")) {
+ usage(**argv);
+ }
+ target_name += strlen("--fuzz-target=");
+ } else {
+ usage(**argv);
+ }
+
+ /* Should we always serialize qtest commands? */
+ if (getenv("FUZZ_SERIALIZE_QTEST")) {
+ serialize = true;
+ }
+
+ fuzz_qtest_set_serialize(serialize);
+
+ /* Identify the fuzz target */
+ fuzz_target = fuzz_get_target(target_name);
+ if (!fuzz_target) {
+ usage(**argv);
+ }
+
+ fuzz_qts = qtest_setup();
+
+ if (fuzz_target->pre_vm_init) {
+ fuzz_target->pre_vm_init();
+ }
+
+ /* Run QEMU's softmmu main with the fuzz-target dependent arguments */
+ cmd_line = fuzz_target->get_init_cmdline(fuzz_target);
+ g_string_append_printf(cmd_line, " %s -qtest /dev/null ",
+ getenv("QTEST_LOG") ? "" : "-qtest-log none");
+
+ /* Split the runcmd into an argv and argc */
+ wordexp_t result;
+ wordexp(cmd_line->str, &result, 0);
+ g_string_free(cmd_line, true);
+
+ if (getenv("QTEST_LOG")) {
+ pretty_cmd_line = g_strjoinv(" ", result.we_wordv + 1);
+ printf("Starting %s with Arguments: %s\n",
+ result.we_wordv[0], pretty_cmd_line);
+ g_free(pretty_cmd_line);
+ }
+
+ qemu_init(result.we_wordc, result.we_wordv, NULL);
+
+ /* re-enable the rcu atfork, which was previously disabled in qemu_init */
+ rcu_enable_atfork();
+
+ /*
+ * Disable QEMU's signal handlers, since we manually control the main_loop,
+ * and don't check for main_loop_should_exit
+ */
+ signal(SIGINT, SIG_DFL);
+ signal(SIGHUP, SIG_DFL);
+ signal(SIGTERM, SIG_DFL);
+
+ return 0;
+}
diff --git a/tests/qtest/fuzz/fuzz.h b/tests/qtest/fuzz/fuzz.h
new file mode 100644
index 000000000..3a8570e84
--- /dev/null
+++ b/tests/qtest/fuzz/fuzz.h
@@ -0,0 +1,125 @@
+/*
+ * fuzzing driver
+ *
+ * Copyright Red Hat Inc., 2019
+ *
+ * Authors:
+ * Alexander Bulekov <alxndr@bu.edu>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ */
+
+#ifndef FUZZER_H_
+#define FUZZER_H_
+
+#include "qemu/units.h"
+#include "qapi/error.h"
+
+#include "tests/qtest/libqos/libqtest.h"
+
+/**
+ * A libfuzzer fuzzing target
+ *
+ * The QEMU fuzzing binary is built with all available targets, each
+ * with a unique @name that can be specified on the command-line to
+ * select which target should run.
+ *
+ * A target must implement ->fuzz() to process a random input. If QEMU
+ * crashes in ->fuzz() then libfuzzer will record a failure.
+ *
+ * Fuzzing targets are registered with fuzz_add_target():
+ *
+ * static const FuzzTarget fuzz_target = {
+ * .name = "my-device-fifo",
+ * .description = "Fuzz the FIFO buffer registers of my-device",
+ * ...
+ * };
+ *
+ * static void register_fuzz_target(void)
+ * {
+ * fuzz_add_target(&fuzz_target);
+ * }
+ * fuzz_target_init(register_fuzz_target);
+ */
+typedef struct FuzzTarget {
+ const char *name; /* target identifier (passed to --fuzz-target=)*/
+ const char *description; /* help text */
+
+
+ /*
+ * Returns the arguments that are passed to qemu/softmmu init(). Freed by
+ * the caller.
+ */
+ GString *(*get_init_cmdline)(struct FuzzTarget *);
+
+ /*
+ * will run once, prior to running qemu/softmmu init.
+ * eg: set up shared-memory for communication with the child-process
+ * Can be NULL
+ */
+ void(*pre_vm_init)(void);
+
+ /*
+ * will run once, after QEMU has been initialized, prior to the fuzz-loop.
+ * eg: detect the memory map
+ * Can be NULL
+ */
+ void(*pre_fuzz)(QTestState *);
+
+ /*
+ * accepts and executes an input from libfuzzer. this is repeatedly
+ * executed during the fuzzing loop. Its should handle setup, input
+ * execution and cleanup.
+ * Cannot be NULL
+ */
+ void(*fuzz)(QTestState *, const unsigned char *, size_t);
+
+ /*
+ * The fuzzer can specify a "Custom Crossover" function for combining two
+ * inputs from the corpus. This function is sometimes called by libfuzzer
+ * when mutating inputs.
+ *
+ * data1: location of first input
+ * size1: length of first input
+ * data1: location of second input
+ * size1: length of second input
+ * out: where to place the resulting, mutated input
+ * max_out_size: the maximum length of the input that can be placed in out
+ * seed: the seed that should be used to make mutations deterministic, when
+ * needed
+ *
+ * See libfuzzer's LLVMFuzzerCustomCrossOver API for more info.
+ *
+ * Can be NULL
+ */
+ size_t(*crossover)(const uint8_t *data1, size_t size1,
+ const uint8_t *data2, size_t size2,
+ uint8_t *out, size_t max_out_size,
+ unsigned int seed);
+
+ void *opaque;
+} FuzzTarget;
+
+void flush_events(QTestState *);
+void reboot(QTestState *);
+
+/* Use the QTest ASCII protocol or call address_space API directly?*/
+void fuzz_qtest_set_serialize(bool option);
+
+/*
+ * makes a copy of *target and adds it to the target-list.
+ * i.e. fine to set up target on the caller's stack
+ */
+void fuzz_add_target(const FuzzTarget *target);
+
+size_t LLVMFuzzerCustomCrossOver(const uint8_t *data1, size_t size1,
+ const uint8_t *data2, size_t size2,
+ uint8_t *out, size_t max_out_size,
+ unsigned int seed);
+int LLVMFuzzerTestOneInput(const unsigned char *Data, size_t Size);
+int LLVMFuzzerInitialize(int *argc, char ***argv, char ***envp);
+
+#endif
+
diff --git a/tests/qtest/fuzz/generic_fuzz.c b/tests/qtest/fuzz/generic_fuzz.c
new file mode 100644
index 000000000..dd7e25851
--- /dev/null
+++ b/tests/qtest/fuzz/generic_fuzz.c
@@ -0,0 +1,1043 @@
+/*
+ * Generic Virtual-Device Fuzzing Target
+ *
+ * Copyright Red Hat Inc., 2020
+ *
+ * Authors:
+ * Alexander Bulekov <alxndr@bu.edu>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#include "qemu/osdep.h"
+
+#include <wordexp.h>
+
+#include "hw/core/cpu.h"
+#include "tests/qtest/libqos/libqtest.h"
+#include "tests/qtest/libqos/pci-pc.h"
+#include "fuzz.h"
+#include "fork_fuzz.h"
+#include "string.h"
+#include "exec/memory.h"
+#include "exec/ramblock.h"
+#include "hw/qdev-core.h"
+#include "hw/pci/pci.h"
+#include "hw/boards.h"
+#include "generic_fuzz_configs.h"
+#include "hw/mem/sparse-mem.h"
+
+/*
+ * SEPARATOR is used to separate "operations" in the fuzz input
+ */
+#define SEPARATOR "FUZZ"
+
+enum cmds {
+ OP_IN,
+ OP_OUT,
+ OP_READ,
+ OP_WRITE,
+ OP_PCI_READ,
+ OP_PCI_WRITE,
+ OP_DISABLE_PCI,
+ OP_ADD_DMA_PATTERN,
+ OP_CLEAR_DMA_PATTERNS,
+ OP_CLOCK_STEP,
+};
+
+#define DEFAULT_TIMEOUT_US 100000
+#define USEC_IN_SEC 1000000000
+
+#define MAX_DMA_FILL_SIZE 0x10000
+
+#define PCI_HOST_BRIDGE_CFG 0xcf8
+#define PCI_HOST_BRIDGE_DATA 0xcfc
+
+typedef struct {
+ ram_addr_t addr;
+ ram_addr_t size; /* The number of bytes until the end of the I/O region */
+} address_range;
+
+static useconds_t timeout = DEFAULT_TIMEOUT_US;
+
+static bool qtest_log_enabled;
+
+MemoryRegion *sparse_mem_mr;
+
+/*
+ * A pattern used to populate a DMA region or perform a memwrite. This is
+ * useful for e.g. populating tables of unique addresses.
+ * Example {.index = 1; .stride = 2; .len = 3; .data = "\x00\x01\x02"}
+ * Renders as: 00 01 02 00 03 02 00 05 02 00 07 02 ...
+ */
+typedef struct {
+ uint8_t index; /* Index of a byte to increment by stride */
+ uint8_t stride; /* Increment each index'th byte by this amount */
+ size_t len;
+ const uint8_t *data;
+} pattern;
+
+/* Avoid filling the same DMA region between MMIO/PIO commands ? */
+static bool avoid_double_fetches;
+
+static QTestState *qts_global; /* Need a global for the DMA callback */
+
+/*
+ * List of memory regions that are children of QOM objects specified by the
+ * user for fuzzing.
+ */
+static GHashTable *fuzzable_memoryregions;
+static GPtrArray *fuzzable_pci_devices;
+
+struct get_io_cb_info {
+ int index;
+ int found;
+ address_range result;
+};
+
+static bool get_io_address_cb(Int128 start, Int128 size,
+ const MemoryRegion *mr,
+ hwaddr offset_in_region,
+ void *opaque)
+{
+ struct get_io_cb_info *info = opaque;
+ if (g_hash_table_lookup(fuzzable_memoryregions, mr)) {
+ if (info->index == 0) {
+ info->result.addr = (ram_addr_t)start;
+ info->result.size = (ram_addr_t)size;
+ info->found = 1;
+ return true;
+ }
+ info->index--;
+ }
+ return false;
+}
+
+/*
+ * List of dma regions populated since the last fuzzing command. Used to ensure
+ * that we only write to each DMA address once, to avoid race conditions when
+ * building reproducers.
+ */
+static GArray *dma_regions;
+
+static GArray *dma_patterns;
+static int dma_pattern_index;
+static bool pci_disabled;
+
+/*
+ * Allocate a block of memory and populate it with a pattern.
+ */
+static void *pattern_alloc(pattern p, size_t len)
+{
+ int i;
+ uint8_t *buf = g_malloc(len);
+ uint8_t sum = 0;
+
+ for (i = 0; i < len; ++i) {
+ buf[i] = p.data[i % p.len];
+ if ((i % p.len) == p.index) {
+ buf[i] += sum;
+ sum += p.stride;
+ }
+ }
+ return buf;
+}
+
+static int memory_access_size(MemoryRegion *mr, unsigned l, hwaddr addr)
+{
+ unsigned access_size_max = mr->ops->valid.max_access_size;
+
+ /*
+ * Regions are assumed to support 1-4 byte accesses unless
+ * otherwise specified.
+ */
+ if (access_size_max == 0) {
+ access_size_max = 4;
+ }
+
+ /* Bound the maximum access by the alignment of the address. */
+ if (!mr->ops->impl.unaligned) {
+ unsigned align_size_max = addr & -addr;
+ if (align_size_max != 0 && align_size_max < access_size_max) {
+ access_size_max = align_size_max;
+ }
+ }
+
+ /* Don't attempt accesses larger than the maximum. */
+ if (l > access_size_max) {
+ l = access_size_max;
+ }
+ l = pow2floor(l);
+
+ return l;
+}
+
+/*
+ * Call-back for functions that perform DMA reads from guest memory. Confirm
+ * that the region has not already been populated since the last loop in
+ * generic_fuzz(), avoiding potential race-conditions, which we don't have
+ * a good way for reproducing right now.
+ */
+void fuzz_dma_read_cb(size_t addr, size_t len, MemoryRegion *mr)
+{
+ /* Are we in the generic-fuzzer or are we using another fuzz-target? */
+ if (!qts_global) {
+ return;
+ }
+
+ /*
+ * Return immediately if:
+ * - We have no DMA patterns defined
+ * - The length of the DMA read request is zero
+ * - The DMA read is hitting an MR other than the machine's main RAM
+ * - The DMA request hits past the bounds of our RAM
+ */
+ if (dma_patterns->len == 0
+ || len == 0
+ || (mr != current_machine->ram && mr != sparse_mem_mr)) {
+ return;
+ }
+
+ /*
+ * If we overlap with any existing dma_regions, split the range and only
+ * populate the non-overlapping parts.
+ */
+ address_range region;
+ bool double_fetch = false;
+ for (int i = 0;
+ i < dma_regions->len && (avoid_double_fetches || qtest_log_enabled);
+ ++i) {
+ region = g_array_index(dma_regions, address_range, i);
+ if (addr < region.addr + region.size && addr + len > region.addr) {
+ double_fetch = true;
+ if (addr < region.addr
+ && avoid_double_fetches) {
+ fuzz_dma_read_cb(addr, region.addr - addr, mr);
+ }
+ if (addr + len > region.addr + region.size
+ && avoid_double_fetches) {
+ fuzz_dma_read_cb(region.addr + region.size,
+ addr + len - (region.addr + region.size), mr);
+ }
+ return;
+ }
+ }
+
+ /* Cap the length of the DMA access to something reasonable */
+ len = MIN(len, MAX_DMA_FILL_SIZE);
+
+ address_range ar = {addr, len};
+ g_array_append_val(dma_regions, ar);
+ pattern p = g_array_index(dma_patterns, pattern, dma_pattern_index);
+ void *buf_base = pattern_alloc(p, ar.size);
+ void *buf = buf_base;
+ hwaddr l, addr1;
+ MemoryRegion *mr1;
+ while (len > 0) {
+ l = len;
+ mr1 = address_space_translate(first_cpu->as,
+ addr, &addr1, &l, true,
+ MEMTXATTRS_UNSPECIFIED);
+
+ /*
+ * If mr1 isn't RAM, address_space_translate doesn't update l. Use
+ * memory_access_size to identify the number of bytes that it is safe
+ * to write without accidentally writing to another MemoryRegion.
+ */
+ if (!memory_region_is_ram(mr1)) {
+ l = memory_access_size(mr1, l, addr1);
+ }
+ if (memory_region_is_ram(mr1) ||
+ memory_region_is_romd(mr1) ||
+ mr1 == sparse_mem_mr) {
+ /* ROM/RAM case */
+ if (qtest_log_enabled) {
+ /*
+ * With QTEST_LOG, use a normal, slow QTest memwrite. Prefix the log
+ * that will be written by qtest.c with a DMA tag, so we can reorder
+ * the resulting QTest trace so the DMA fills precede the last PIO/MMIO
+ * command.
+ */
+ fprintf(stderr, "[DMA] ");
+ if (double_fetch) {
+ fprintf(stderr, "[DOUBLE-FETCH] ");
+ }
+ fflush(stderr);
+ }
+ qtest_memwrite(qts_global, addr, buf, l);
+ }
+ len -= l;
+ buf += l;
+ addr += l;
+
+ }
+ g_free(buf_base);
+
+ /* Increment the index of the pattern for the next DMA access */
+ dma_pattern_index = (dma_pattern_index + 1) % dma_patterns->len;
+}
+
+/*
+ * Here we want to convert a fuzzer-provided [io-region-index, offset] to
+ * a physical address. To do this, we iterate over all of the matched
+ * MemoryRegions. Check whether each region exists within the particular io
+ * space. Return the absolute address of the offset within the index'th region
+ * that is a subregion of the io_space and the distance until the end of the
+ * memory region.
+ */
+static bool get_io_address(address_range *result, AddressSpace *as,
+ uint8_t index,
+ uint32_t offset) {
+ FlatView *view;
+ view = as->current_map;
+ g_assert(view);
+ struct get_io_cb_info cb_info = {};
+
+ cb_info.index = index;
+
+ /*
+ * Loop around the FlatView until we match "index" number of
+ * fuzzable_memoryregions, or until we know that there are no matching
+ * memory_regions.
+ */
+ do {
+ flatview_for_each_range(view, get_io_address_cb , &cb_info);
+ } while (cb_info.index != index && !cb_info.found);
+
+ *result = cb_info.result;
+ if (result->size) {
+ offset = offset % result->size;
+ result->addr += offset;
+ result->size -= offset;
+ }
+ return cb_info.found;
+}
+
+static bool get_pio_address(address_range *result,
+ uint8_t index, uint16_t offset)
+{
+ /*
+ * PIO BARs can be set past the maximum port address (0xFFFF). Thus, result
+ * can contain an addr that extends past the PIO space. When we pass this
+ * address to qtest_in/qtest_out, it is cast to a uint16_t, so we might end
+ * up fuzzing a completely different MemoryRegion/Device. Therefore, check
+ * that the address here is within the PIO space limits.
+ */
+ bool found = get_io_address(result, &address_space_io, index, offset);
+ return result->addr <= 0xFFFF ? found : false;
+}
+
+static bool get_mmio_address(address_range *result,
+ uint8_t index, uint32_t offset)
+{
+ return get_io_address(result, &address_space_memory, index, offset);
+}
+
+static void op_in(QTestState *s, const unsigned char * data, size_t len)
+{
+ enum Sizes {Byte, Word, Long, end_sizes};
+ struct {
+ uint8_t size;
+ uint8_t base;
+ uint16_t offset;
+ } a;
+ address_range abs;
+
+ if (len < sizeof(a)) {
+ return;
+ }
+ memcpy(&a, data, sizeof(a));
+ if (get_pio_address(&abs, a.base, a.offset) == 0) {
+ return;
+ }
+
+ switch (a.size %= end_sizes) {
+ case Byte:
+ qtest_inb(s, abs.addr);
+ break;
+ case Word:
+ if (abs.size >= 2) {
+ qtest_inw(s, abs.addr);
+ }
+ break;
+ case Long:
+ if (abs.size >= 4) {
+ qtest_inl(s, abs.addr);
+ }
+ break;
+ }
+}
+
+static void op_out(QTestState *s, const unsigned char * data, size_t len)
+{
+ enum Sizes {Byte, Word, Long, end_sizes};
+ struct {
+ uint8_t size;
+ uint8_t base;
+ uint16_t offset;
+ uint32_t value;
+ } a;
+ address_range abs;
+
+ if (len < sizeof(a)) {
+ return;
+ }
+ memcpy(&a, data, sizeof(a));
+
+ if (get_pio_address(&abs, a.base, a.offset) == 0) {
+ return;
+ }
+
+ switch (a.size %= end_sizes) {
+ case Byte:
+ qtest_outb(s, abs.addr, a.value & 0xFF);
+ break;
+ case Word:
+ if (abs.size >= 2) {
+ qtest_outw(s, abs.addr, a.value & 0xFFFF);
+ }
+ break;
+ case Long:
+ if (abs.size >= 4) {
+ qtest_outl(s, abs.addr, a.value);
+ }
+ break;
+ }
+}
+
+static void op_read(QTestState *s, const unsigned char * data, size_t len)
+{
+ enum Sizes {Byte, Word, Long, Quad, end_sizes};
+ struct {
+ uint8_t size;
+ uint8_t base;
+ uint32_t offset;
+ } a;
+ address_range abs;
+
+ if (len < sizeof(a)) {
+ return;
+ }
+ memcpy(&a, data, sizeof(a));
+
+ if (get_mmio_address(&abs, a.base, a.offset) == 0) {
+ return;
+ }
+
+ switch (a.size %= end_sizes) {
+ case Byte:
+ qtest_readb(s, abs.addr);
+ break;
+ case Word:
+ if (abs.size >= 2) {
+ qtest_readw(s, abs.addr);
+ }
+ break;
+ case Long:
+ if (abs.size >= 4) {
+ qtest_readl(s, abs.addr);
+ }
+ break;
+ case Quad:
+ if (abs.size >= 8) {
+ qtest_readq(s, abs.addr);
+ }
+ break;
+ }
+}
+
+static void op_write(QTestState *s, const unsigned char * data, size_t len)
+{
+ enum Sizes {Byte, Word, Long, Quad, end_sizes};
+ struct {
+ uint8_t size;
+ uint8_t base;
+ uint32_t offset;
+ uint64_t value;
+ } a;
+ address_range abs;
+
+ if (len < sizeof(a)) {
+ return;
+ }
+ memcpy(&a, data, sizeof(a));
+
+ if (get_mmio_address(&abs, a.base, a.offset) == 0) {
+ return;
+ }
+
+ switch (a.size %= end_sizes) {
+ case Byte:
+ qtest_writeb(s, abs.addr, a.value & 0xFF);
+ break;
+ case Word:
+ if (abs.size >= 2) {
+ qtest_writew(s, abs.addr, a.value & 0xFFFF);
+ }
+ break;
+ case Long:
+ if (abs.size >= 4) {
+ qtest_writel(s, abs.addr, a.value & 0xFFFFFFFF);
+ }
+ break;
+ case Quad:
+ if (abs.size >= 8) {
+ qtest_writeq(s, abs.addr, a.value);
+ }
+ break;
+ }
+}
+
+static void op_pci_read(QTestState *s, const unsigned char * data, size_t len)
+{
+ enum Sizes {Byte, Word, Long, end_sizes};
+ struct {
+ uint8_t size;
+ uint8_t base;
+ uint8_t offset;
+ } a;
+ if (len < sizeof(a) || fuzzable_pci_devices->len == 0 || pci_disabled) {
+ return;
+ }
+ memcpy(&a, data, sizeof(a));
+ PCIDevice *dev = g_ptr_array_index(fuzzable_pci_devices,
+ a.base % fuzzable_pci_devices->len);
+ int devfn = dev->devfn;
+ qtest_outl(s, PCI_HOST_BRIDGE_CFG, (1U << 31) | (devfn << 8) | a.offset);
+ switch (a.size %= end_sizes) {
+ case Byte:
+ qtest_inb(s, PCI_HOST_BRIDGE_DATA);
+ break;
+ case Word:
+ qtest_inw(s, PCI_HOST_BRIDGE_DATA);
+ break;
+ case Long:
+ qtest_inl(s, PCI_HOST_BRIDGE_DATA);
+ break;
+ }
+}
+
+static void op_pci_write(QTestState *s, const unsigned char * data, size_t len)
+{
+ enum Sizes {Byte, Word, Long, end_sizes};
+ struct {
+ uint8_t size;
+ uint8_t base;
+ uint8_t offset;
+ uint32_t value;
+ } a;
+ if (len < sizeof(a) || fuzzable_pci_devices->len == 0 || pci_disabled) {
+ return;
+ }
+ memcpy(&a, data, sizeof(a));
+ PCIDevice *dev = g_ptr_array_index(fuzzable_pci_devices,
+ a.base % fuzzable_pci_devices->len);
+ int devfn = dev->devfn;
+ qtest_outl(s, PCI_HOST_BRIDGE_CFG, (1U << 31) | (devfn << 8) | a.offset);
+ switch (a.size %= end_sizes) {
+ case Byte:
+ qtest_outb(s, PCI_HOST_BRIDGE_DATA, a.value & 0xFF);
+ break;
+ case Word:
+ qtest_outw(s, PCI_HOST_BRIDGE_DATA, a.value & 0xFFFF);
+ break;
+ case Long:
+ qtest_outl(s, PCI_HOST_BRIDGE_DATA, a.value & 0xFFFFFFFF);
+ break;
+ }
+}
+
+static void op_add_dma_pattern(QTestState *s,
+ const unsigned char *data, size_t len)
+{
+ struct {
+ /*
+ * index and stride can be used to increment the index-th byte of the
+ * pattern by the value stride, for each loop of the pattern.
+ */
+ uint8_t index;
+ uint8_t stride;
+ } a;
+
+ if (len < sizeof(a) + 1) {
+ return;
+ }
+ memcpy(&a, data, sizeof(a));
+ pattern p = {a.index, a.stride, len - sizeof(a), data + sizeof(a)};
+ p.index = a.index % p.len;
+ g_array_append_val(dma_patterns, p);
+ return;
+}
+
+static void op_clear_dma_patterns(QTestState *s,
+ const unsigned char *data, size_t len)
+{
+ g_array_set_size(dma_patterns, 0);
+ dma_pattern_index = 0;
+}
+
+static void op_clock_step(QTestState *s, const unsigned char *data, size_t len)
+{
+ qtest_clock_step_next(s);
+}
+
+static void op_disable_pci(QTestState *s, const unsigned char *data, size_t len)
+{
+ pci_disabled = true;
+}
+
+static void handle_timeout(int sig)
+{
+ if (qtest_log_enabled) {
+ fprintf(stderr, "[Timeout]\n");
+ fflush(stderr);
+ }
+
+ /*
+ * If there is a crash, libfuzzer/ASAN forks a child to run an
+ * "llvm-symbolizer" process for printing out a pretty stacktrace. It
+ * communicates with this child using a pipe. If we timeout+Exit, while
+ * libfuzzer is still communicating with the llvm-symbolizer child, we will
+ * be left with an orphan llvm-symbolizer process. Sometimes, this appears
+ * to lead to a deadlock in the forkserver. Use waitpid to check if there
+ * are any waitable children. If so, exit out of the signal-handler, and
+ * let libfuzzer finish communicating with the child, and exit, on its own.
+ */
+ if (waitpid(-1, NULL, WNOHANG) == 0) {
+ return;
+ }
+
+ _Exit(0);
+}
+
+/*
+ * Here, we interpret random bytes from the fuzzer, as a sequence of commands.
+ * Some commands can be variable-width, so we use a separator, SEPARATOR, to
+ * specify the boundaries between commands. SEPARATOR is used to separate
+ * "operations" in the fuzz input. Why use a separator, instead of just using
+ * the operations' length to identify operation boundaries?
+ * 1. This is a simple way to support variable-length operations
+ * 2. This adds "stability" to the input.
+ * For example take the input "AbBcgDefg", where there is no separator and
+ * Opcodes are capitalized.
+ * Simply, by removing the first byte, we end up with a very different
+ * sequence:
+ * BbcGdefg...
+ * By adding a separator, we avoid this problem:
+ * Ab SEP Bcg SEP Defg -> B SEP Bcg SEP Defg
+ * Since B uses two additional bytes as operands, the first "B" will be
+ * ignored. The fuzzer actively tries to reduce inputs, so such unused
+ * bytes are likely to be pruned, eventually.
+ *
+ * SEPARATOR is trivial for the fuzzer to discover when using ASan. Optionally,
+ * SEPARATOR can be manually specified as a dictionary value (see libfuzzer's
+ * -dict), though this should not be necessary.
+ *
+ * As a result, the stream of bytes is converted into a sequence of commands.
+ * In a simplified example where SEPARATOR is 0xFF:
+ * 00 01 02 FF 03 04 05 06 FF 01 FF ...
+ * becomes this sequence of commands:
+ * 00 01 02 -> op00 (0102) -> in (0102, 2)
+ * 03 04 05 06 -> op03 (040506) -> write (040506, 3)
+ * 01 -> op01 (-,0) -> out (-,0)
+ * ...
+ *
+ * Note here that it is the job of the individual opcode functions to check
+ * that enough data was provided. I.e. in the last command out (,0), out needs
+ * to check that there is not enough data provided to select an address/value
+ * for the operation.
+ */
+static void generic_fuzz(QTestState *s, const unsigned char *Data, size_t Size)
+{
+ void (*ops[]) (QTestState *s, const unsigned char* , size_t) = {
+ [OP_IN] = op_in,
+ [OP_OUT] = op_out,
+ [OP_READ] = op_read,
+ [OP_WRITE] = op_write,
+ [OP_PCI_READ] = op_pci_read,
+ [OP_PCI_WRITE] = op_pci_write,
+ [OP_DISABLE_PCI] = op_disable_pci,
+ [OP_ADD_DMA_PATTERN] = op_add_dma_pattern,
+ [OP_CLEAR_DMA_PATTERNS] = op_clear_dma_patterns,
+ [OP_CLOCK_STEP] = op_clock_step,
+ };
+ const unsigned char *cmd = Data;
+ const unsigned char *nextcmd;
+ size_t cmd_len;
+ uint8_t op;
+
+ if (fork() == 0) {
+ struct sigaction sact;
+ struct itimerval timer;
+ sigset_t set;
+ /*
+ * Sometimes the fuzzer will find inputs that take quite a long time to
+ * process. Often times, these inputs do not result in new coverage.
+ * Even if these inputs might be interesting, they can slow down the
+ * fuzzer, overall. Set a timeout for each command to avoid hurting
+ * performance, too much
+ */
+ if (timeout) {
+
+ sigemptyset(&sact.sa_mask);
+ sact.sa_flags = SA_NODEFER;
+ sact.sa_handler = handle_timeout;
+ sigaction(SIGALRM, &sact, NULL);
+
+ sigemptyset(&set);
+ sigaddset(&set, SIGALRM);
+ pthread_sigmask(SIG_UNBLOCK, &set, NULL);
+
+ memset(&timer, 0, sizeof(timer));
+ timer.it_value.tv_sec = timeout / USEC_IN_SEC;
+ timer.it_value.tv_usec = timeout % USEC_IN_SEC;
+ }
+
+ op_clear_dma_patterns(s, NULL, 0);
+ pci_disabled = false;
+
+ while (cmd && Size) {
+ /* Reset the timeout, each time we run a new command */
+ if (timeout) {
+ setitimer(ITIMER_REAL, &timer, NULL);
+ }
+
+ /* Get the length until the next command or end of input */
+ nextcmd = memmem(cmd, Size, SEPARATOR, strlen(SEPARATOR));
+ cmd_len = nextcmd ? nextcmd - cmd : Size;
+
+ if (cmd_len > 0) {
+ /* Interpret the first byte of the command as an opcode */
+ op = *cmd % (sizeof(ops) / sizeof((ops)[0]));
+ ops[op](s, cmd + 1, cmd_len - 1);
+
+ /* Run the main loop */
+ flush_events(s);
+ }
+ /* Advance to the next command */
+ cmd = nextcmd ? nextcmd + sizeof(SEPARATOR) - 1 : nextcmd;
+ Size = Size - (cmd_len + sizeof(SEPARATOR) - 1);
+ g_array_set_size(dma_regions, 0);
+ }
+ _Exit(0);
+ } else {
+ flush_events(s);
+ wait(0);
+ }
+}
+
+static void usage(void)
+{
+ printf("Please specify the following environment variables:\n");
+ printf("QEMU_FUZZ_ARGS= the command line arguments passed to qemu\n");
+ printf("QEMU_FUZZ_OBJECTS= "
+ "a space separated list of QOM type names for objects to fuzz\n");
+ printf("Optionally: QEMU_AVOID_DOUBLE_FETCH= "
+ "Try to avoid racy DMA double fetch bugs? %d by default\n",
+ avoid_double_fetches);
+ printf("Optionally: QEMU_FUZZ_TIMEOUT= Specify a custom timeout (us). "
+ "0 to disable. %d by default\n", timeout);
+ exit(0);
+}
+
+static int locate_fuzz_memory_regions(Object *child, void *opaque)
+{
+ const char *name;
+ MemoryRegion *mr;
+ if (object_dynamic_cast(child, TYPE_MEMORY_REGION)) {
+ mr = MEMORY_REGION(child);
+ if ((memory_region_is_ram(mr) ||
+ memory_region_is_ram_device(mr) ||
+ memory_region_is_rom(mr)) == false) {
+ name = object_get_canonical_path_component(child);
+ /*
+ * We don't want duplicate pointers to the same MemoryRegion, so
+ * try to remove copies of the pointer, before adding it.
+ */
+ g_hash_table_insert(fuzzable_memoryregions, mr, (gpointer)true);
+ }
+ }
+ return 0;
+}
+
+static int locate_fuzz_objects(Object *child, void *opaque)
+{
+ GString *type_name;
+ GString *path_name;
+ char *pattern = opaque;
+
+ type_name = g_string_new(object_get_typename(child));
+ g_string_ascii_down(type_name);
+ if (g_pattern_match_simple(pattern, type_name->str)) {
+ /* Find and save ptrs to any child MemoryRegions */
+ object_child_foreach_recursive(child, locate_fuzz_memory_regions, NULL);
+
+ /*
+ * We matched an object. If its a PCI device, store a pointer to it so
+ * we can map BARs and fuzz its config space.
+ */
+ if (object_dynamic_cast(OBJECT(child), TYPE_PCI_DEVICE)) {
+ /*
+ * Don't want duplicate pointers to the same PCIDevice, so remove
+ * copies of the pointer, before adding it.
+ */
+ g_ptr_array_remove_fast(fuzzable_pci_devices, PCI_DEVICE(child));
+ g_ptr_array_add(fuzzable_pci_devices, PCI_DEVICE(child));
+ }
+ } else if (object_dynamic_cast(OBJECT(child), TYPE_MEMORY_REGION)) {
+ path_name = g_string_new(object_get_canonical_path_component(child));
+ g_string_ascii_down(path_name);
+ if (g_pattern_match_simple(pattern, path_name->str)) {
+ MemoryRegion *mr;
+ mr = MEMORY_REGION(child);
+ if ((memory_region_is_ram(mr) ||
+ memory_region_is_ram_device(mr) ||
+ memory_region_is_rom(mr)) == false) {
+ g_hash_table_insert(fuzzable_memoryregions, mr, (gpointer)true);
+ }
+ }
+ g_string_free(path_name, true);
+ }
+ g_string_free(type_name, true);
+ return 0;
+}
+
+
+static void pci_enum(gpointer pcidev, gpointer bus)
+{
+ PCIDevice *dev = pcidev;
+ QPCIDevice *qdev;
+ int i;
+
+ qdev = qpci_device_find(bus, dev->devfn);
+ g_assert(qdev != NULL);
+ for (i = 0; i < 6; i++) {
+ if (dev->io_regions[i].size) {
+ qpci_iomap(qdev, i, NULL);
+ }
+ }
+ qpci_device_enable(qdev);
+ g_free(qdev);
+}
+
+static void generic_pre_fuzz(QTestState *s)
+{
+ GHashTableIter iter;
+ MemoryRegion *mr;
+ QPCIBus *pcibus;
+ char **result;
+ GString *name_pattern;
+
+ if (!getenv("QEMU_FUZZ_OBJECTS")) {
+ usage();
+ }
+ if (getenv("QTEST_LOG")) {
+ qtest_log_enabled = 1;
+ }
+ if (getenv("QEMU_AVOID_DOUBLE_FETCH")) {
+ avoid_double_fetches = 1;
+ }
+ if (getenv("QEMU_FUZZ_TIMEOUT")) {
+ timeout = g_ascii_strtoll(getenv("QEMU_FUZZ_TIMEOUT"), NULL, 0);
+ }
+ qts_global = s;
+
+ /*
+ * Create a special device that we can use to back DMA buffers at very
+ * high memory addresses
+ */
+ sparse_mem_mr = sparse_mem_init(0, UINT64_MAX);
+
+ dma_regions = g_array_new(false, false, sizeof(address_range));
+ dma_patterns = g_array_new(false, false, sizeof(pattern));
+
+ fuzzable_memoryregions = g_hash_table_new(NULL, NULL);
+ fuzzable_pci_devices = g_ptr_array_new();
+
+ result = g_strsplit(getenv("QEMU_FUZZ_OBJECTS"), " ", -1);
+ for (int i = 0; result[i] != NULL; i++) {
+ name_pattern = g_string_new(result[i]);
+ /*
+ * Make the pattern lowercase. We do the same for all the MemoryRegion
+ * and Type names so the configs are case-insensitive.
+ */
+ g_string_ascii_down(name_pattern);
+ printf("Matching objects by name %s\n", result[i]);
+ object_child_foreach_recursive(qdev_get_machine(),
+ locate_fuzz_objects,
+ name_pattern->str);
+ g_string_free(name_pattern, true);
+ }
+ g_strfreev(result);
+ printf("This process will try to fuzz the following MemoryRegions:\n");
+
+ g_hash_table_iter_init(&iter, fuzzable_memoryregions);
+ while (g_hash_table_iter_next(&iter, (gpointer)&mr, NULL)) {
+ printf(" * %s (size 0x%" PRIx64 ")\n",
+ object_get_canonical_path_component(&(mr->parent_obj)),
+ memory_region_size(mr));
+ }
+
+ if (!g_hash_table_size(fuzzable_memoryregions)) {
+ printf("No fuzzable memory regions found...\n");
+ exit(1);
+ }
+
+ pcibus = qpci_new_pc(s, NULL);
+ g_ptr_array_foreach(fuzzable_pci_devices, pci_enum, pcibus);
+ qpci_free_pc(pcibus);
+
+ counter_shm_init();
+}
+
+/*
+ * When libfuzzer gives us two inputs to combine, return a new input with the
+ * following structure:
+ *
+ * Input 1 (data1)
+ * SEPARATOR
+ * Clear out the DMA Patterns
+ * SEPARATOR
+ * Disable the pci_read/write instructions
+ * SEPARATOR
+ * Input 2 (data2)
+ *
+ * The idea is to collate the core behaviors of the two inputs.
+ * For example:
+ * Input 1: maps a device's BARs, sets up three DMA patterns, and triggers
+ * device functionality A
+ * Input 2: maps a device's BARs, sets up one DMA pattern, and triggers device
+ * functionality B
+ *
+ * This function attempts to produce an input that:
+ * Ouptut: maps a device's BARs, set up three DMA patterns, triggers
+ * functionality A device, replaces the DMA patterns with a single
+ * patten, and triggers device functionality B.
+ */
+static size_t generic_fuzz_crossover(const uint8_t *data1, size_t size1, const
+ uint8_t *data2, size_t size2, uint8_t *out,
+ size_t max_out_size, unsigned int seed)
+{
+ size_t copy_len = 0, size = 0;
+
+ /* Check that we have enough space for data1 and at least part of data2 */
+ if (max_out_size <= size1 + strlen(SEPARATOR) * 3 + 2) {
+ return 0;
+ }
+
+ /* Copy_Len in the first input */
+ copy_len = size1;
+ memcpy(out + size, data1, copy_len);
+ size += copy_len;
+ max_out_size -= copy_len;
+
+ /* Append a separator */
+ copy_len = strlen(SEPARATOR);
+ memcpy(out + size, SEPARATOR, copy_len);
+ size += copy_len;
+ max_out_size -= copy_len;
+
+ /* Clear out the DMA Patterns */
+ copy_len = 1;
+ if (copy_len) {
+ out[size] = OP_CLEAR_DMA_PATTERNS;
+ }
+ size += copy_len;
+ max_out_size -= copy_len;
+
+ /* Append a separator */
+ copy_len = strlen(SEPARATOR);
+ memcpy(out + size, SEPARATOR, copy_len);
+ size += copy_len;
+ max_out_size -= copy_len;
+
+ /* Disable PCI ops. Assume data1 took care of setting up PCI */
+ copy_len = 1;
+ if (copy_len) {
+ out[size] = OP_DISABLE_PCI;
+ }
+ size += copy_len;
+ max_out_size -= copy_len;
+
+ /* Append a separator */
+ copy_len = strlen(SEPARATOR);
+ memcpy(out + size, SEPARATOR, copy_len);
+ size += copy_len;
+ max_out_size -= copy_len;
+
+ /* Copy_Len over the second input */
+ copy_len = MIN(size2, max_out_size);
+ memcpy(out + size, data2, copy_len);
+ size += copy_len;
+ max_out_size -= copy_len;
+
+ return size;
+}
+
+
+static GString *generic_fuzz_cmdline(FuzzTarget *t)
+{
+ GString *cmd_line = g_string_new(TARGET_NAME);
+ if (!getenv("QEMU_FUZZ_ARGS")) {
+ usage();
+ }
+ g_string_append_printf(cmd_line, " -display none \
+ -machine accel=qtest, \
+ -m 512M %s ", getenv("QEMU_FUZZ_ARGS"));
+ return cmd_line;
+}
+
+static GString *generic_fuzz_predefined_config_cmdline(FuzzTarget *t)
+{
+ gchar *args;
+ const generic_fuzz_config *config;
+ g_assert(t->opaque);
+
+ config = t->opaque;
+ setenv("QEMU_AVOID_DOUBLE_FETCH", "1", 1);
+ if (config->argfunc) {
+ args = config->argfunc();
+ setenv("QEMU_FUZZ_ARGS", args, 1);
+ g_free(args);
+ } else {
+ g_assert_nonnull(config->args);
+ setenv("QEMU_FUZZ_ARGS", config->args, 1);
+ }
+ setenv("QEMU_FUZZ_OBJECTS", config->objects, 1);
+ return generic_fuzz_cmdline(t);
+}
+
+static void register_generic_fuzz_targets(void)
+{
+ fuzz_add_target(&(FuzzTarget){
+ .name = "generic-fuzz",
+ .description = "Fuzz based on any qemu command-line args. ",
+ .get_init_cmdline = generic_fuzz_cmdline,
+ .pre_fuzz = generic_pre_fuzz,
+ .fuzz = generic_fuzz,
+ .crossover = generic_fuzz_crossover
+ });
+
+ GString *name;
+ const generic_fuzz_config *config;
+
+ for (int i = 0;
+ i < sizeof(predefined_configs) / sizeof(generic_fuzz_config);
+ i++) {
+ config = predefined_configs + i;
+ name = g_string_new("generic-fuzz");
+ g_string_append_printf(name, "-%s", config->name);
+ fuzz_add_target(&(FuzzTarget){
+ .name = name->str,
+ .description = "Predefined generic-fuzz config.",
+ .get_init_cmdline = generic_fuzz_predefined_config_cmdline,
+ .pre_fuzz = generic_pre_fuzz,
+ .fuzz = generic_fuzz,
+ .crossover = generic_fuzz_crossover,
+ .opaque = (void *)config
+ });
+ }
+}
+
+fuzz_target_init(register_generic_fuzz_targets);
diff --git a/tests/qtest/fuzz/generic_fuzz_configs.h b/tests/qtest/fuzz/generic_fuzz_configs.h
new file mode 100644
index 000000000..004c70191
--- /dev/null
+++ b/tests/qtest/fuzz/generic_fuzz_configs.h
@@ -0,0 +1,245 @@
+/*
+ * Generic Virtual-Device Fuzzing Target Configs
+ *
+ * Copyright Red Hat Inc., 2020
+ *
+ * Authors:
+ * Alexander Bulekov <alxndr@bu.edu>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#ifndef GENERIC_FUZZ_CONFIGS_H
+#define GENERIC_FUZZ_CONFIGS_H
+
+
+typedef struct generic_fuzz_config {
+ const char *name, *args, *objects;
+ gchar* (*argfunc)(void); /* Result must be freeable by g_free() */
+} generic_fuzz_config;
+
+static inline gchar *generic_fuzzer_virtio_9p_args(void){
+ char tmpdir[] = "/tmp/qemu-fuzz.XXXXXX";
+ g_assert_nonnull(mkdtemp(tmpdir));
+
+ return g_strdup_printf("-machine q35 -nodefaults "
+ "-device virtio-9p,fsdev=hshare,mount_tag=hshare "
+ "-fsdev local,id=hshare,path=%s,security_model=mapped-xattr,"
+ "writeout=immediate,fmode=0600,dmode=0700", tmpdir);
+}
+
+const generic_fuzz_config predefined_configs[] = {
+ {
+ .name = "virtio-net-pci-slirp",
+ .args = "-M q35 -nodefaults "
+ "-device virtio-net,netdev=net0 -netdev user,id=net0",
+ .objects = "virtio*",
+ },{
+ .name = "virtio-blk",
+ .args = "-machine q35 -device virtio-blk,drive=disk0 "
+ "-drive file=null-co://,id=disk0,if=none,format=raw",
+ .objects = "virtio*",
+ },{
+ .name = "virtio-scsi",
+ .args = "-machine q35 -device virtio-scsi,num_queues=8 "
+ "-device scsi-hd,drive=disk0 "
+ "-drive file=null-co://,id=disk0,if=none,format=raw",
+ .objects = "scsi* virtio*",
+ },{
+ .name = "virtio-gpu",
+ .args = "-machine q35 -nodefaults -device virtio-gpu",
+ .objects = "virtio*",
+ },{
+ .name = "virtio-vga",
+ .args = "-machine q35 -nodefaults -device virtio-vga",
+ .objects = "virtio*",
+ },{
+ .name = "virtio-rng",
+ .args = "-machine q35 -nodefaults -device virtio-rng",
+ .objects = "virtio*",
+ },{
+ .name = "virtio-balloon",
+ .args = "-machine q35 -nodefaults -device virtio-balloon",
+ .objects = "virtio*",
+ },{
+ .name = "virtio-serial",
+ .args = "-machine q35 -nodefaults -device virtio-serial",
+ .objects = "virtio*",
+ },{
+ .name = "virtio-mouse",
+ .args = "-machine q35 -nodefaults -device virtio-mouse",
+ .objects = "virtio*",
+ },{
+ .name = "virtio-9p",
+ .argfunc = generic_fuzzer_virtio_9p_args,
+ .objects = "virtio*",
+ },{
+ .name = "virtio-9p-synth",
+ .args = "-machine q35 -nodefaults "
+ "-device virtio-9p,fsdev=hshare,mount_tag=hshare "
+ "-fsdev synth,id=hshare",
+ .objects = "virtio*",
+ },{
+ .name = "e1000",
+ .args = "-M q35 -nodefaults "
+ "-device e1000,netdev=net0 -netdev user,id=net0",
+ .objects = "e1000",
+ },{
+ .name = "e1000e",
+ .args = "-M q35 -nodefaults "
+ "-device e1000e,netdev=net0 -netdev user,id=net0",
+ .objects = "e1000e",
+ },{
+ .name = "cirrus-vga",
+ .args = "-machine q35 -nodefaults -device cirrus-vga",
+ .objects = "cirrus*",
+ },{
+ .name = "bochs-display",
+ .args = "-machine q35 -nodefaults -device bochs-display",
+ .objects = "bochs*",
+ },{
+ .name = "intel-hda",
+ .args = "-machine q35 -nodefaults -device intel-hda,id=hda0 "
+ "-device hda-output,bus=hda0.0 -device hda-micro,bus=hda0.0 "
+ "-device hda-duplex,bus=hda0.0",
+ .objects = "intel-hda",
+ },{
+ .name = "ide-hd",
+ .args = "-machine pc -nodefaults "
+ "-drive file=null-co://,if=none,format=raw,id=disk0 "
+ "-device ide-hd,drive=disk0",
+ .objects = "*ide*",
+ },{
+ .name = "ide-atapi",
+ .args = "-machine pc -nodefaults "
+ "-drive file=null-co://,if=none,format=raw,id=disk0 "
+ "-device ide-cd,drive=disk0",
+ .objects = "*ide*",
+ },{
+ .name = "ahci-hd",
+ .args = "-machine q35 -nodefaults "
+ "-drive file=null-co://,if=none,format=raw,id=disk0 "
+ "-device ide-hd,drive=disk0",
+ .objects = "*ahci*",
+ },{
+ .name = "ahci-atapi",
+ .args = "-machine q35 -nodefaults "
+ "-drive file=null-co://,if=none,format=raw,id=disk0 "
+ "-device ide-cd,drive=disk0",
+ .objects = "*ahci*",
+ },{
+ .name = "floppy",
+ .args = "-machine pc -nodefaults -device floppy,id=floppy0 "
+ "-drive id=disk0,file=null-co://,file.read-zeroes=on,if=none,format=raw "
+ "-device floppy,drive=disk0,drive-type=288",
+ .objects = "fd* floppy* i8257",
+ },{
+ .name = "xhci",
+ .args = "-machine q35 -nodefaults "
+ "-drive file=null-co://,if=none,format=raw,id=disk0 "
+ "-device qemu-xhci,id=xhci -device usb-tablet,bus=xhci.0 "
+ "-device usb-bot -device usb-storage,drive=disk0 "
+ "-chardev null,id=cd0 -chardev null,id=cd1 "
+ "-device usb-braille,chardev=cd0 -device usb-ccid -device usb-ccid "
+ "-device usb-kbd -device usb-mouse -device usb-serial,chardev=cd1 "
+ "-device usb-tablet -device usb-wacom-tablet -device usb-audio",
+ .objects = "*usb* *uhci* *xhci*",
+ },{
+ .name = "pc-i440fx",
+ .args = "-machine pc",
+ .objects = "*",
+ },{
+ .name = "pc-q35",
+ .args = "-machine q35",
+ .objects = "*",
+ },{
+ .name = "vmxnet3",
+ .args = "-machine q35 -nodefaults "
+ "-device vmxnet3,netdev=net0 -netdev user,id=net0",
+ .objects = "vmxnet3"
+ },{
+ .name = "ne2k_pci",
+ .args = "-machine q35 -nodefaults "
+ "-device ne2k_pci,netdev=net0 -netdev user,id=net0",
+ .objects = "ne2k*"
+ },{
+ .name = "pcnet",
+ .args = "-machine q35 -nodefaults "
+ "-device pcnet,netdev=net0 -netdev user,id=net0",
+ .objects = "pcnet"
+ },{
+ .name = "rtl8139",
+ .args = "-machine q35 -nodefaults "
+ "-device rtl8139,netdev=net0 -netdev user,id=net0",
+ .objects = "rtl8139"
+ },{
+ .name = "i82550",
+ .args = "-machine q35 -nodefaults "
+ "-device i82550,netdev=net0 -netdev user,id=net0",
+ .objects = "i8255*"
+ },{
+ .name = "sdhci-v3",
+ .args = "-nodefaults -device sdhci-pci,sd-spec-version=3 "
+ "-device sd-card,drive=mydrive "
+ "-drive if=none,index=0,file=null-co://,format=raw,id=mydrive -nographic",
+ .objects = "sd*"
+ },{
+ .name = "ehci",
+ .args = "-machine q35 -nodefaults "
+ "-device ich9-usb-ehci1,bus=pcie.0,addr=1d.7,"
+ "multifunction=on,id=ich9-ehci-1 "
+ "-device ich9-usb-uhci1,bus=pcie.0,addr=1d.0,"
+ "multifunction=on,masterbus=ich9-ehci-1.0,firstport=0 "
+ "-device ich9-usb-uhci2,bus=pcie.0,addr=1d.1,"
+ "multifunction=on,masterbus=ich9-ehci-1.0,firstport=2 "
+ "-device ich9-usb-uhci3,bus=pcie.0,addr=1d.2,"
+ "multifunction=on,masterbus=ich9-ehci-1.0,firstport=4 "
+ "-drive if=none,id=usbcdrom,media=cdrom "
+ "-device usb-tablet,bus=ich9-ehci-1.0,port=1,usb_version=1 "
+ "-device usb-storage,bus=ich9-ehci-1.0,port=2,drive=usbcdrom",
+ .objects = "*usb* *hci*",
+ },{
+ .name = "ohci",
+ .args = "-machine q35 -nodefaults -device pci-ohci -device usb-kbd",
+ .objects = "*usb* *ohci*",
+ },{
+ .name = "megaraid",
+ .args = "-machine q35 -nodefaults -device megasas -device scsi-cd,drive=null0 "
+ "-blockdev driver=null-co,read-zeroes=on,node-name=null0",
+ .objects = "megasas*",
+ },{
+ .name = "am53c974",
+ .args = "-device am53c974,id=scsi -device scsi-hd,drive=disk0 "
+ "-drive id=disk0,if=none,file=null-co://,format=raw "
+ "-nodefaults",
+ .objects = "*esp* *scsi* *am53c974*",
+ },{
+ .name = "ac97",
+ .args = "-machine q35 -nodefaults "
+ "-device ac97,audiodev=snd0 -audiodev none,id=snd0 -nodefaults",
+ .objects = "ac97*",
+ },{
+ .name = "cs4231a",
+ .args = "-machine q35 -nodefaults "
+ "-device cs4231a,audiodev=snd0 -audiodev none,id=snd0 -nodefaults",
+ .objects = "cs4231a* i8257*",
+ },{
+ .name = "es1370",
+ .args = "-machine q35 -nodefaults "
+ "-device es1370,audiodev=snd0 -audiodev none,id=snd0 -nodefaults",
+ .objects = "es1370*",
+ },{
+ .name = "sb16",
+ .args = "-machine q35 -nodefaults "
+ "-device sb16,audiodev=snd0 -audiodev none,id=snd0 -nodefaults",
+ .objects = "sb16* i8257*",
+ },{
+ .name = "parallel",
+ .args = "-machine q35 -nodefaults "
+ "-parallel file:/dev/null",
+ .objects = "parallel*",
+ }
+};
+
+#endif
diff --git a/tests/qtest/fuzz/i440fx_fuzz.c b/tests/qtest/fuzz/i440fx_fuzz.c
new file mode 100644
index 000000000..86796bff2
--- /dev/null
+++ b/tests/qtest/fuzz/i440fx_fuzz.c
@@ -0,0 +1,207 @@
+/*
+ * I440FX Fuzzing Target
+ *
+ * Copyright Red Hat Inc., 2019
+ *
+ * Authors:
+ * Alexander Bulekov <alxndr@bu.edu>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#include "qemu/osdep.h"
+
+#include "qemu/main-loop.h"
+#include "tests/qtest/libqos/libqtest.h"
+#include "tests/qtest/libqos/pci.h"
+#include "tests/qtest/libqos/pci-pc.h"
+#include "fuzz.h"
+#include "qos_fuzz.h"
+#include "fork_fuzz.h"
+
+
+#define I440FX_PCI_HOST_BRIDGE_CFG 0xcf8
+#define I440FX_PCI_HOST_BRIDGE_DATA 0xcfc
+
+/*
+ * the input to the fuzzing functions below is a buffer of random bytes. we
+ * want to convert these bytes into a sequence of qtest or qos calls. to do
+ * this we define some opcodes:
+ */
+enum action_id {
+ WRITEB,
+ WRITEW,
+ WRITEL,
+ READB,
+ READW,
+ READL,
+ ACTION_MAX
+};
+
+static void ioport_fuzz_qtest(QTestState *s,
+ const unsigned char *Data, size_t Size) {
+ /*
+ * loop over the Data, breaking it up into actions. each action has an
+ * opcode, address offset and value
+ */
+ struct {
+ uint8_t opcode;
+ uint8_t addr;
+ uint32_t value;
+ } a;
+
+ while (Size >= sizeof(a)) {
+ /* make a copy of the action so we can normalize the values in-place */
+ memcpy(&a, Data, sizeof(a));
+ /* select between two i440fx Port IO addresses */
+ uint16_t addr = a.addr % 2 ? I440FX_PCI_HOST_BRIDGE_CFG :
+ I440FX_PCI_HOST_BRIDGE_DATA;
+ switch (a.opcode % ACTION_MAX) {
+ case WRITEB:
+ qtest_outb(s, addr, (uint8_t)a.value);
+ break;
+ case WRITEW:
+ qtest_outw(s, addr, (uint16_t)a.value);
+ break;
+ case WRITEL:
+ qtest_outl(s, addr, (uint32_t)a.value);
+ break;
+ case READB:
+ qtest_inb(s, addr);
+ break;
+ case READW:
+ qtest_inw(s, addr);
+ break;
+ case READL:
+ qtest_inl(s, addr);
+ break;
+ }
+ /* Move to the next operation */
+ Size -= sizeof(a);
+ Data += sizeof(a);
+ }
+ flush_events(s);
+}
+
+static void i440fx_fuzz_qtest(QTestState *s,
+ const unsigned char *Data,
+ size_t Size)
+{
+ ioport_fuzz_qtest(s, Data, Size);
+}
+
+static void pciconfig_fuzz_qos(QTestState *s, QPCIBus *bus,
+ const unsigned char *Data, size_t Size) {
+ /*
+ * Same as ioport_fuzz_qtest, but using QOS. devfn is incorporated into the
+ * value written over Port IO
+ */
+ struct {
+ uint8_t opcode;
+ uint8_t offset;
+ int devfn;
+ uint32_t value;
+ } a;
+
+ while (Size >= sizeof(a)) {
+ memcpy(&a, Data, sizeof(a));
+ switch (a.opcode % ACTION_MAX) {
+ case WRITEB:
+ bus->config_writeb(bus, a.devfn, a.offset, (uint8_t)a.value);
+ break;
+ case WRITEW:
+ bus->config_writew(bus, a.devfn, a.offset, (uint16_t)a.value);
+ break;
+ case WRITEL:
+ bus->config_writel(bus, a.devfn, a.offset, (uint32_t)a.value);
+ break;
+ case READB:
+ bus->config_readb(bus, a.devfn, a.offset);
+ break;
+ case READW:
+ bus->config_readw(bus, a.devfn, a.offset);
+ break;
+ case READL:
+ bus->config_readl(bus, a.devfn, a.offset);
+ break;
+ }
+ Size -= sizeof(a);
+ Data += sizeof(a);
+ }
+ flush_events(s);
+}
+
+static void i440fx_fuzz_qos(QTestState *s,
+ const unsigned char *Data,
+ size_t Size)
+{
+ static QPCIBus *bus;
+
+ if (!bus) {
+ bus = qpci_new_pc(s, fuzz_qos_alloc);
+ }
+
+ pciconfig_fuzz_qos(s, bus, Data, Size);
+}
+
+static void i440fx_fuzz_qos_fork(QTestState *s,
+ const unsigned char *Data, size_t Size) {
+ if (fork() == 0) {
+ i440fx_fuzz_qos(s, Data, Size);
+ _Exit(0);
+ } else {
+ flush_events(s);
+ wait(NULL);
+ }
+}
+
+static const char *i440fx_qtest_argv = TARGET_NAME " -machine accel=qtest"
+ " -m 0 -display none";
+static GString *i440fx_argv(FuzzTarget *t)
+{
+ return g_string_new(i440fx_qtest_argv);
+}
+
+static void fork_init(void)
+{
+ counter_shm_init();
+}
+
+static void register_pci_fuzz_targets(void)
+{
+ /* Uses simple qtest commands and reboots to reset state */
+ fuzz_add_target(&(FuzzTarget){
+ .name = "i440fx-qtest-reboot-fuzz",
+ .description = "Fuzz the i440fx using raw qtest commands and "
+ "rebooting after each run",
+ .get_init_cmdline = i440fx_argv,
+ .fuzz = i440fx_fuzz_qtest});
+
+ /* Uses libqos and forks to prevent state leakage */
+ fuzz_add_qos_target(&(FuzzTarget){
+ .name = "i440fx-qos-fork-fuzz",
+ .description = "Fuzz the i440fx using raw qtest commands and "
+ "rebooting after each run",
+ .pre_vm_init = &fork_init,
+ .fuzz = i440fx_fuzz_qos_fork,},
+ "i440FX-pcihost",
+ &(QOSGraphTestOptions){}
+ );
+
+ /*
+ * Uses libqos. Doesn't do anything to reset state. Note that if we were to
+ * reboot after each run, we would also have to redo the qos-related
+ * initialization (qos_init_path)
+ */
+ fuzz_add_qos_target(&(FuzzTarget){
+ .name = "i440fx-qos-noreset-fuzz",
+ .description = "Fuzz the i440fx using raw qtest commands and "
+ "rebooting after each run",
+ .fuzz = i440fx_fuzz_qos,},
+ "i440FX-pcihost",
+ &(QOSGraphTestOptions){}
+ );
+}
+
+fuzz_target_init(register_pci_fuzz_targets);
diff --git a/tests/qtest/fuzz/meson.build b/tests/qtest/fuzz/meson.build
new file mode 100644
index 000000000..189901d4a
--- /dev/null
+++ b/tests/qtest/fuzz/meson.build
@@ -0,0 +1,38 @@
+if not get_option('fuzzing')
+ subdir_done()
+endif
+
+specific_fuzz_ss.add(files('fuzz.c', 'fork_fuzz.c', 'qos_fuzz.c',
+ 'qtest_wrappers.c'), qos)
+
+# Targets
+specific_fuzz_ss.add(when: 'CONFIG_I440FX', if_true: files('i440fx_fuzz.c'))
+specific_fuzz_ss.add(when: 'CONFIG_VIRTIO_NET', if_true: files('virtio_net_fuzz.c'))
+specific_fuzz_ss.add(when: 'CONFIG_VIRTIO_SCSI', if_true: files('virtio_scsi_fuzz.c'))
+specific_fuzz_ss.add(when: 'CONFIG_VIRTIO_BLK', if_true: files('virtio_blk_fuzz.c'))
+specific_fuzz_ss.add(files('generic_fuzz.c'))
+
+fork_fuzz = declare_dependency(
+ link_args: fuzz_exe_ldflags +
+ ['-Wl,-wrap,qtest_inb',
+ '-Wl,-wrap,qtest_inw',
+ '-Wl,-wrap,qtest_inl',
+ '-Wl,-wrap,qtest_outb',
+ '-Wl,-wrap,qtest_outw',
+ '-Wl,-wrap,qtest_outl',
+ '-Wl,-wrap,qtest_readb',
+ '-Wl,-wrap,qtest_readw',
+ '-Wl,-wrap,qtest_readl',
+ '-Wl,-wrap,qtest_readq',
+ '-Wl,-wrap,qtest_writeb',
+ '-Wl,-wrap,qtest_writew',
+ '-Wl,-wrap,qtest_writel',
+ '-Wl,-wrap,qtest_writeq',
+ '-Wl,-wrap,qtest_memread',
+ '-Wl,-wrap,qtest_bufread',
+ '-Wl,-wrap,qtest_memwrite',
+ '-Wl,-wrap,qtest_bufwrite',
+ '-Wl,-wrap,qtest_memset']
+)
+
+specific_fuzz_ss.add(fork_fuzz)
diff --git a/tests/qtest/fuzz/qos_fuzz.c b/tests/qtest/fuzz/qos_fuzz.c
new file mode 100644
index 000000000..7a244c951
--- /dev/null
+++ b/tests/qtest/fuzz/qos_fuzz.c
@@ -0,0 +1,217 @@
+/*
+ * QOS-assisted fuzzing helpers
+ *
+ * Copyright (c) 2018 Emanuele Giuseppe Esposito <e.emanuelegiuseppe@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>
+ */
+
+#include "qemu/osdep.h"
+#include "qemu/units.h"
+#include "qapi/error.h"
+#include "qemu-common.h"
+#include "exec/memory.h"
+#include "qemu/main-loop.h"
+
+#include "tests/qtest/libqos/libqtest.h"
+#include "tests/qtest/libqos/malloc.h"
+#include "tests/qtest/libqos/qgraph.h"
+#include "tests/qtest/libqos/qgraph_internal.h"
+#include "tests/qtest/libqos/qos_external.h"
+
+#include "fuzz.h"
+#include "qos_fuzz.h"
+
+#include "qapi/qapi-commands-machine.h"
+#include "qapi/qapi-commands-qom.h"
+
+
+void *fuzz_qos_obj;
+QGuestAllocator *fuzz_qos_alloc;
+
+static const char *fuzz_target_name;
+static char **fuzz_path_vec;
+
+static void qos_set_machines_devices_available(void)
+{
+ MachineInfoList *mach_info;
+ ObjectTypeInfoList *type_info;
+
+ mach_info = qmp_query_machines(&error_abort);
+ machines_apply_to_node(mach_info);
+ qapi_free_MachineInfoList(mach_info);
+
+ type_info = qmp_qom_list_types(true, "device", true, true,
+ &error_abort);
+ types_apply_to_node(type_info);
+ qapi_free_ObjectTypeInfoList(type_info);
+}
+
+static char **current_path;
+
+void *qos_allocate_objects(QTestState *qts, QGuestAllocator **p_alloc)
+{
+ return allocate_objects(qts, current_path + 1, p_alloc);
+}
+
+static GString *qos_build_main_args(void)
+{
+ char **path = fuzz_path_vec;
+ QOSGraphNode *test_node;
+ GString *cmd_line;
+ void *test_arg;
+
+ if (!path) {
+ fprintf(stderr, "QOS Path not found\n");
+ abort();
+ }
+
+ /* Before test */
+ cmd_line = g_string_new(path[0]);
+ current_path = path;
+ test_node = qos_graph_get_node(path[(g_strv_length(path) - 1)]);
+ test_arg = test_node->u.test.arg;
+ if (test_node->u.test.before) {
+ test_arg = test_node->u.test.before(cmd_line, test_arg);
+ }
+ /* Prepend the arguments that we need */
+ g_string_prepend(cmd_line,
+ TARGET_NAME " -display none -machine accel=qtest -m 64 ");
+ return cmd_line;
+}
+
+/*
+ * This function is largely a copy of qos-test.c:walk_path. Since walk_path
+ * is itself a callback, its a little annoying to add another argument/layer of
+ * indirection
+ */
+static void walk_path(QOSGraphNode *orig_path, int len)
+{
+ QOSGraphNode *path;
+ QOSGraphEdge *edge;
+
+ /*
+ * etype set to QEDGE_CONSUMED_BY so that machine can add to the command
+ * line
+ */
+ QOSEdgeType etype = QEDGE_CONSUMED_BY;
+
+ /* twice QOS_PATH_MAX_ELEMENT_SIZE since each edge can have its arg */
+ char **path_vec = g_new0(char *, (QOS_PATH_MAX_ELEMENT_SIZE * 2));
+ int path_vec_size = 0;
+
+ char *after_cmd, *before_cmd, *after_device;
+ GString *after_device_str = g_string_new("");
+ char *node_name = orig_path->name, *path_str;
+
+ GString *cmd_line = g_string_new("");
+ GString *cmd_line2 = g_string_new("");
+
+ path = qos_graph_get_node(node_name); /* root */
+ node_name = qos_graph_edge_get_dest(path->path_edge); /* machine name */
+
+ path_vec[path_vec_size++] = node_name;
+ path_vec[path_vec_size++] = qos_get_machine_type(node_name);
+
+ for (;;) {
+ path = qos_graph_get_node(node_name);
+ if (!path->path_edge) {
+ break;
+ }
+
+ node_name = qos_graph_edge_get_dest(path->path_edge);
+
+ /* append node command line + previous edge command line */
+ if (path->command_line && etype == QEDGE_CONSUMED_BY) {
+ g_string_append(cmd_line, path->command_line);
+ g_string_append(cmd_line, after_device_str->str);
+ g_string_truncate(after_device_str, 0);
+ }
+
+ path_vec[path_vec_size++] = qos_graph_edge_get_name(path->path_edge);
+ /* detect if edge has command line args */
+ after_cmd = qos_graph_edge_get_after_cmd_line(path->path_edge);
+ after_device = qos_graph_edge_get_extra_device_opts(path->path_edge);
+ before_cmd = qos_graph_edge_get_before_cmd_line(path->path_edge);
+ edge = qos_graph_get_edge(path->name, node_name);
+ etype = qos_graph_edge_get_type(edge);
+
+ if (before_cmd) {
+ g_string_append(cmd_line, before_cmd);
+ }
+ if (after_cmd) {
+ g_string_append(cmd_line2, after_cmd);
+ }
+ if (after_device) {
+ g_string_append(after_device_str, after_device);
+ }
+ }
+
+ path_vec[path_vec_size++] = NULL;
+ g_string_append(cmd_line, after_device_str->str);
+ g_string_free(after_device_str, true);
+
+ g_string_append(cmd_line, cmd_line2->str);
+ g_string_free(cmd_line2, true);
+
+ /*
+ * here position 0 has <arch>/<machine>, position 1 has <machine>.
+ * The path must not have the <arch>, qtest_add_data_func adds it.
+ */
+ path_str = g_strjoinv("/", path_vec + 1);
+
+ /* Check that this is the test we care about: */
+ char *test_name = strrchr(path_str, '/') + 1;
+ if (strcmp(test_name, fuzz_target_name) == 0) {
+ /*
+ * put arch/machine in position 1 so run_one_test can do its work
+ * and add the command line at position 0.
+ */
+ path_vec[1] = path_vec[0];
+ path_vec[0] = g_string_free(cmd_line, false);
+
+ fuzz_path_vec = path_vec;
+ } else {
+ g_free(path_vec);
+ }
+
+ g_free(path_str);
+}
+
+static GString *qos_get_cmdline(FuzzTarget *t)
+{
+ /*
+ * Set a global variable that we use to identify the qos_path for our
+ * fuzz_target
+ */
+ fuzz_target_name = t->name;
+ qos_set_machines_devices_available();
+ qos_graph_foreach_test_path(walk_path);
+ return qos_build_main_args();
+}
+
+void fuzz_add_qos_target(
+ FuzzTarget *fuzz_opts,
+ const char *interface,
+ QOSGraphTestOptions *opts
+ )
+{
+ qos_add_test(fuzz_opts->name, interface, NULL, opts);
+ fuzz_opts->get_init_cmdline = qos_get_cmdline;
+ fuzz_add_target(fuzz_opts);
+}
+
+void qos_init_path(QTestState *s)
+{
+ fuzz_qos_obj = qos_allocate_objects(s , &fuzz_qos_alloc);
+}
diff --git a/tests/qtest/fuzz/qos_fuzz.h b/tests/qtest/fuzz/qos_fuzz.h
new file mode 100644
index 000000000..63d8459b7
--- /dev/null
+++ b/tests/qtest/fuzz/qos_fuzz.h
@@ -0,0 +1,33 @@
+/*
+ * QOS-assisted fuzzing helpers
+ *
+ * Copyright Red Hat Inc., 2019
+ *
+ * Authors:
+ * Alexander Bulekov <alxndr@bu.edu>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#ifndef QOS_FUZZ_H
+#define QOS_FUZZ_H
+
+#include "tests/qtest/fuzz/fuzz.h"
+#include "tests/qtest/libqos/qgraph.h"
+
+int qos_fuzz(const unsigned char *Data, size_t Size);
+void qos_setup(void);
+
+extern void *fuzz_qos_obj;
+extern QGuestAllocator *fuzz_qos_alloc;
+
+void fuzz_add_qos_target(
+ FuzzTarget *fuzz_opts,
+ const char *interface,
+ QOSGraphTestOptions *opts
+ );
+
+void qos_init_path(QTestState *);
+
+#endif
diff --git a/tests/qtest/fuzz/qtest_wrappers.c b/tests/qtest/fuzz/qtest_wrappers.c
new file mode 100644
index 000000000..0580f8df8
--- /dev/null
+++ b/tests/qtest/fuzz/qtest_wrappers.c
@@ -0,0 +1,252 @@
+/*
+ * qtest function wrappers
+ *
+ * Copyright Red Hat Inc., 2019
+ *
+ * Authors:
+ * Alexander Bulekov <alxndr@bu.edu>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ */
+
+#include "qemu/osdep.h"
+#include "hw/core/cpu.h"
+#include "exec/ioport.h"
+
+#include "fuzz.h"
+
+static bool serialize = true;
+
+#define WRAP(RET_TYPE, NAME_AND_ARGS)\
+ RET_TYPE __wrap_##NAME_AND_ARGS;\
+ RET_TYPE __real_##NAME_AND_ARGS;
+
+WRAP(uint8_t , qtest_inb(QTestState *s, uint16_t addr))
+WRAP(uint16_t , qtest_inw(QTestState *s, uint16_t addr))
+WRAP(uint32_t , qtest_inl(QTestState *s, uint16_t addr))
+WRAP(void , qtest_outb(QTestState *s, uint16_t addr, uint8_t value))
+WRAP(void , qtest_outw(QTestState *s, uint16_t addr, uint16_t value))
+WRAP(void , qtest_outl(QTestState *s, uint16_t addr, uint32_t value))
+WRAP(uint8_t , qtest_readb(QTestState *s, uint64_t addr))
+WRAP(uint16_t , qtest_readw(QTestState *s, uint64_t addr))
+WRAP(uint32_t , qtest_readl(QTestState *s, uint64_t addr))
+WRAP(uint64_t , qtest_readq(QTestState *s, uint64_t addr))
+WRAP(void , qtest_writeb(QTestState *s, uint64_t addr, uint8_t value))
+WRAP(void , qtest_writew(QTestState *s, uint64_t addr, uint16_t value))
+WRAP(void , qtest_writel(QTestState *s, uint64_t addr, uint32_t value))
+WRAP(void , qtest_writeq(QTestState *s, uint64_t addr, uint64_t value))
+WRAP(void , qtest_memread(QTestState *s, uint64_t addr,
+ void *data, size_t size))
+WRAP(void , qtest_bufread(QTestState *s, uint64_t addr, void *data,
+ size_t size))
+WRAP(void , qtest_memwrite(QTestState *s, uint64_t addr, const void *data,
+ size_t size))
+WRAP(void, qtest_bufwrite(QTestState *s, uint64_t addr,
+ const void *data, size_t size))
+WRAP(void, qtest_memset(QTestState *s, uint64_t addr,
+ uint8_t patt, size_t size))
+
+
+uint8_t __wrap_qtest_inb(QTestState *s, uint16_t addr)
+{
+ if (!serialize) {
+ return cpu_inb(addr);
+ } else {
+ return __real_qtest_inb(s, addr);
+ }
+}
+
+uint16_t __wrap_qtest_inw(QTestState *s, uint16_t addr)
+{
+ if (!serialize) {
+ return cpu_inw(addr);
+ } else {
+ return __real_qtest_inw(s, addr);
+ }
+}
+
+uint32_t __wrap_qtest_inl(QTestState *s, uint16_t addr)
+{
+ if (!serialize) {
+ return cpu_inl(addr);
+ } else {
+ return __real_qtest_inl(s, addr);
+ }
+}
+
+void __wrap_qtest_outb(QTestState *s, uint16_t addr, uint8_t value)
+{
+ if (!serialize) {
+ cpu_outb(addr, value);
+ } else {
+ __real_qtest_outb(s, addr, value);
+ }
+}
+
+void __wrap_qtest_outw(QTestState *s, uint16_t addr, uint16_t value)
+{
+ if (!serialize) {
+ cpu_outw(addr, value);
+ } else {
+ __real_qtest_outw(s, addr, value);
+ }
+}
+
+void __wrap_qtest_outl(QTestState *s, uint16_t addr, uint32_t value)
+{
+ if (!serialize) {
+ cpu_outl(addr, value);
+ } else {
+ __real_qtest_outl(s, addr, value);
+ }
+}
+
+uint8_t __wrap_qtest_readb(QTestState *s, uint64_t addr)
+{
+ uint8_t value;
+ if (!serialize) {
+ address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
+ &value, 1);
+ return value;
+ } else {
+ return __real_qtest_readb(s, addr);
+ }
+}
+
+uint16_t __wrap_qtest_readw(QTestState *s, uint64_t addr)
+{
+ uint16_t value;
+ if (!serialize) {
+ address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
+ &value, 2);
+ return value;
+ } else {
+ return __real_qtest_readw(s, addr);
+ }
+}
+
+uint32_t __wrap_qtest_readl(QTestState *s, uint64_t addr)
+{
+ uint32_t value;
+ if (!serialize) {
+ address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
+ &value, 4);
+ return value;
+ } else {
+ return __real_qtest_readl(s, addr);
+ }
+}
+
+uint64_t __wrap_qtest_readq(QTestState *s, uint64_t addr)
+{
+ uint64_t value;
+ if (!serialize) {
+ address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
+ &value, 8);
+ return value;
+ } else {
+ return __real_qtest_readq(s, addr);
+ }
+}
+
+void __wrap_qtest_writeb(QTestState *s, uint64_t addr, uint8_t value)
+{
+ if (!serialize) {
+ address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
+ &value, 1);
+ } else {
+ __real_qtest_writeb(s, addr, value);
+ }
+}
+
+void __wrap_qtest_writew(QTestState *s, uint64_t addr, uint16_t value)
+{
+ if (!serialize) {
+ address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
+ &value, 2);
+ } else {
+ __real_qtest_writew(s, addr, value);
+ }
+}
+
+void __wrap_qtest_writel(QTestState *s, uint64_t addr, uint32_t value)
+{
+ if (!serialize) {
+ address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
+ &value, 4);
+ } else {
+ __real_qtest_writel(s, addr, value);
+ }
+}
+
+void __wrap_qtest_writeq(QTestState *s, uint64_t addr, uint64_t value)
+{
+ if (!serialize) {
+ address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
+ &value, 8);
+ } else {
+ __real_qtest_writeq(s, addr, value);
+ }
+}
+
+void __wrap_qtest_memread(QTestState *s, uint64_t addr, void *data, size_t size)
+{
+ if (!serialize) {
+ address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED, data,
+ size);
+ } else {
+ __real_qtest_memread(s, addr, data, size);
+ }
+}
+
+void __wrap_qtest_bufread(QTestState *s, uint64_t addr, void *data, size_t size)
+{
+ if (!serialize) {
+ address_space_read(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED, data,
+ size);
+ } else {
+ __real_qtest_bufread(s, addr, data, size);
+ }
+}
+
+void __wrap_qtest_memwrite(QTestState *s, uint64_t addr, const void *data,
+ size_t size)
+{
+ if (!serialize) {
+ address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
+ data, size);
+ } else {
+ __real_qtest_memwrite(s, addr, data, size);
+ }
+}
+
+void __wrap_qtest_bufwrite(QTestState *s, uint64_t addr,
+ const void *data, size_t size)
+{
+ if (!serialize) {
+ address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
+ data, size);
+ } else {
+ __real_qtest_bufwrite(s, addr, data, size);
+ }
+}
+void __wrap_qtest_memset(QTestState *s, uint64_t addr,
+ uint8_t patt, size_t size)
+{
+ void *data;
+ if (!serialize) {
+ data = malloc(size);
+ memset(data, patt, size);
+ address_space_write(first_cpu->as, addr, MEMTXATTRS_UNSPECIFIED,
+ data, size);
+ } else {
+ __real_qtest_memset(s, addr, patt, size);
+ }
+}
+
+void fuzz_qtest_set_serialize(bool option)
+{
+ serialize = option;
+}
diff --git a/tests/qtest/fuzz/virtio_blk_fuzz.c b/tests/qtest/fuzz/virtio_blk_fuzz.c
new file mode 100644
index 000000000..623a756fd
--- /dev/null
+++ b/tests/qtest/fuzz/virtio_blk_fuzz.c
@@ -0,0 +1,234 @@
+/*
+ * virtio-blk Fuzzing Target
+ *
+ * Copyright Red Hat Inc., 2020
+ *
+ * Based on virtio-scsi-fuzz target.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#include "qemu/osdep.h"
+
+#include "tests/qtest/libqos/libqtest.h"
+#include "tests/qtest/libqos/virtio-blk.h"
+#include "tests/qtest/libqos/virtio.h"
+#include "tests/qtest/libqos/virtio-pci.h"
+#include "standard-headers/linux/virtio_ids.h"
+#include "standard-headers/linux/virtio_pci.h"
+#include "standard-headers/linux/virtio_blk.h"
+#include "fuzz.h"
+#include "fork_fuzz.h"
+#include "qos_fuzz.h"
+
+#define TEST_IMAGE_SIZE (64 * 1024 * 1024)
+#define PCI_SLOT 0x02
+#define PCI_FN 0x00
+
+#define MAX_NUM_QUEUES 64
+
+/* Based on tests/qtest/virtio-blk-test.c. */
+typedef struct {
+ int num_queues;
+ QVirtQueue *vq[MAX_NUM_QUEUES + 2];
+} QVirtioBlkQueues;
+
+static QVirtioBlkQueues *qvirtio_blk_init(QVirtioDevice *dev, uint64_t mask)
+{
+ QVirtioBlkQueues *vs;
+ uint64_t features;
+
+ vs = g_new0(QVirtioBlkQueues, 1);
+
+ features = qvirtio_get_features(dev);
+ if (!mask) {
+ mask = ~((1u << VIRTIO_RING_F_INDIRECT_DESC) |
+ (1u << VIRTIO_RING_F_EVENT_IDX) |
+ (1u << VIRTIO_BLK_F_SCSI));
+ }
+ mask |= ~QVIRTIO_F_BAD_FEATURE;
+ features &= mask;
+ qvirtio_set_features(dev, features);
+
+ vs->num_queues = 1;
+ vs->vq[0] = qvirtqueue_setup(dev, fuzz_qos_alloc, 0);
+
+ qvirtio_set_driver_ok(dev);
+
+ return vs;
+}
+
+static void virtio_blk_fuzz(QTestState *s, QVirtioBlkQueues* queues,
+ const unsigned char *Data, size_t Size)
+{
+ /*
+ * Data is a sequence of random bytes. We split them up into "actions",
+ * followed by data:
+ * [vqa][dddddddd][vqa][dddd][vqa][dddddddddddd] ...
+ * The length of the data is specified by the preceding vqa.length
+ */
+ typedef struct vq_action {
+ uint8_t queue;
+ uint8_t length;
+ uint8_t write;
+ uint8_t next;
+ uint8_t kick;
+ } vq_action;
+
+ /* Keep track of the free head for each queue we interact with */
+ bool vq_touched[MAX_NUM_QUEUES + 2] = {0};
+ uint32_t free_head[MAX_NUM_QUEUES + 2];
+
+ QGuestAllocator *t_alloc = fuzz_qos_alloc;
+
+ QVirtioBlk *blk = fuzz_qos_obj;
+ QVirtioDevice *dev = blk->vdev;
+ QVirtQueue *q;
+ vq_action vqa;
+ while (Size >= sizeof(vqa)) {
+ /* Copy the action, so we can normalize length, queue and flags */
+ memcpy(&vqa, Data, sizeof(vqa));
+
+ Data += sizeof(vqa);
+ Size -= sizeof(vqa);
+
+ vqa.queue = vqa.queue % queues->num_queues;
+ /* Cap length at the number of remaining bytes in data */
+ vqa.length = vqa.length >= Size ? Size : vqa.length;
+ vqa.write = vqa.write & 1;
+ vqa.next = vqa.next & 1;
+ vqa.kick = vqa.kick & 1;
+
+ q = queues->vq[vqa.queue];
+
+ /* Copy the data into ram, and place it on the virtqueue */
+ uint64_t req_addr = guest_alloc(t_alloc, vqa.length);
+ qtest_memwrite(s, req_addr, Data, vqa.length);
+ if (vq_touched[vqa.queue] == 0) {
+ vq_touched[vqa.queue] = 1;
+ free_head[vqa.queue] = qvirtqueue_add(s, q, req_addr, vqa.length,
+ vqa.write, vqa.next);
+ } else {
+ qvirtqueue_add(s, q, req_addr, vqa.length, vqa.write , vqa.next);
+ }
+
+ if (vqa.kick) {
+ qvirtqueue_kick(s, dev, q, free_head[vqa.queue]);
+ free_head[vqa.queue] = 0;
+ }
+ Data += vqa.length;
+ Size -= vqa.length;
+ }
+ /* In the end, kick each queue we interacted with */
+ for (int i = 0; i < MAX_NUM_QUEUES + 2; i++) {
+ if (vq_touched[i]) {
+ qvirtqueue_kick(s, dev, queues->vq[i], free_head[i]);
+ }
+ }
+}
+
+static void virtio_blk_fork_fuzz(QTestState *s,
+ const unsigned char *Data, size_t Size)
+{
+ QVirtioBlk *blk = fuzz_qos_obj;
+ static QVirtioBlkQueues *queues;
+ if (!queues) {
+ queues = qvirtio_blk_init(blk->vdev, 0);
+ }
+ if (fork() == 0) {
+ virtio_blk_fuzz(s, queues, Data, Size);
+ flush_events(s);
+ _Exit(0);
+ } else {
+ flush_events(s);
+ wait(NULL);
+ }
+}
+
+static void virtio_blk_with_flag_fuzz(QTestState *s,
+ const unsigned char *Data, size_t Size)
+{
+ QVirtioBlk *blk = fuzz_qos_obj;
+ static QVirtioBlkQueues *queues;
+
+ if (fork() == 0) {
+ if (Size >= sizeof(uint64_t)) {
+ queues = qvirtio_blk_init(blk->vdev, *(uint64_t *)Data);
+ virtio_blk_fuzz(s, queues,
+ Data + sizeof(uint64_t), Size - sizeof(uint64_t));
+ flush_events(s);
+ }
+ _Exit(0);
+ } else {
+ flush_events(s);
+ wait(NULL);
+ }
+}
+
+static void virtio_blk_pre_fuzz(QTestState *s)
+{
+ qos_init_path(s);
+ counter_shm_init();
+}
+
+static void drive_destroy(void *path)
+{
+ unlink(path);
+ g_free(path);
+}
+
+static char *drive_create(void)
+{
+ int fd, ret;
+ char *t_path = g_strdup("/tmp/qtest.XXXXXX");
+
+ /* Create a temporary raw image */
+ fd = mkstemp(t_path);
+ g_assert_cmpint(fd, >=, 0);
+ ret = ftruncate(fd, TEST_IMAGE_SIZE);
+ g_assert_cmpint(ret, ==, 0);
+ close(fd);
+
+ g_test_queue_destroy(drive_destroy, t_path);
+ return t_path;
+}
+
+static void *virtio_blk_test_setup(GString *cmd_line, void *arg)
+{
+ char *tmp_path = drive_create();
+
+ g_string_append_printf(cmd_line,
+ " -drive if=none,id=drive0,file=%s,"
+ "format=raw,auto-read-only=off ",
+ tmp_path);
+
+ return arg;
+}
+
+static void register_virtio_blk_fuzz_targets(void)
+{
+ fuzz_add_qos_target(&(FuzzTarget){
+ .name = "virtio-blk-fuzz",
+ .description = "Fuzz the virtio-blk virtual queues, forking "
+ "for each fuzz run",
+ .pre_vm_init = &counter_shm_init,
+ .pre_fuzz = &virtio_blk_pre_fuzz,
+ .fuzz = virtio_blk_fork_fuzz,},
+ "virtio-blk",
+ &(QOSGraphTestOptions){.before = virtio_blk_test_setup}
+ );
+
+ fuzz_add_qos_target(&(FuzzTarget){
+ .name = "virtio-blk-flags-fuzz",
+ .description = "Fuzz the virtio-blk virtual queues, forking "
+ "for each fuzz run (also fuzzes the virtio flags)",
+ .pre_vm_init = &counter_shm_init,
+ .pre_fuzz = &virtio_blk_pre_fuzz,
+ .fuzz = virtio_blk_with_flag_fuzz,},
+ "virtio-blk",
+ &(QOSGraphTestOptions){.before = virtio_blk_test_setup}
+ );
+}
+
+fuzz_target_init(register_virtio_blk_fuzz_targets);
diff --git a/tests/qtest/fuzz/virtio_net_fuzz.c b/tests/qtest/fuzz/virtio_net_fuzz.c
new file mode 100644
index 000000000..0e873ab8e
--- /dev/null
+++ b/tests/qtest/fuzz/virtio_net_fuzz.c
@@ -0,0 +1,201 @@
+/*
+ * virtio-net Fuzzing Target
+ *
+ * Copyright Red Hat Inc., 2019
+ *
+ * Authors:
+ * Alexander Bulekov <alxndr@bu.edu>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#include "qemu/osdep.h"
+
+#include "standard-headers/linux/virtio_config.h"
+#include "tests/qtest/libqos/libqtest.h"
+#include "tests/qtest/libqos/virtio-net.h"
+#include "fuzz.h"
+#include "fork_fuzz.h"
+#include "qos_fuzz.h"
+
+
+#define QVIRTIO_NET_TIMEOUT_US (30 * 1000 * 1000)
+#define QVIRTIO_RX_VQ 0
+#define QVIRTIO_TX_VQ 1
+#define QVIRTIO_CTRL_VQ 2
+
+static int sockfds[2];
+static bool sockfds_initialized;
+
+static void virtio_net_fuzz_multi(QTestState *s,
+ const unsigned char *Data, size_t Size, bool check_used)
+{
+ typedef struct vq_action {
+ uint8_t queue;
+ uint8_t length;
+ uint8_t write;
+ uint8_t next;
+ uint8_t rx;
+ } vq_action;
+
+ uint32_t free_head = 0;
+
+ QGuestAllocator *t_alloc = fuzz_qos_alloc;
+
+ QVirtioNet *net_if = fuzz_qos_obj;
+ QVirtioDevice *dev = net_if->vdev;
+ QVirtQueue *q;
+ vq_action vqa;
+ while (Size >= sizeof(vqa)) {
+ memcpy(&vqa, Data, sizeof(vqa));
+ Data += sizeof(vqa);
+ Size -= sizeof(vqa);
+
+ q = net_if->queues[vqa.queue % 3];
+
+ vqa.length = vqa.length >= Size ? Size : vqa.length;
+
+ /*
+ * Only attempt to write incoming packets, when using the socket
+ * backend. Otherwise, always place the input on a virtqueue.
+ */
+ if (vqa.rx && sockfds_initialized) {
+ int ignored = write(sockfds[0], Data, vqa.length);
+ (void) ignored;
+ } else {
+ vqa.rx = 0;
+ uint64_t req_addr = guest_alloc(t_alloc, vqa.length);
+ /*
+ * If checking used ring, ensure that the fuzzer doesn't trigger
+ * trivial asserion failure on zero-zied buffer
+ */
+ qtest_memwrite(s, req_addr, Data, vqa.length);
+
+
+ free_head = qvirtqueue_add(s, q, req_addr, vqa.length,
+ vqa.write, vqa.next);
+ qvirtqueue_add(s, q, req_addr, vqa.length, vqa.write , vqa.next);
+ qvirtqueue_kick(s, dev, q, free_head);
+ }
+
+ /* Run the main loop */
+ qtest_clock_step(s, 100);
+ flush_events(s);
+
+ /* Wait on used descriptors */
+ if (check_used && !vqa.rx) {
+ gint64 start_time = g_get_monotonic_time();
+ /*
+ * normally, we could just use qvirtio_wait_used_elem, but since we
+ * must manually run the main-loop for all the bhs to run, we use
+ * this hack with flush_events(), to run the main_loop
+ */
+ while (!vqa.rx && q != net_if->queues[QVIRTIO_RX_VQ]) {
+ uint32_t got_desc_idx;
+ /* Input led to a virtio_error */
+ if (dev->bus->get_status(dev) & VIRTIO_CONFIG_S_NEEDS_RESET) {
+ break;
+ }
+ if (dev->bus->get_queue_isr_status(dev, q) &&
+ qvirtqueue_get_buf(s, q, &got_desc_idx, NULL)) {
+ g_assert_cmpint(got_desc_idx, ==, free_head);
+ break;
+ }
+ g_assert(g_get_monotonic_time() - start_time
+ <= QVIRTIO_NET_TIMEOUT_US);
+
+ /* Run the main loop */
+ qtest_clock_step(s, 100);
+ flush_events(s);
+ }
+ }
+ Data += vqa.length;
+ Size -= vqa.length;
+ }
+}
+
+static void virtio_net_fork_fuzz(QTestState *s,
+ const unsigned char *Data, size_t Size)
+{
+ if (fork() == 0) {
+ virtio_net_fuzz_multi(s, Data, Size, false);
+ flush_events(s);
+ _Exit(0);
+ } else {
+ flush_events(s);
+ wait(NULL);
+ }
+}
+
+static void virtio_net_fork_fuzz_check_used(QTestState *s,
+ const unsigned char *Data, size_t Size)
+{
+ if (fork() == 0) {
+ virtio_net_fuzz_multi(s, Data, Size, true);
+ flush_events(s);
+ _Exit(0);
+ } else {
+ flush_events(s);
+ wait(NULL);
+ }
+}
+
+static void virtio_net_pre_fuzz(QTestState *s)
+{
+ qos_init_path(s);
+ counter_shm_init();
+}
+
+static void *virtio_net_test_setup_socket(GString *cmd_line, void *arg)
+{
+ int ret = socketpair(PF_UNIX, SOCK_STREAM, 0, sockfds);
+ g_assert_cmpint(ret, !=, -1);
+ fcntl(sockfds[0], F_SETFL, O_NONBLOCK);
+ sockfds_initialized = true;
+ g_string_append_printf(cmd_line, " -netdev socket,fd=%d,id=hs0 ",
+ sockfds[1]);
+ return arg;
+}
+
+static void *virtio_net_test_setup_user(GString *cmd_line, void *arg)
+{
+ g_string_append_printf(cmd_line, " -netdev user,id=hs0 ");
+ return arg;
+}
+
+static void register_virtio_net_fuzz_targets(void)
+{
+ fuzz_add_qos_target(&(FuzzTarget){
+ .name = "virtio-net-socket",
+ .description = "Fuzz the virtio-net virtual queues. Fuzz incoming "
+ "traffic using the socket backend",
+ .pre_fuzz = &virtio_net_pre_fuzz,
+ .fuzz = virtio_net_fork_fuzz,},
+ "virtio-net",
+ &(QOSGraphTestOptions){.before = virtio_net_test_setup_socket}
+ );
+
+ fuzz_add_qos_target(&(FuzzTarget){
+ .name = "virtio-net-socket-check-used",
+ .description = "Fuzz the virtio-net virtual queues. Wait for the "
+ "descriptors to be used. Timeout may indicate improperly handled "
+ "input",
+ .pre_fuzz = &virtio_net_pre_fuzz,
+ .fuzz = virtio_net_fork_fuzz_check_used,},
+ "virtio-net",
+ &(QOSGraphTestOptions){.before = virtio_net_test_setup_socket}
+ );
+ fuzz_add_qos_target(&(FuzzTarget){
+ .name = "virtio-net-slirp",
+ .description = "Fuzz the virtio-net virtual queues with the slirp "
+ " backend. Warning: May result in network traffic emitted from the "
+ " process. Run in an isolated network environment.",
+ .pre_fuzz = &virtio_net_pre_fuzz,
+ .fuzz = virtio_net_fork_fuzz,},
+ "virtio-net",
+ &(QOSGraphTestOptions){.before = virtio_net_test_setup_user}
+ );
+}
+
+fuzz_target_init(register_virtio_net_fuzz_targets);
diff --git a/tests/qtest/fuzz/virtio_scsi_fuzz.c b/tests/qtest/fuzz/virtio_scsi_fuzz.c
new file mode 100644
index 000000000..6ff6fabe4
--- /dev/null
+++ b/tests/qtest/fuzz/virtio_scsi_fuzz.c
@@ -0,0 +1,215 @@
+/*
+ * virtio-serial Fuzzing Target
+ *
+ * Copyright Red Hat Inc., 2019
+ *
+ * Authors:
+ * Alexander Bulekov <alxndr@bu.edu>
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ */
+
+#include "qemu/osdep.h"
+
+#include "tests/qtest/libqos/libqtest.h"
+#include "tests/qtest/libqos/virtio-scsi.h"
+#include "tests/qtest/libqos/virtio.h"
+#include "tests/qtest/libqos/virtio-pci.h"
+#include "standard-headers/linux/virtio_ids.h"
+#include "standard-headers/linux/virtio_pci.h"
+#include "standard-headers/linux/virtio_scsi.h"
+#include "fuzz.h"
+#include "fork_fuzz.h"
+#include "qos_fuzz.h"
+
+#define PCI_SLOT 0x02
+#define PCI_FN 0x00
+#define QVIRTIO_SCSI_TIMEOUT_US (1 * 1000 * 1000)
+
+#define MAX_NUM_QUEUES 64
+
+/* Based on tests/virtio-scsi-test.c */
+typedef struct {
+ int num_queues;
+ QVirtQueue *vq[MAX_NUM_QUEUES + 2];
+} QVirtioSCSIQueues;
+
+static QVirtioSCSIQueues *qvirtio_scsi_init(QVirtioDevice *dev, uint64_t mask)
+{
+ QVirtioSCSIQueues *vs;
+ uint64_t feat;
+ int i;
+
+ vs = g_new0(QVirtioSCSIQueues, 1);
+
+ feat = qvirtio_get_features(dev);
+ if (mask) {
+ feat &= ~QVIRTIO_F_BAD_FEATURE | mask;
+ } else {
+ feat &= ~(QVIRTIO_F_BAD_FEATURE | (1ull << VIRTIO_RING_F_EVENT_IDX));
+ }
+ qvirtio_set_features(dev, feat);
+
+ vs->num_queues = qvirtio_config_readl(dev, 0);
+
+ for (i = 0; i < vs->num_queues + 2; i++) {
+ vs->vq[i] = qvirtqueue_setup(dev, fuzz_qos_alloc, i);
+ }
+
+ qvirtio_set_driver_ok(dev);
+
+ return vs;
+}
+
+static void virtio_scsi_fuzz(QTestState *s, QVirtioSCSIQueues* queues,
+ const unsigned char *Data, size_t Size)
+{
+ /*
+ * Data is a sequence of random bytes. We split them up into "actions",
+ * followed by data:
+ * [vqa][dddddddd][vqa][dddd][vqa][dddddddddddd] ...
+ * The length of the data is specified by the preceding vqa.length
+ */
+ typedef struct vq_action {
+ uint8_t queue;
+ uint8_t length;
+ uint8_t write;
+ uint8_t next;
+ uint8_t kick;
+ } vq_action;
+
+ /* Keep track of the free head for each queue we interact with */
+ bool vq_touched[MAX_NUM_QUEUES + 2] = {0};
+ uint32_t free_head[MAX_NUM_QUEUES + 2];
+
+ QGuestAllocator *t_alloc = fuzz_qos_alloc;
+
+ QVirtioSCSI *scsi = fuzz_qos_obj;
+ QVirtioDevice *dev = scsi->vdev;
+ QVirtQueue *q;
+ vq_action vqa;
+ while (Size >= sizeof(vqa)) {
+ /* Copy the action, so we can normalize length, queue and flags */
+ memcpy(&vqa, Data, sizeof(vqa));
+
+ Data += sizeof(vqa);
+ Size -= sizeof(vqa);
+
+ vqa.queue = vqa.queue % queues->num_queues;
+ /* Cap length at the number of remaining bytes in data */
+ vqa.length = vqa.length >= Size ? Size : vqa.length;
+ vqa.write = vqa.write & 1;
+ vqa.next = vqa.next & 1;
+ vqa.kick = vqa.kick & 1;
+
+
+ q = queues->vq[vqa.queue];
+
+ /* Copy the data into ram, and place it on the virtqueue */
+ uint64_t req_addr = guest_alloc(t_alloc, vqa.length);
+ qtest_memwrite(s, req_addr, Data, vqa.length);
+ if (vq_touched[vqa.queue] == 0) {
+ vq_touched[vqa.queue] = 1;
+ free_head[vqa.queue] = qvirtqueue_add(s, q, req_addr, vqa.length,
+ vqa.write, vqa.next);
+ } else {
+ qvirtqueue_add(s, q, req_addr, vqa.length, vqa.write , vqa.next);
+ }
+
+ if (vqa.kick) {
+ qvirtqueue_kick(s, dev, q, free_head[vqa.queue]);
+ free_head[vqa.queue] = 0;
+ }
+ Data += vqa.length;
+ Size -= vqa.length;
+ }
+ /* In the end, kick each queue we interacted with */
+ for (int i = 0; i < MAX_NUM_QUEUES + 2; i++) {
+ if (vq_touched[i]) {
+ qvirtqueue_kick(s, dev, queues->vq[i], free_head[i]);
+ }
+ }
+}
+
+static void virtio_scsi_fork_fuzz(QTestState *s,
+ const unsigned char *Data, size_t Size)
+{
+ QVirtioSCSI *scsi = fuzz_qos_obj;
+ static QVirtioSCSIQueues *queues;
+ if (!queues) {
+ queues = qvirtio_scsi_init(scsi->vdev, 0);
+ }
+ if (fork() == 0) {
+ virtio_scsi_fuzz(s, queues, Data, Size);
+ flush_events(s);
+ _Exit(0);
+ } else {
+ flush_events(s);
+ wait(NULL);
+ }
+}
+
+static void virtio_scsi_with_flag_fuzz(QTestState *s,
+ const unsigned char *Data, size_t Size)
+{
+ QVirtioSCSI *scsi = fuzz_qos_obj;
+ static QVirtioSCSIQueues *queues;
+
+ if (fork() == 0) {
+ if (Size >= sizeof(uint64_t)) {
+ queues = qvirtio_scsi_init(scsi->vdev, *(uint64_t *)Data);
+ virtio_scsi_fuzz(s, queues,
+ Data + sizeof(uint64_t), Size - sizeof(uint64_t));
+ flush_events(s);
+ }
+ _Exit(0);
+ } else {
+ flush_events(s);
+ wait(NULL);
+ }
+}
+
+static void virtio_scsi_pre_fuzz(QTestState *s)
+{
+ qos_init_path(s);
+ counter_shm_init();
+}
+
+static void *virtio_scsi_test_setup(GString *cmd_line, void *arg)
+{
+ g_string_append(cmd_line,
+ " -drive file=blkdebug::null-co://,"
+ "file.image.read-zeroes=on,"
+ "if=none,id=dr1,format=raw,file.align=4k "
+ "-device scsi-hd,drive=dr1,lun=0,scsi-id=1");
+ return arg;
+}
+
+
+static void register_virtio_scsi_fuzz_targets(void)
+{
+ fuzz_add_qos_target(&(FuzzTarget){
+ .name = "virtio-scsi-fuzz",
+ .description = "Fuzz the virtio-scsi virtual queues, forking "
+ "for each fuzz run",
+ .pre_vm_init = &counter_shm_init,
+ .pre_fuzz = &virtio_scsi_pre_fuzz,
+ .fuzz = virtio_scsi_fork_fuzz,},
+ "virtio-scsi",
+ &(QOSGraphTestOptions){.before = virtio_scsi_test_setup}
+ );
+
+ fuzz_add_qos_target(&(FuzzTarget){
+ .name = "virtio-scsi-flags-fuzz",
+ .description = "Fuzz the virtio-scsi virtual queues, forking "
+ "for each fuzz run (also fuzzes the virtio flags)",
+ .pre_vm_init = &counter_shm_init,
+ .pre_fuzz = &virtio_scsi_pre_fuzz,
+ .fuzz = virtio_scsi_with_flag_fuzz,},
+ "virtio-scsi",
+ &(QOSGraphTestOptions){.before = virtio_scsi_test_setup}
+ );
+}
+
+fuzz_target_init(register_virtio_scsi_fuzz_targets);