blob: 8187bbcea6687eb6081ff2a6103f80d0a4feff73 [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;
60 auto M = parseModule(Data, Size, Context);
61 if (!M || verifyModule(*M, &errs())) {
62 errs() << "error: mutator input module is broken!\n";
63 return 0;
64 }
65
66 Mutator->mutateModule(*M, Seed, Size, MaxSize);
67
68#ifndef NDEBUG
69 if (verifyModule(*M, &errs())) {
70 errs() << "mutation result doesn't pass verification\n";
71 M->dump();
72 abort();
73 }
74#endif
75
76 return writeModule(*M, Data, MaxSize);
77}
78
79extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
80 assert(TM && "Should have been created during fuzzer initialization");
81
82 if (Size <= 1)
83 // We get bogus data given an empty corpus - ignore it.
84 return 0;
85
86 // Parse module
87 //
88
89 LLVMContext Context;
90 auto M = parseModule(Data, Size, Context);
91 if (!M || verifyModule(*M, &errs())) {
92 errs() << "error: input module is broken!\n";
93 return 0;
94 }
95
96 // Set up target dependant options
97 //
98
99 M->setTargetTriple(TM->getTargetTriple().normalize());
100 M->setDataLayout(TM->createDataLayout());
101 setFunctionAttributes(TM->getTargetCPU(), TM->getTargetFeatureString(), *M);
102
103 // Create pass pipeline
104 //
105
106 PassBuilder PB(TM.get());
107
108 LoopAnalysisManager LAM;
109 FunctionAnalysisManager FAM;
110 CGSCCAnalysisManager CGAM;
111 ModulePassManager MPM;
112 ModuleAnalysisManager MAM;
113
114 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
115 PB.registerModuleAnalyses(MAM);
116 PB.registerCGSCCAnalyses(CGAM);
117 PB.registerFunctionAnalyses(FAM);
118 PB.registerLoopAnalyses(LAM);
119 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
120
121 bool Ok = PB.parsePassPipeline(MPM, PassPipeline, false, false);
122 assert(Ok && "Should have been checked during fuzzer initialization");
Igor Laevskyc05ee9d2017-11-10 13:19:14 +0000123 (void)Ok; // silence unused variable warning on release builds
Igor Laevsky13cc9952017-11-10 12:19:08 +0000124
125 // Run passes which we need to test
126 //
127
128 MPM.run(*M, MAM);
129
130 // Check that passes resulted in a correct code
131 if (verifyModule(*M, &errs())) {
132 errs() << "Transformation resulted in an invalid module\n";
133 abort();
134 }
135
136 return 0;
137}
138
139static void handleLLVMFatalError(void *, const std::string &Message, bool) {
140 // TODO: Would it be better to call into the fuzzer internals directly?
141 dbgs() << "LLVM ERROR: " << Message << "\n"
142 << "Aborting to trigger fuzzer exit handling.\n";
143 abort();
144}
145
146extern "C" LLVM_ATTRIBUTE_USED int LLVMFuzzerInitialize(
147 int *argc, char ***argv) {
148 EnableDebugBuffering = true;
149
150 // Make sure we print the summary and the current unit when LLVM errors out.
151 install_fatal_error_handler(handleLLVMFatalError, nullptr);
152
153 // Initialize llvm
154 //
155
156 InitializeAllTargets();
157 InitializeAllTargetMCs();
158
159 PassRegistry &Registry = *PassRegistry::getPassRegistry();
160 initializeCore(Registry);
161 initializeCoroutines(Registry);
162 initializeScalarOpts(Registry);
163 initializeObjCARCOpts(Registry);
164 initializeVectorization(Registry);
165 initializeIPO(Registry);
166 initializeAnalysis(Registry);
167 initializeTransformUtils(Registry);
168 initializeInstCombine(Registry);
169 initializeInstrumentation(Registry);
170 initializeTarget(Registry);
171
172 // Parse input options
173 //
174
175 handleExecNameEncodedOptimizerOpts(*argv[0]);
176 parseFuzzerCLOpts(*argc, *argv);
177
178 // Create TargetMachine
179 //
180
181 if (TargetTripleStr.empty()) {
182 errs() << *argv[0] << ": -mtriple must be specified\n";
183 exit(1);
184 }
185 Triple TargetTriple = Triple(Triple::normalize(TargetTripleStr));
186
187 std::string Error;
188 const Target *TheTarget =
189 TargetRegistry::lookupTarget(MArch, TargetTriple, Error);
190 if (!TheTarget) {
191 errs() << *argv[0] << ": " << Error;
192 exit(1);
193 }
194
195 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
196 TM.reset(TheTarget->createTargetMachine(
197 TargetTriple.getTriple(), getCPUStr(), getFeaturesStr(),
198 Options, getRelocModel(), getCodeModel(), CodeGenOpt::Default));
199 assert(TM && "Could not allocate target machine!");
200
201 // Check that pass pipeline is specified and correct
202 //
203
204 if (PassPipeline.empty()) {
205 errs() << *argv[0] << ": at least one pass should be specified\n";
206 exit(1);
207 }
208
209 PassBuilder PB(TM.get());
210 ModulePassManager MPM;
211 if (!PB.parsePassPipeline(MPM, PassPipeline, false, false)) {
212 errs() << *argv[0] << ": can't parse pass pipeline\n";
213 exit(1);
214 }
215
216 // Create mutator
217 //
218
219 Mutator = createOptMutator();
220
221 return 0;
222}