llvm-isel-fuzzer.cpp 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. //===--- llvm-isel-fuzzer.cpp - Fuzzer for instruction selection ----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Tool to fuzz instruction selection using libFuzzer.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/Analysis/TargetLibraryInfo.h"
  15. #include "llvm/Bitcode/BitcodeReader.h"
  16. #include "llvm/Bitcode/BitcodeWriter.h"
  17. #include "llvm/CodeGen/CommandFlags.def"
  18. #include "llvm/FuzzMutate/FuzzerCLI.h"
  19. #include "llvm/FuzzMutate/IRMutator.h"
  20. #include "llvm/FuzzMutate/Operations.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/LLVMContext.h"
  23. #include "llvm/IR/LegacyPassManager.h"
  24. #include "llvm/IR/Module.h"
  25. #include "llvm/IR/Verifier.h"
  26. #include "llvm/IRReader/IRReader.h"
  27. #include "llvm/Support/DataTypes.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/SourceMgr.h"
  30. #include "llvm/Support/TargetRegistry.h"
  31. #include "llvm/Support/TargetSelect.h"
  32. #include "llvm/Target/TargetMachine.h"
  33. #define DEBUG_TYPE "isel-fuzzer"
  34. using namespace llvm;
  35. static cl::opt<char>
  36. OptLevel("O",
  37. cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
  38. "(default = '-O2')"),
  39. cl::Prefix,
  40. cl::ZeroOrMore,
  41. cl::init(' '));
  42. static cl::opt<std::string>
  43. TargetTriple("mtriple", cl::desc("Override target triple for module"));
  44. static std::unique_ptr<TargetMachine> TM;
  45. static std::unique_ptr<IRMutator> Mutator;
  46. std::unique_ptr<IRMutator> createISelMutator() {
  47. std::vector<TypeGetter> Types{
  48. Type::getInt1Ty, Type::getInt8Ty, Type::getInt16Ty, Type::getInt32Ty,
  49. Type::getInt64Ty, Type::getFloatTy, Type::getDoubleTy};
  50. std::vector<std::unique_ptr<IRMutationStrategy>> Strategies;
  51. Strategies.emplace_back(
  52. new InjectorIRStrategy(InjectorIRStrategy::getDefaultOps()));
  53. Strategies.emplace_back(new InstDeleterIRStrategy());
  54. return llvm::make_unique<IRMutator>(std::move(Types), std::move(Strategies));
  55. }
  56. extern "C" LLVM_ATTRIBUTE_USED size_t LLVMFuzzerCustomMutator(
  57. uint8_t *Data, size_t Size, size_t MaxSize, unsigned int Seed) {
  58. LLVMContext Context;
  59. std::unique_ptr<Module> M;
  60. if (Size <= 1)
  61. // We get bogus data given an empty corpus - just create a new module.
  62. M.reset(new Module("M", Context));
  63. else
  64. M = parseModule(Data, Size, Context);
  65. Mutator->mutateModule(*M, Seed, Size, MaxSize);
  66. return writeModule(*M, Data, MaxSize);
  67. }
  68. extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  69. if (Size <= 1)
  70. // We get bogus data given an empty corpus - ignore it.
  71. return 0;
  72. LLVMContext Context;
  73. auto M = parseModule(Data, Size, Context);
  74. if (!M || verifyModule(*M, &errs())) {
  75. errs() << "error: input module is broken!\n";
  76. return 0;
  77. }
  78. // Set up the module to build for our target.
  79. M->setTargetTriple(TM->getTargetTriple().normalize());
  80. M->setDataLayout(TM->createDataLayout());
  81. // Build up a PM to do instruction selection.
  82. legacy::PassManager PM;
  83. TargetLibraryInfoImpl TLII(TM->getTargetTriple());
  84. PM.add(new TargetLibraryInfoWrapperPass(TLII));
  85. raw_null_ostream OS;
  86. TM->addPassesToEmitFile(PM, OS, TargetMachine::CGFT_Null);
  87. PM.run(*M);
  88. return 0;
  89. }
  90. static void handleLLVMFatalError(void *, const std::string &Message, bool) {
  91. // TODO: Would it be better to call into the fuzzer internals directly?
  92. dbgs() << "LLVM ERROR: " << Message << "\n"
  93. << "Aborting to trigger fuzzer exit handling.\n";
  94. abort();
  95. }
  96. extern "C" LLVM_ATTRIBUTE_USED int LLVMFuzzerInitialize(int *argc,
  97. char ***argv) {
  98. EnableDebugBuffering = true;
  99. InitializeAllTargets();
  100. InitializeAllTargetMCs();
  101. InitializeAllAsmPrinters();
  102. InitializeAllAsmParsers();
  103. handleExecNameEncodedBEOpts(*argv[0]);
  104. parseFuzzerCLOpts(*argc, *argv);
  105. if (TargetTriple.empty()) {
  106. errs() << *argv[0] << ": -mtriple must be specified\n";
  107. exit(1);
  108. }
  109. Triple TheTriple = Triple(Triple::normalize(TargetTriple));
  110. // Get the target specific parser.
  111. std::string Error;
  112. const Target *TheTarget =
  113. TargetRegistry::lookupTarget(MArch, TheTriple, Error);
  114. if (!TheTarget) {
  115. errs() << argv[0] << ": " << Error;
  116. return 1;
  117. }
  118. // Set up the pipeline like llc does.
  119. std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
  120. CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  121. switch (OptLevel) {
  122. default:
  123. errs() << argv[0] << ": invalid optimization level.\n";
  124. return 1;
  125. case ' ': break;
  126. case '0': OLvl = CodeGenOpt::None; break;
  127. case '1': OLvl = CodeGenOpt::Less; break;
  128. case '2': OLvl = CodeGenOpt::Default; break;
  129. case '3': OLvl = CodeGenOpt::Aggressive; break;
  130. }
  131. TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
  132. TM.reset(TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr,
  133. FeaturesStr, Options, getRelocModel(),
  134. getCodeModel(), OLvl));
  135. assert(TM && "Could not allocate target machine!");
  136. // Make sure we print the summary and the current unit when LLVM errors out.
  137. install_fatal_error_handler(handleLLVMFatalError, nullptr);
  138. // Finally, create our mutator.
  139. Mutator = createISelMutator();
  140. return 0;
  141. }