blob: 39909ecd4e0a87be07285b61a622ec8712aff13a [file] [log] [blame]
Igor Laevsky13cc9952017-11-10 12:19:08 +00001//===--- llvm-opt-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 optimization passes using libFuzzer.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Bitcode/BitcodeReader.h"
15#include "llvm/Bitcode/BitcodeWriter.h"
David Blaikiec14bfec2017-11-27 19:43:58 +000016#include "llvm/CodeGen/CommandFlags.def"
Igor Laevsky13cc9952017-11-10 12:19:08 +000017#include "llvm/FuzzMutate/FuzzerCLI.h"
18#include "llvm/FuzzMutate/IRMutator.h"
Igor Laevsky13cc9952017-11-10 12:19:08 +000019#include "llvm/IR/Verifier.h"
20#include "llvm/Passes/PassBuilder.h"
21#include "llvm/Support/SourceMgr.h"
22#include "llvm/Support/TargetRegistry.h"
23#include "llvm/Support/TargetSelect.h"
24
25using namespace llvm;
26
27static cl::opt<std::string>
28 TargetTripleStr("mtriple", cl::desc("Override target triple for module"));
29
30// Passes to run for this fuzzer instance. Expects new pass manager syntax.
31static cl::opt<std::string> PassPipeline(
32 "passes",
33 cl::desc("A textual description of the pass pipeline for testing"));
34
35static std::unique_ptr<IRMutator> Mutator;
36static std::unique_ptr<TargetMachine> TM;
37
Igor Laevsky13cc9952017-11-10 12:19:08 +000038std::unique_ptr<IRMutator> createOptMutator() {
39 std::vector<TypeGetter> Types{
40 Type::getInt1Ty, Type::getInt8Ty, Type::getInt16Ty, Type::getInt32Ty,
41 Type::getInt64Ty, Type::getFloatTy, Type::getDoubleTy};
42
43 std::vector<std::unique_ptr<IRMutationStrategy>> Strategies;
44 Strategies.push_back(
45 llvm::make_unique<InjectorIRStrategy>(
46 InjectorIRStrategy::getDefaultOps()));
47 Strategies.push_back(
48 llvm::make_unique<InstDeleterIRStrategy>());
49
50 return llvm::make_unique<IRMutator>(std::move(Types), std::move(Strategies));
51}
52
53extern "C" LLVM_ATTRIBUTE_USED size_t LLVMFuzzerCustomMutator(
54 uint8_t *Data, size_t Size, size_t MaxSize, unsigned int Seed) {
55
56 assert(Mutator &&
57 "IR mutator should have been created during fuzzer initialization");
58
59 LLVMContext Context;
Igor Laevsky14c979d2018-02-05 11:05:47 +000060 auto M = parseAndVerify(Data, Size, Context);
61 if (!M) {
Igor Laevsky13cc9952017-11-10 12:19:08 +000062 errs() << "error: mutator input module is broken!\n";
63 return 0;
64 }
65
66 Mutator->mutateModule(*M, Seed, Size, MaxSize);
67
Igor Laevsky13cc9952017-11-10 12:19:08 +000068 if (verifyModule(*M, &errs())) {
69 errs() << "mutation result doesn't pass verification\n";
70 M->dump();
Igor Laevsky14c979d2018-02-05 11:05:47 +000071 // Avoid adding incorrect test cases to the corpus.
72 return 0;
Igor Laevsky13cc9952017-11-10 12:19:08 +000073 }
Igor Laevsky14c979d2018-02-05 11:05:47 +000074
75 std::string Buf;
76 {
77 raw_string_ostream OS(Buf);
78 WriteBitcodeToFile(M.get(), OS);
79 }
80 if (Buf.size() > MaxSize)
81 return 0;
82
83 // There are some invariants which are not checked by the verifier in favor
84 // of having them checked by the parser. They may be considered as bugs in the
85 // verifier and should be fixed there. However until all of those are covered
86 // we want to check for them explicitly. Otherwise we will add incorrect input
87 // to the corpus and this is going to confuse the fuzzer which will start
88 // exploration of the bitcode reader error handling code.
89 auto NewM = parseAndVerify(
90 reinterpret_cast<const uint8_t*>(Buf.data()), Buf.size(), Context);
91 if (!NewM) {
92 errs() << "mutator failed to re-read the module\n";
93 M->dump();
94 return 0;
95 }
Igor Laevsky13cc9952017-11-10 12:19:08 +000096
Igor Laevsky14c979d2018-02-05 11:05:47 +000097 memcpy(Data, Buf.data(), Buf.size());
98 return Buf.size();
Igor Laevsky13cc9952017-11-10 12:19:08 +000099}
100
101extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
102 assert(TM && "Should have been created during fuzzer initialization");
103
104 if (Size <= 1)
105 // We get bogus data given an empty corpus - ignore it.
106 return 0;
107
108 // Parse module
109 //
110
111 LLVMContext Context;
Igor Laevsky14c979d2018-02-05 11:05:47 +0000112 auto M = parseAndVerify(Data, Size, Context);
113 if (!M) {
Igor Laevsky13cc9952017-11-10 12:19:08 +0000114 errs() << "error: input module is broken!\n";
115 return 0;
116 }
117
118 // Set up target dependant options
119 //
120
121 M->setTargetTriple(TM->getTargetTriple().normalize());
122 M->setDataLayout(TM->createDataLayout());
123 setFunctionAttributes(TM->getTargetCPU(), TM->getTargetFeatureString(), *M);
124
125 // Create pass pipeline
126 //
127
128 PassBuilder PB(TM.get());
129
130 LoopAnalysisManager LAM;
131 FunctionAnalysisManager FAM;
132 CGSCCAnalysisManager CGAM;
133 ModulePassManager MPM;
134 ModuleAnalysisManager MAM;
135
136 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
137 PB.registerModuleAnalyses(MAM);
138 PB.registerCGSCCAnalyses(CGAM);
139 PB.registerFunctionAnalyses(FAM);
140 PB.registerLoopAnalyses(LAM);
141 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
142
143 bool Ok = PB.parsePassPipeline(MPM, PassPipeline, false, false);
144 assert(Ok && "Should have been checked during fuzzer initialization");
Igor Laevskyc05ee9d2017-11-10 13:19:14 +0000145 (void)Ok; // silence unused variable warning on release builds
Igor Laevsky13cc9952017-11-10 12:19:08 +0000146
147 // Run passes which we need to test
148 //
149
150 MPM.run(*M, MAM);
151
152 // Check that passes resulted in a correct code
153 if (verifyModule(*M, &errs())) {
154 errs() << "Transformation resulted in an invalid module\n";
155 abort();
156 }
157
158 return 0;
159}
160
161static void handleLLVMFatalError(void *, const std::string &Message, bool) {
162 // TODO: Would it be better to call into the fuzzer internals directly?
163 dbgs() << "LLVM ERROR: " << Message << "\n"
164 << "Aborting to trigger fuzzer exit handling.\n";
165 abort();
166}
167
168extern "C" LLVM_ATTRIBUTE_USED int LLVMFuzzerInitialize(
169 int *argc, char ***argv) {
170 EnableDebugBuffering = true;
171
172 // Make sure we print the summary and the current unit when LLVM errors out.
173 install_fatal_error_handler(handleLLVMFatalError, nullptr);
174
175 // Initialize llvm
176 //
177
178 InitializeAllTargets();
179 InitializeAllTargetMCs();
180
181 PassRegistry &Registry = *PassRegistry::getPassRegistry();
182 initializeCore(Registry);
183 initializeCoroutines(Registry);
184 initializeScalarOpts(Registry);
185 initializeObjCARCOpts(Registry);
186 initializeVectorization(Registry);
187 initializeIPO(Registry);
188 initializeAnalysis(Registry);
189 initializeTransformUtils(Registry);
190 initializeInstCombine(Registry);
191 initializeInstrumentation(Registry);
192 initializeTarget(Registry);
193
194 // Parse input options
195 //
196
197 handleExecNameEncodedOptimizerOpts(*argv[0]);
198 parseFuzzerCLOpts(*argc, *argv);
199
200 // Create TargetMachine
201 //
202
203 if (TargetTripleStr.empty()) {
204 errs() << *argv[0] << ": -mtriple must be specified\n";
205 exit(1);
206 }
207 Triple TargetTriple = Triple(Triple::normalize(TargetTripleStr));
208
209 std::string Error;
210 const Target *TheTarget =
211 TargetRegistry::lookupTarget(MArch, TargetTriple, Error);
212 if (!TheTarget) {
213 errs() << *argv[0] << ": " << Error;
214 exit(1);
215 }
216
217 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
218 TM.reset(TheTarget->createTargetMachine(
219 TargetTriple.getTriple(), getCPUStr(), getFeaturesStr(),
220 Options, getRelocModel(), getCodeModel(), CodeGenOpt::Default));
221 assert(TM && "Could not allocate target machine!");
222
223 // Check that pass pipeline is specified and correct
224 //
225
226 if (PassPipeline.empty()) {
227 errs() << *argv[0] << ": at least one pass should be specified\n";
228 exit(1);
229 }
230
231 PassBuilder PB(TM.get());
232 ModulePassManager MPM;
233 if (!PB.parsePassPipeline(MPM, PassPipeline, false, false)) {
234 errs() << *argv[0] << ": can't parse pass pipeline\n";
235 exit(1);
236 }
237
238 // Create mutator
239 //
240
241 Mutator = createOptMutator();
242
243 return 0;
244}