| 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-exception |
| 6 |
// |
| 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 |
|
| 39 |
using namespace llvm; |
| 40 |
|
| 41 |
static mc::RegisterMCTargetOptionsFlags MOF; |
| 42 |
|
| 43 |
static cl::opt<std::string> |
| 44 |
TripleName("triple", cl::desc("Target triple to assemble for, " |
| 45 |
"see -version for available targets")); |
| 46 |
|
| 47 |
static 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. |
| 53 |
static 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 |
|
| 58 |
static 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. |
| 63 |
std::string FeaturesStr; |
| 64 |
|
| 65 |
static cl::list<std::string> |
| 66 |
FuzzerArgs("fuzzer-args", cl::Positional, |
| 67 |
cl::desc("Options to pass to the fuzzer"), |
| 68 |
cl::PositionalEatsArgs); |
| 69 |
static std::vector<char *> ModifiedArgv; |
| 70 |
|
| 71 |
enum OutputFileType { |
| 72 |
OFT_Null, |
| 73 |
OFT_AssemblyFile, |
| 74 |
OFT_ObjectFile |
| 75 |
}; |
| 76 |
static cl::opt<OutputFileType> |
| 77 |
FileType("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 |
|
| 88 |
class LLVMFuzzerInputBuffer : public MemoryBuffer |
| 89 |
{ |
| 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 |
virtual BufferKind getBufferKind() const override { |
| 98 |
return MemoryBuffer_Malloc; // it's not disk-backed so I think that's |
| 99 |
// the intent ... though AFAIK it |
| 100 |
// probably came from an mmap or sbrk |
| 101 |
} |
| 102 |
|
| 103 |
private: |
| 104 |
const char *Data; |
| 105 |
size_t Size; |
| 106 |
}; |
| 107 |
|
| 108 |
static int AssembleInput(const char *ProgName, const Target *TheTarget, |
| 109 |
SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str, |
| 110 |
MCAsmInfo &MAI, MCSubtargetInfo &STI, |
| 111 |
MCInstrInfo &MCII, MCTargetOptions &MCOptions) { |
| 112 |
static const bool NoInitialTextSection = false; |
| 113 |
|
| 114 |
std::unique_ptr<MCAsmParser> Parser( |
| 115 |
createMCAsmParser(SrcMgr, Ctx, Str, MAI)); |
| 116 |
|
| 117 |
std::unique_ptr<MCTargetAsmParser> TAP( |
| 118 |
TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions)); |
| 119 |
|
| 120 |
if (!TAP) { |
| 121 |
errs() << ProgName |
| 122 |
<< ": error: this target '" << TripleName |
| 123 |
<< "', does not support assembly parsing.\n"; |
| 124 |
abort(); |
| 125 |
} |
| 126 |
|
| 127 |
Parser->setTargetParser(*TAP); |
| 128 |
|
| 129 |
return Parser->Run(NoInitialTextSection); |
| 130 |
} |
| 131 |
|
| 132 |
|
| 133 |
int AssembleOneInput(const uint8_t *Data, size_t Size) { |
| 134 |
Triple TheTriple(Triple::normalize(TripleName)); |
| 135 |
|
| 136 |
SourceMgr SrcMgr; |
| 137 |
|
| 138 |
std::unique_ptr<MemoryBuffer> BufferPtr(new LLVMFuzzerInputBuffer(Data, Size)); |
| 139 |
|
| 140 |
// Tell SrcMgr about this buffer, which is what the parser will pick up. |
| 141 |
SrcMgr.AddNewSourceBuffer(std::move(BufferPtr), SMLoc()); |
| 142 |
|
| 143 |
static const std::vector<std::string> NoIncludeDirs; |
| 144 |
SrcMgr.setIncludeDirs(NoIncludeDirs); |
| 145 |
SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem()); |
| 146 |
|
| 147 |
static std::string ArchName; |
| 148 |
std::string Error; |
| 149 |
const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, |
| 150 |
Error); |
| 151 |
if (!TheTarget) { |
| 152 |
errs() << "error: this target '" << TheTriple.normalize() |
| 153 |
<< "/" << ArchName << "', was not found: '" << Error << "'\n"; |
| 154 |
|
| 155 |
abort(); |
| 156 |
} |
| 157 |
|
| 158 |
std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName)); |
| 159 |
if (!MRI) { |
| 160 |
errs() << "Unable to create target register info!\n"; |
| 161 |
abort(); |
| 162 |
} |
| 163 |
|
| 164 |
MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags(); |
| 165 |
std::unique_ptr<MCAsmInfo> MAI( |
| 166 |
TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); |
| 167 |
if (!MAI) { |
| 168 |
errs() << "Unable to create target asm info!\n"; |
| 169 |
abort(); |
| 170 |
} |
| 171 |
|
| 172 |
std::unique_ptr<MCSubtargetInfo> STI( |
| 173 |
TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr)); |
| 174 |
if (!STI) { |
| 175 |
errs() << "Unable to create subtargettarget info!\n"; |
| 176 |
abort(); |
| 177 |
} |
| 178 |
|
| 179 |
MCContext Ctx(TheTriple, MAI.get(), MRI.get(), STI.get(), &SrcMgr); |
| 180 |
std::unique_ptr<MCObjectFileInfo> MOFI( |
| 181 |
TheTarget->createMCObjectFileInfo(Ctx, /*PIC=*/false)); |
| 182 |
Ctx.setObjectFileInfo(MOFI.get()); |
| 183 |
|
| 184 |
const unsigned OutputAsmVariant = 0; |
| 185 |
std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); |
| 186 |
std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( |
| 187 |
Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI)); |
| 188 |
if (!IP) { |
| 189 |
errs() |
| 190 |
<< "error: unable to create instruction printer for target triple '" |
| 191 |
<< TheTriple.normalize() << "' with assembly variant " |
| 192 |
<< OutputAsmVariant << ".\n"; |
| 193 |
|
| 194 |
abort(); |
| 195 |
} |
| 196 |
|
| 197 |
const char *ProgName = "llvm-mc-fuzzer"; |
| 198 |
std::unique_ptr<MCCodeEmitter> CE = nullptr; |
| 199 |
std::unique_ptr<MCAsmBackend> MAB = nullptr; |
| 200 |
|
| 201 |
std::string OutputString; |
| 202 |
raw_string_ostream Out(OutputString); |
| 203 |
auto FOut = std::make_unique<formatted_raw_ostream>(Out); |
| 204 |
|
| 205 |
std::unique_ptr<MCStreamer> Str; |
| 206 |
|
| 207 |
if (FileType == OFT_AssemblyFile) { |
| 208 |
Str.reset(TheTarget->createAsmStreamer(Ctx, std::move(FOut), std::move(IP), |
| 209 |
std::move(CE), std::move(MAB))); |
| 210 |
} else { |
| 211 |
assert(FileType == OFT_ObjectFile && "Invalid file type!"); |
| 212 |
|
| 213 |
std::error_code EC; |
| 214 |
const std::string OutputFilename = "-"; |
| 215 |
auto Out = |
| 216 |
std::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::OF_None); |
| 217 |
if (EC) { |
| 218 |
errs() << EC.message() << '\n'; |
| 219 |
abort(); |
| 220 |
} |
| 221 |
|
| 222 |
// Don't waste memory on names of temp labels. |
| 223 |
Ctx.setUseNamesOnTempLabels(false); |
| 224 |
|
| 225 |
std::unique_ptr<buffer_ostream> BOS; |
| 226 |
raw_pwrite_stream *OS = &Out->os(); |
| 227 |
if (!Out->os().supportsSeeking()) { |
| 228 |
BOS = std::make_unique<buffer_ostream>(Out->os()); |
| 229 |
OS = BOS.get(); |
| 230 |
} |
| 231 |
|
| 232 |
MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, Ctx); |
| 233 |
MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions); |
| 234 |
Str.reset(TheTarget->createMCObjectStreamer( |
| 235 |
TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB), |
| 236 |
MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(CE), |
| 237 |
*STI)); |
| 238 |
} |
| 239 |
const int Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI, |
| 240 |
*MCII, MCOptions); |
| 241 |
|
| 242 |
(void) Res; |
| 243 |
|
| 244 |
return 0; |
| 245 |
} |
| 246 |
|
| 247 |
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { |
| 248 |
return AssembleOneInput(Data, Size); |
| 249 |
} |
| 250 |
|
| 251 |
extern "C" LLVM_ATTRIBUTE_USED int LLVMFuzzerInitialize(int *argc, |
| 252 |
char ***argv) { |
| 253 |
// The command line is unusual compared to other fuzzers due to the need to |
| 254 |
// specify the target. Options like -triple, -mcpu, and -mattr work like |
| 255 |
// their counterparts in llvm-mc, while -fuzzer-args collects options for the |
| 256 |
// fuzzer itself. |
| 257 |
// |
| 258 |
// Examples: |
| 259 |
// |
| 260 |
// Fuzz the big-endian MIPS32R6 disassembler using 100,000 inputs of up to |
| 261 |
// 4-bytes each and use the contents of ./corpus as the test corpus: |
| 262 |
// llvm-mc-fuzzer -triple mips-linux-gnu -mcpu=mips32r6 -disassemble \ |
| 263 |
// -fuzzer-args -max_len=4 -runs=100000 ./corpus |
| 264 |
// |
| 265 |
// Infinitely fuzz the little-endian MIPS64R2 disassembler with the MSA |
| 266 |
// feature enabled using up to 64-byte inputs: |
| 267 |
// llvm-mc-fuzzer -triple mipsel-linux-gnu -mcpu=mips64r2 -mattr=msa \ |
| 268 |
// -disassemble -fuzzer-args ./corpus |
| 269 |
// |
| 270 |
// If your aim is to find instructions that are not tested, then it is |
| 271 |
// advisable to constrain the maximum input size to a single instruction |
| 272 |
// using -max_len as in the first example. This results in a test corpus of |
| 273 |
// individual instructions that test unique paths. Without this constraint, |
| 274 |
// there will be considerable redundancy in the corpus. |
| 275 |
|
| 276 |
char **OriginalArgv = *argv; |
| 277 |
|
| 278 |
LLVMInitializeAllTargetInfos(); |
| 279 |
LLVMInitializeAllTargetMCs(); |
| 280 |
LLVMInitializeAllAsmParsers(); |
| 281 |
|
| 282 |
cl::ParseCommandLineOptions(*argc, OriginalArgv); |
| 283 |
|
| 284 |
// Rebuild the argv without the arguments llvm-mc-fuzzer consumed so that |
| 285 |
// the driver can parse its arguments. |
| 286 |
// |
| 287 |
// FuzzerArgs cannot provide the non-const pointer that OriginalArgv needs. |
| 288 |
// Re-use the strings from OriginalArgv instead of copying FuzzerArg to a |
| 289 |
// non-const buffer to avoid the need to clean up when the fuzzer terminates. |
| 290 |
ModifiedArgv.push_back(OriginalArgv[0]); |
| 291 |
for (const auto &FuzzerArg : FuzzerArgs) { |
| 292 |
for (int i = 1; i < *argc; ++i) { |
| 293 |
if (FuzzerArg == OriginalArgv[i]) |
| 294 |
ModifiedArgv.push_back(OriginalArgv[i]); |
| 295 |
} |
| 296 |
} |
| 297 |
*argc = ModifiedArgv.size(); |
| 298 |
*argv = ModifiedArgv.data(); |
| 299 |
|
| 300 |
// Package up features to be passed to target/subtarget |
| 301 |
// We have to pass it via a global since the callback doesn't |
| 302 |
// permit any user data. |
| 303 |
if (MAttrs.size()) { |
| 304 |
SubtargetFeatures Features; |
| 305 |
for (unsigned i = 0; i != MAttrs.size(); ++i) |
| 306 |
Features.AddFeature(MAttrs[i]); |
| 307 |
FeaturesStr = Features.getString(); |
| 308 |
} |
| 309 |
|
| 310 |
if (TripleName.empty()) |
| 311 |
TripleName = sys::getDefaultTargetTriple(); |
| 312 |
|
| 313 |
return 0; |
| 314 |
} |