From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-17.7 required=3.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,HEADER_FROM_DIFFERENT_DOMAINS,HK_RANDOM_FROM,INCLUDES_PATCH, MAILING_LIST_MULTI,MENTIONS_GIT_HOSTING,MSGID_FROM_MTA_HEADER,SIGNED_OFF_BY, SPF_HELO_NONE,SPF_PASS,URIBL_BLOCKED,USER_AGENT_GIT autolearn=ham autolearn_force=no version=3.4.0 Received: from mail.kernel.org (mail.kernel.org [198.145.29.99]) by smtp.lore.kernel.org (Postfix) with ESMTP id A5454C43466 for ; Mon, 21 Sep 2020 02:27:39 +0000 (UTC) Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.kernel.org (Postfix) with ESMTPS id 364732078E for ; Mon, 21 Sep 2020 02:27:39 +0000 (UTC) Authentication-Results: mail.kernel.org; dkim=pass (1024-bit key) header.d=bushare.onmicrosoft.com header.i=@bushare.onmicrosoft.com header.b="Mpa4LUUY" DMARC-Filter: OpenDMARC Filter v1.3.2 mail.kernel.org 364732078E Authentication-Results: mail.kernel.org; dmarc=none (p=none dis=none) header.from=bu.edu Authentication-Results: mail.kernel.org; spf=pass smtp.mailfrom=qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Received: from localhost ([::1]:40522 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1kKBYI-00050p-58 for qemu-devel@archiver.kernel.org; Sun, 20 Sep 2020 22:27:38 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]:41448) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1kKBWR-000380-U9 for qemu-devel@nongnu.org; Sun, 20 Sep 2020 22:25:43 -0400 Received: from mail-dm6nam10on2102.outbound.protection.outlook.com ([40.107.93.102]:19201 helo=NAM10-DM6-obe.outbound.protection.outlook.com) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1kKBWP-0000aa-GP for qemu-devel@nongnu.org; Sun, 20 Sep 2020 22:25:43 -0400 ARC-Seal: i=1; a=rsa-sha256; s=arcselector9901; d=microsoft.com; cv=none; b=e89B4jW2Kg8PP3Rme4saI2AEJYjwKz6kzzBwcoPPYwejBxlArbKjR7viH6LZknM2bovu+XPKvaHSjspsaZKM7A22l1BqwpgaGBQ+kAd9Byp0oaqKrmH5dcGBmso8noHEQX6vlR5Smpe/sCPOV9XIQ4EJbsbioFzXuBXE+edU8U3sKip06C08mAYSyuibmOM7R4+OegruG0Jptjg/WOFj3Mn0wNJFWZtl8cpuiEvEGlFIzCq5NRB/CAXmArdI3ahZ9vdqdRkxwb36rQgvKXG9CaHmk1C86L39fHlB9s5uxuJC6At1rNiUKCLWg0ohdOtW08J9ufkf6zZu2NvDZae/zA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector9901; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=6FhtfdJO4D9jlL2lnHUenV9S3dZN3wvSNiOT4tZknA8=; b=KseNHkXsF95ozpJ9PzktszlMK8zPUl8gLwA6x6DEXbpr+DztaftExJRKp+uER+otHh2qWVmI7Q4tDUcE6FBv59ENXS6ZU0zazA6FE3Q7vC8/EJjWPI3X3zVQKia8c3+h/iM9UpoftQhLDl1sBhu5QQSU/begqrGJOYEzdESThRY1uh/ReUczOhe7uMxguYYgWKbibk6E8xOiiYHmd1PrIEO6OjnIfrwSmIPDsoU6HqXkoIaHTdlHX3M0kfUwp73tIJebWKZMrEq6iBKt5jU9vf4LYLjzE90ABBkBxK0Y1AypyJh0Vrf5dFPcb2tUozTFDZwIjk01UtZKvR///SwK5A== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=bu.edu; dmarc=pass action=none header.from=bu.edu; dkim=pass header.d=bu.edu; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=bushare.onmicrosoft.com; s=selector2-bushare-onmicrosoft-com; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=6FhtfdJO4D9jlL2lnHUenV9S3dZN3wvSNiOT4tZknA8=; b=Mpa4LUUYHBis2WpqL94E4xItW6Mc6IqlLrupGIcyZTJY0rE+kSiL4OSDhnCf1TUkXg+wa219twnRC+dp1A5xFxryKFUl+OIdY7IxAViVVF2fy7Lakx14mkXi9wh6jBda+C4iKtPW0XXCGAhZTRsl/x3z442ePvEQvwyXtt4YRE0= Authentication-Results: nongnu.org; dkim=none (message not signed) header.d=none;nongnu.org; dmarc=none action=none header.from=bu.edu; Received: from SN6PR03MB3871.namprd03.prod.outlook.com (2603:10b6:805:6d::32) by SN2PR03MB2237.namprd03.prod.outlook.com (2603:10b6:804:e::27) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.3391.11; Mon, 21 Sep 2020 02:25:23 +0000 Received: from SN6PR03MB3871.namprd03.prod.outlook.com ([fe80::61ae:93a8:b26c:77b8]) by SN6PR03MB3871.namprd03.prod.outlook.com ([fe80::61ae:93a8:b26c:77b8%4]) with mapi id 15.20.3391.024; Mon, 21 Sep 2020 02:25:22 +0000 From: Alexander Bulekov To: qemu-devel@nongnu.org Subject: [PATCH v3 02/16] fuzz: Add general virtual-device fuzzer Date: Sun, 20 Sep 2020 22:24:52 -0400 Message-Id: <20200921022506.873303-3-alxndr@bu.edu> X-Mailer: git-send-email 2.28.0 In-Reply-To: <20200921022506.873303-1-alxndr@bu.edu> References: <20200921022506.873303-1-alxndr@bu.edu> Content-Transfer-Encoding: 8bit Content-Type: text/plain X-ClientProxiedBy: BL0PR1501CA0034.namprd15.prod.outlook.com (2603:10b6:207:17::47) To SN6PR03MB3871.namprd03.prod.outlook.com (2603:10b6:805:6d::32) MIME-Version: 1.0 X-MS-Exchange-MessageSentRepresentingType: 1 Received: from stormtrooper.vrmnet (72.93.72.163) by BL0PR1501CA0034.namprd15.prod.outlook.com (2603:10b6:207:17::47) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.3391.14 via Frontend Transport; Mon, 21 Sep 2020 02:25:20 +0000 X-Mailer: git-send-email 2.28.0 X-Originating-IP: [72.93.72.163] X-MS-PublicTrafficType: Email X-MS-Office365-Filtering-Correlation-Id: 8bb5964f-6fde-4d59-f36e-08d85dd596b4 X-MS-TrafficTypeDiagnostic: SN2PR03MB2237: X-MS-Exchange-Transport-Forked: True X-Microsoft-Antispam-PRVS: X-MS-Oob-TLC-OOBClassifiers: OLM:849; X-MS-Exchange-SenderADCheck: 1 X-Microsoft-Antispam: BCL:0; X-Microsoft-Antispam-Message-Info: 17GJm4m0dmJJhq8wtzoZTQsQMcZowdUz8L/h1ItjbDljaANUOrNRDBsf1ksvAbL/RLiPu8viDyKwZ0H/XnYIb3S3zLweUqd85Gn+Y3nJogNOxQNdyNh3ZL/bxgV8/5YBp0ZVcdfMg5RXeYglKg6UvjJbFNmW5V2bEdWIKk1ZVISruF8YKdrZpdvXMe/eOW1X3YXbokGgw85tYXdsxf5jM1yR1y/wXEWeHjraqE/Aio2nBX8fvCbLR2vtAz+MAz6ZGhRCIEHcAPeVF7F7XeEc2yxgBEijJfXVW/EPltIKELQMm9I+nCQW4DYTyf6SvkKh/XdO7t379IspXyy7iaP+BFHOPHiBr8R0csCdvUjwKEadMyo4JXEjG0b1I9+yFWTSEu+4AsPKjtUuwCN//ruDnxP1dZT6qdi9C81M8Fs1K4P9LdSmNuginskXwSdY+TiydMZOXjxlEZoCMZJOXi7aJQ== X-Forefront-Antispam-Report: CIP:255.255.255.255; CTRY:; LANG:en; SCL:1; SRV:; IPV:NLI; SFV:NSPM; H:SN6PR03MB3871.namprd03.prod.outlook.com; PTR:; CAT:NONE; SFS:(4636009)(396003)(366004)(376002)(136003)(346002)(39860400002)(2616005)(956004)(4326008)(54906003)(83380400001)(26005)(478600001)(16526019)(6666004)(8936002)(316002)(966005)(6486002)(66476007)(1076003)(6512007)(186003)(6916009)(86362001)(66946007)(5660300002)(36756003)(75432002)(2906002)(6506007)(8676002)(30864003)(66556008)(52116002)(786003); DIR:OUT; SFP:1102; X-MS-Exchange-AntiSpam-MessageData: pv6WNUCbHY/DWHlE9z+/FhOaRxHJ8zx8aZwJ92vvlys87hUcPYubguD27o1udbFRc4IBMZWIxZvwSnDOij/DNmLdnHidJ5fSceHfeSuAbsHZCf+IsrNeJzxmDaRThYWNjMXukxuMjksy7BK/4MsQcENHv4Tc0JPtmXeSt56iDyi2VDN1ywQb3tWfP4j/r0ATgKQKD7SWpfQSxhT46Tj2z2mWXmf4pRCuYit2YAMb9QV2kWiam6ZzurOFp/X0knljtAQZRUGR+ZnB/hDtkJcgpXOT/0rQmlS/cXMtuOxlIf/rnBmzODQquo2ufLh+d+KkiRKMf345FeUlLzLrOhtB8vRN9FeeuTKTzX73+N6xVB75n3gwQGkXZMnbMmUXHuS2ElN52iuTZzOGQlFPPMCAcS5Muw4NL2dD1su+kmAMoSiM4A2Ap2HR72Bvr3vS2cJnNTcqvLceeO9nZkTb3AB1KCD21dL7WPtY8TclOj1lvOboLY1Dke1xXlEu15ayruy7eukb0iRWH9fVl0RTQXdbvYj6OL5pv/Kj2w/FQ1purQox5w0IkAH3lYiv2VVDbtEcAsDNA+KUNTeX8js4i3KxhDMInW+NPKK5cMINp0rP95ADebqYtWkiVz/axTMGXS0TkrJnYGgvfCp35y9d8PFfeg== X-OriginatorOrg: bu.edu X-MS-Exchange-CrossTenant-Network-Message-Id: 8bb5964f-6fde-4d59-f36e-08d85dd596b4 X-MS-Exchange-CrossTenant-AuthSource: SN6PR03MB3871.namprd03.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 21 Sep 2020 02:25:22.1177 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: d57d32cc-c121-488f-b07b-dfe705680c71 X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: 0cm2IDjdKu1c1mPpCPadSx19DMwAw+Eglcd6QoOfKLAetzF1Z8e5HBJdDA/Rrg4x X-MS-Exchange-Transport-CrossTenantHeadersStamped: SN2PR03MB2237 Received-SPF: pass client-ip=40.107.93.102; envelope-from=alxndr@bu.edu; helo=NAM10-DM6-obe.outbound.protection.outlook.com X-detected-operating-system: by eggs.gnu.org: First seen = 2020/09/20 22:25:33 X-ACL-Warn: Detected OS = Windows NT kernel [generic] [fuzzy] X-Spam_score_int: -18 X-Spam_score: -1.9 X-Spam_bar: - X-Spam_report: (-1.9 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, HK_RANDOM_ENVFROM=0.001, HK_RANDOM_FROM=0.001, MSGID_FROM_MTA_HEADER=0.001, RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H2=-0.001, SPF_HELO_PASS=-0.001, SPF_PASS=-0.001 autolearn=no autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.23 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Laurent Vivier , Thomas Huth , Alexander Bulekov , darren.kenny@oracle.com, bsd@redhat.com, stefanha@redhat.com, Paolo Bonzini , philmd@redhat.com Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: "Qemu-devel" This is a generic fuzzer designed to fuzz a virtual device's MemoryRegions, as long as they exist within the Memory or Port IO (if it exists) AddressSpaces. The fuzzer's input is interpreted into a sequence of qtest commands (outb, readw, etc). The interpreted commands are separated by a magic seaparator, which should be easy for the fuzzer to guess. Without ASan, the separator can be specified as a "dictionary value" using the -dict argument (see libFuzzer documentation). Signed-off-by: Alexander Bulekov --- tests/qtest/fuzz/general_fuzz.c | 498 ++++++++++++++++++++++++++++++++ tests/qtest/fuzz/meson.build | 1 + 2 files changed, 499 insertions(+) create mode 100644 tests/qtest/fuzz/general_fuzz.c diff --git a/tests/qtest/fuzz/general_fuzz.c b/tests/qtest/fuzz/general_fuzz.c new file mode 100644 index 0000000000..bf75b215ca --- /dev/null +++ b/tests/qtest/fuzz/general_fuzz.c @@ -0,0 +1,498 @@ +/* + * General Virtual-Device Fuzzing Target + * + * Copyright Red Hat Inc., 2020 + * + * Authors: + * Alexander Bulekov + * + * 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 + +#include "hw/core/cpu.h" +#include "tests/qtest/libqos/libqtest.h" +#include "fuzz.h" +#include "fork_fuzz.h" +#include "exec/address-spaces.h" +#include "string.h" +#include "exec/memory.h" +#include "exec/ramblock.h" +#include "exec/address-spaces.h" +#include "hw/qdev-core.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_CLOCK_STEP, +}; + +#define DEFAULT_TIMEOUT_US 100000 +#define USEC_IN_SEC 100000000 + +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 = 100000; + +static bool qtest_log_enabled; + +/* + * List of memory regions that are children of QOM objects specified by the + * user for fuzzing. + */ +static GHashTable *fuzzable_memoryregions; + +struct get_io_cb_info { + int index; + int found; + address_range result; +}; + +static int get_io_address_cb(ram_addr_t start, ram_addr_t size, + const MemoryRegion *mr, void *opaque) { + struct get_io_cb_info *info = opaque; + if (g_hash_table_lookup(fuzzable_memoryregions, mr)) { + if (info->index == 0) { + info->result.addr = start; + info->result.size = size; + info->found = 1; + return 1; + } + info->index--; + } + return 0; +} + +/* + * 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; + 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_clock_step(QTestState *s, const unsigned char *data, size_t len) +{ + qtest_clock_step_next(s); +} + +static void handle_timeout(int sig) +{ + if (qtest_log_enabled) { + fprintf(stderr, "[Timeout]\n"); + fflush(stderr); + } + _Exit(0); +} + +/* + * Here, we interpret random bytes from the fuzzer, as a sequence of commands. + * Our commands are variable-width, so we use a separator, SEPARATOR, to specify + * the boundaries between commands. This is just a random 32-bit value, which + * is easily identified by libfuzzer+AddressSanitizer, as long as we use + * memmem. It can also be included in the fuzzer's dictionary. More details + * here: + * https://github.com/google/fuzzing/blob/master/docs/split-inputs.md + * + * 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 general_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_CLOCK_STEP] = op_clock_step, + }; + const unsigned char *cmd = Data; + const unsigned char *nextcmd; + size_t cmd_len; + uint8_t op; + + if (fork() == 0) { + /* + * 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 to avoid hurting performance, too much + */ + if (timeout) { + struct sigaction sact; + struct itimerval timer; + + sigemptyset(&sact.sa_mask); + sact.sa_flags = SA_NODEFER; + sact.sa_handler = handle_timeout; + sigaction(SIGALRM, &sact, NULL); + + memset(&timer, 0, sizeof(timer)); + timer.it_value.tv_sec = timeout / USEC_IN_SEC; + timer.it_value.tv_usec = timeout % USEC_IN_SEC; + setitimer(ITIMER_VIRTUAL, &timer, NULL); + } + + while (cmd && Size) { + /* 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); + } + _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_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) || + memory_region_is_romd(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) +{ + char *pattern = opaque; + if (g_pattern_match_simple(pattern, object_get_typename(child))) { + /* Find and save ptrs to any child MemoryRegions */ + object_child_foreach_recursive(child, locate_fuzz_memory_regions, NULL); + + } else if (object_dynamic_cast(OBJECT(child), TYPE_MEMORY_REGION)) { + if (g_pattern_match_simple(pattern, + object_get_canonical_path_component(child))) { + MemoryRegion *mr; + mr = MEMORY_REGION(child); + if ((memory_region_is_ram(mr) || + memory_region_is_ram_device(mr) || + memory_region_is_rom(mr) || + memory_region_is_romd(mr)) == false) { + g_hash_table_insert(fuzzable_memoryregions, mr, (gpointer)true); + } + } + } + return 0; +} + +static void general_pre_fuzz(QTestState *s) +{ + GHashTableIter iter; + MemoryRegion *mr; + char **result; + + if (!getenv("QEMU_FUZZ_OBJECTS")) { + usage(); + } + if (getenv("QTEST_LOG")) { + qtest_log_enabled = 1; + } + if (getenv("QEMU_FUZZ_TIMEOUT")) { + timeout = g_ascii_strtoll(getenv("QEMU_FUZZ_TIMEOUT"), NULL, 0); + } + + fuzzable_memoryregions = g_hash_table_new(NULL, NULL); + + result = g_strsplit(getenv("QEMU_FUZZ_OBJECTS"), " ", -1); + for (int i = 0; result[i] != NULL; i++) { + printf("Matching objects by name %s\n", result[i]); + object_child_foreach_recursive(qdev_get_machine(), + locate_fuzz_objects, + result[i]); + } + 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 %lx)\n", + object_get_canonical_path_component(&(mr->parent_obj)), + mr->addr); + } + + if (!g_hash_table_size(fuzzable_memoryregions)) { + printf("No fuzzable memory regions found...\n"); + exit(1); + } + + counter_shm_init(); +} +static GString *general_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 64 %s ", getenv("QEMU_FUZZ_ARGS")); + return cmd_line; +} + +static void register_general_fuzz_targets(void) +{ + fuzz_add_target(&(FuzzTarget){ + .name = "general-fuzz", + .description = "Fuzz based on any qemu command-line args. ", + .get_init_cmdline = general_fuzz_cmdline, + .pre_fuzz = general_pre_fuzz, + .fuzz = general_fuzz}); +} + +fuzz_target_init(register_general_fuzz_targets); diff --git a/tests/qtest/fuzz/meson.build b/tests/qtest/fuzz/meson.build index b31ace7d5a..a59de6aa8c 100644 --- a/tests/qtest/fuzz/meson.build +++ b/tests/qtest/fuzz/meson.build @@ -5,6 +5,7 @@ specific_fuzz_ss.add(files('fuzz.c', 'fork_fuzz.c', 'qos_fuzz.c', 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(files('general_fuzz.c')) fork_fuzz = declare_dependency( link_args: config_host['FUZZ_EXE_LDFLAGS'].split() + -- 2.28.0