316 lines · cpp
1//===-- llvm-mc-assemble-fuzzer.cpp - Fuzzer for the MC layer -------------===//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//===----------------------------------------------------------------------===//10 11#include "llvm-c/Target.h"12#include "llvm/MC/MCAsmBackend.h"13#include "llvm/MC/MCAsmInfo.h"14#include "llvm/MC/MCCodeEmitter.h"15#include "llvm/MC/MCContext.h"16#include "llvm/MC/MCInstPrinter.h"17#include "llvm/MC/MCInstrInfo.h"18#include "llvm/MC/MCObjectFileInfo.h"19#include "llvm/MC/MCObjectWriter.h"20#include "llvm/MC/MCParser/AsmLexer.h"21#include "llvm/MC/MCParser/MCTargetAsmParser.h"22#include "llvm/MC/MCRegisterInfo.h"23#include "llvm/MC/MCSectionMachO.h"24#include "llvm/MC/MCStreamer.h"25#include "llvm/MC/MCSubtargetInfo.h"26#include "llvm/MC/MCTargetOptionsCommandFlags.h"27#include "llvm/MC/TargetRegistry.h"28#include "llvm/Support/CommandLine.h"29#include "llvm/Support/FileUtilities.h"30#include "llvm/Support/MemoryBuffer.h"31#include "llvm/Support/SourceMgr.h"32#include "llvm/Support/TargetSelect.h"33#include "llvm/Support/ToolOutputFile.h"34#include "llvm/Support/VirtualFileSystem.h"35#include "llvm/Support/raw_ostream.h"36#include "llvm/TargetParser/Host.h"37#include "llvm/TargetParser/SubtargetFeature.h"38 39using namespace llvm;40 41static mc::RegisterMCTargetOptionsFlags MOF;42 43static cl::opt<std::string>44 TripleName("triple", cl::desc("Target triple to assemble for, "45 "see -version for available targets"));46 47static cl::opt<std::string>48 MCPU("mcpu",49 cl::desc("Target a specific cpu type (-mcpu=help for details)"),50 cl::value_desc("cpu-name"), cl::init(""));51 52// This is useful for variable-length instruction sets.53static cl::opt<unsigned> InsnLimit(54 "insn-limit",55 cl::desc("Limit the number of instructions to process (0 for no limit)"),56 cl::value_desc("count"), cl::init(0));57 58static cl::list<std::string>59 MAttrs("mattr", cl::CommaSeparated,60 cl::desc("Target specific attributes (-mattr=help for details)"),61 cl::value_desc("a1,+a2,-a3,..."));62// The feature string derived from -mattr's values.63std::string FeaturesStr;64 65static cl::list<std::string>66 FuzzerArgs("fuzzer-args", cl::Positional,67 cl::desc("Options to pass to the fuzzer"),68 cl::PositionalEatsArgs);69static std::vector<char *> ModifiedArgv;70 71enum OutputFileType {72 OFT_Null,73 OFT_AssemblyFile,74 OFT_ObjectFile75};76static cl::opt<OutputFileType>77FileType("filetype", cl::init(OFT_AssemblyFile),78 cl::desc("Choose an output file type:"),79 cl::values(80 clEnumValN(OFT_AssemblyFile, "asm",81 "Emit an assembly ('.s') file"),82 clEnumValN(OFT_Null, "null",83 "Don't emit anything (for timing purposes)"),84 clEnumValN(OFT_ObjectFile, "obj",85 "Emit a native object ('.o') file")));86 87 88class LLVMFuzzerInputBuffer : public MemoryBuffer89{90 public:91 LLVMFuzzerInputBuffer(const uint8_t *data_, size_t size_)92 : Data(reinterpret_cast<const char *>(data_)),93 Size(size_) {94 init(Data, Data+Size, false);95 }96 97 98 virtual BufferKind getBufferKind() const {99 return MemoryBuffer_Malloc; // it's not disk-backed so I think that's100 // the intent ... though AFAIK it101 // probably came from an mmap or sbrk102 }103 104 private:105 const char *Data;106 size_t Size;107};108 109static int AssembleInput(const char *ProgName, const Target *TheTarget,110 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,111 MCAsmInfo &MAI, MCSubtargetInfo &STI,112 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {113 static const bool NoInitialTextSection = false;114 115 std::unique_ptr<MCAsmParser> Parser(116 createMCAsmParser(SrcMgr, Ctx, Str, MAI));117 118 std::unique_ptr<MCTargetAsmParser> TAP(119 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));120 121 if (!TAP) {122 errs() << ProgName123 << ": error: this target '" << TripleName124 << "', does not support assembly parsing.\n";125 abort();126 }127 128 Parser->setTargetParser(*TAP);129 130 return Parser->Run(NoInitialTextSection);131}132 133 134int AssembleOneInput(const uint8_t *Data, size_t Size) {135 Triple TheTriple(Triple::normalize(TripleName));136 137 SourceMgr SrcMgr;138 139 std::unique_ptr<MemoryBuffer> BufferPtr(new LLVMFuzzerInputBuffer(Data, Size));140 141 // Tell SrcMgr about this buffer, which is what the parser will pick up.142 SrcMgr.AddNewSourceBuffer(std::move(BufferPtr), SMLoc());143 144 static const std::vector<std::string> NoIncludeDirs;145 SrcMgr.setIncludeDirs(NoIncludeDirs);146 SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem());147 148 static std::string ArchName;149 std::string Error;150 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,151 Error);152 if (!TheTarget) {153 errs() << "error: this target '" << TheTriple.normalize()154 << "/" << ArchName << "', was not found: '" << Error << "'\n";155 156 abort();157 }158 159 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));160 if (!MRI) {161 errs() << "Unable to create target register info!\n";162 abort();163 }164 165 MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();166 std::unique_ptr<MCAsmInfo> MAI(167 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));168 if (!MAI) {169 errs() << "Unable to create target asm info!\n";170 abort();171 }172 173 std::unique_ptr<MCSubtargetInfo> STI(174 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));175 if (!STI) {176 errs() << "Unable to create subtargettarget info!\n";177 abort();178 }179 180 MCContext Ctx(TheTriple, MAI.get(), MRI.get(), STI.get(), &SrcMgr);181 std::unique_ptr<MCObjectFileInfo> MOFI(182 TheTarget->createMCObjectFileInfo(Ctx, /*PIC=*/false));183 Ctx.setObjectFileInfo(MOFI.get());184 185 const unsigned OutputAsmVariant = 0;186 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());187 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(188 Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI));189 if (!IP) {190 errs()191 << "error: unable to create instruction printer for target triple '"192 << TheTriple.normalize() << "' with assembly variant "193 << OutputAsmVariant << ".\n";194 195 abort();196 }197 198 const char *ProgName = "llvm-mc-fuzzer";199 std::unique_ptr<MCCodeEmitter> CE = nullptr;200 std::unique_ptr<MCAsmBackend> MAB = nullptr;201 202 std::string OutputString;203 raw_string_ostream Out(OutputString);204 auto FOut = std::make_unique<formatted_raw_ostream>(Out);205 206 std::unique_ptr<MCStreamer> Str;207 208 if (FileType == OFT_AssemblyFile) {209 Str.reset(TheTarget->createAsmStreamer(Ctx, std::move(FOut), std::move(IP),210 std::move(CE), std::move(MAB)));211 } else {212 assert(FileType == OFT_ObjectFile && "Invalid file type!");213 214 std::error_code EC;215 const std::string OutputFilename = "-";216 auto Out =217 std::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::OF_None);218 if (EC) {219 errs() << EC.message() << '\n';220 abort();221 }222 223 // Don't waste memory on names of temp labels.224 Ctx.setUseNamesOnTempLabels(false);225 226 std::unique_ptr<buffer_ostream> BOS;227 raw_pwrite_stream *OS = &Out->os();228 if (!Out->os().supportsSeeking()) {229 BOS = std::make_unique<buffer_ostream>(Out->os());230 OS = BOS.get();231 }232 233 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, Ctx);234 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);235 Str.reset(TheTarget->createMCObjectStreamer(236 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB),237 MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(CE),238 *STI));239 }240 const int Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,241 *MCII, MCOptions);242 243 (void) Res;244 245 return 0;246}247 248extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {249 return AssembleOneInput(Data, Size);250}251 252extern "C" LLVM_ATTRIBUTE_USED int LLVMFuzzerInitialize(int *argc,253 char ***argv) {254 // The command line is unusual compared to other fuzzers due to the need to255 // specify the target. Options like -triple, -mcpu, and -mattr work like256 // their counterparts in llvm-mc, while -fuzzer-args collects options for the257 // fuzzer itself.258 //259 // Examples:260 //261 // Fuzz the big-endian MIPS32R6 disassembler using 100,000 inputs of up to262 // 4-bytes each and use the contents of ./corpus as the test corpus:263 // llvm-mc-fuzzer -triple mips-linux-gnu -mcpu=mips32r6 -disassemble \264 // -fuzzer-args -max_len=4 -runs=100000 ./corpus265 //266 // Infinitely fuzz the little-endian MIPS64R2 disassembler with the MSA267 // feature enabled using up to 64-byte inputs:268 // llvm-mc-fuzzer -triple mipsel-linux-gnu -mcpu=mips64r2 -mattr=msa \269 // -disassemble -fuzzer-args ./corpus270 //271 // If your aim is to find instructions that are not tested, then it is272 // advisable to constrain the maximum input size to a single instruction273 // using -max_len as in the first example. This results in a test corpus of274 // individual instructions that test unique paths. Without this constraint,275 // there will be considerable redundancy in the corpus.276 277 char **OriginalArgv = *argv;278 279 LLVMInitializeAllTargetInfos();280 LLVMInitializeAllTargetMCs();281 LLVMInitializeAllAsmParsers();282 283 cl::ParseCommandLineOptions(*argc, OriginalArgv);284 285 // Rebuild the argv without the arguments llvm-mc-fuzzer consumed so that286 // the driver can parse its arguments.287 //288 // FuzzerArgs cannot provide the non-const pointer that OriginalArgv needs.289 // Re-use the strings from OriginalArgv instead of copying FuzzerArg to a290 // non-const buffer to avoid the need to clean up when the fuzzer terminates.291 ModifiedArgv.push_back(OriginalArgv[0]);292 for (const auto &FuzzerArg : FuzzerArgs) {293 for (int i = 1; i < *argc; ++i) {294 if (FuzzerArg == OriginalArgv[i])295 ModifiedArgv.push_back(OriginalArgv[i]);296 }297 }298 *argc = ModifiedArgv.size();299 *argv = ModifiedArgv.data();300 301 // Package up features to be passed to target/subtarget302 // We have to pass it via a global since the callback doesn't303 // permit any user data.304 if (MAttrs.size()) {305 SubtargetFeatures Features;306 for (unsigned i = 0; i != MAttrs.size(); ++i)307 Features.AddFeature(MAttrs[i]);308 FeaturesStr = Features.getString();309 }310 311 if (TripleName.empty())312 TripleName = sys::getDefaultTargetTriple();313 314 return 0;315}316