84 lines · cpp
1//===-- lldb-target-fuzzer.cpp --------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "utils/TempFile.h"10 11#include "Plugins/Platform/Linux/PlatformLinux.h"12#include "lldb/Core/Debugger.h"13#include "lldb/Core/Value.h"14#include "lldb/Expression/DWARFExpression.h"15#include "lldb/Host/FileSystem.h"16#include "lldb/Host/HostInfo.h"17#include "lldb/Target/Target.h"18 19using namespace lldb;20using namespace lldb_private;21using namespace lldb_private::plugin::dwarf;22using namespace lldb_fuzzer;23 24extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {25 FileSystem::Initialize();26 HostInfo::Initialize();27 platform_linux::PlatformLinux::Initialize();28 return 0;29}30 31static void Evaluate(llvm::ArrayRef<uint8_t> expr,32 lldb::ModuleSP module_sp = {}, DWARFUnit *unit = nullptr,33 ExecutionContext *exe_ctx = nullptr) {34 DataExtractor extractor(expr.data(), expr.size(), lldb::eByteOrderLittle,35 /*addr_size*/ 4);36 37 llvm::Expected<Value> result =38 DWARFExpression::Evaluate(exe_ctx, /*reg_ctx*/ nullptr, module_sp,39 extractor, unit, lldb::eRegisterKindLLDB,40 /*initial_value_ptr*/ nullptr,41 /*object_address_ptr*/ nullptr);42 43 if (!result)44 llvm::consumeError(result.takeError());45}46 47class MockTarget : public Target {48public:49 MockTarget(Debugger &debugger, const ArchSpec &target_arch,50 const lldb::PlatformSP &platform_sp, llvm::ArrayRef<uint8_t> data)51 : Target(debugger, target_arch, platform_sp, true), m_data(data) {}52 53 size_t ReadMemory(const Address &addr, void *dst, size_t dst_len,54 Status &error, bool force_live_memory = false,55 lldb::addr_t *load_addr_ptr = nullptr) override {56 std::memcpy(dst, m_data.data(), m_data.size());57 return m_data.size();58 }59 60private:61 llvm::ArrayRef<uint8_t> m_data;62};63 64extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {65 // We're going to use the first half of the input data as the DWARF expression66 // and the second half as memory.67 const size_t partition = size / 2;68 llvm::ArrayRef expression_data(data, partition);69 llvm::ArrayRef memory_data(data + partition, size - partition);70 71 // Create a mock target for reading memory.72 ArchSpec arch("i386-pc-linux");73 Platform::SetHostPlatform(74 platform_linux::PlatformLinux::CreateInstance(true, &arch));75 lldb::DebuggerSP debugger_sp = Debugger::CreateInstance();76 lldb::PlatformSP platform_sp;77 auto target_sp = std::make_shared<MockTarget>(*debugger_sp, arch, platform_sp,78 memory_data);79 ExecutionContext exe_ctx(static_cast<lldb::TargetSP>(target_sp), false);80 81 Evaluate(expression_data);82 return 0;83}84