blob: 7ca1d93d70d38510fc74cb7425f4c8a2a2965087 [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"
16#include "llvm/CodeGen/CommandFlags.h"
17#include "llvm/FuzzMutate/FuzzerCLI.h"
18#include "llvm/FuzzMutate/IRMutator.h"
19#include "llvm/FuzzMutate/Operations.h"
20#include "llvm/FuzzMutate/Random.h"
21#include "llvm/IR/Verifier.h"
22#include "llvm/Passes/PassBuilder.h"
23#include "llvm/Support/SourceMgr.h"
24#include "llvm/Support/TargetRegistry.h"
25#include "llvm/Support/TargetSelect.h"
26
27using namespace llvm;
28
29static cl::opt<std::string>
30 TargetTripleStr("mtriple", cl::desc("Override target triple for module"));
31
32// Passes to run for this fuzzer instance. Expects new pass manager syntax.
33static cl::opt<std::string> PassPipeline(
34 "passes",
35 cl::desc("A textual description of the pass pipeline for testing"));
36
37static std::unique_ptr<IRMutator> Mutator;
38static std::unique_ptr<TargetMachine> TM;
39
Igor Laevsky13cc9952017-11-10 12:19:08 +000040std::unique_ptr<IRMutator> createOptMutator() {
41 std::vector<TypeGetter> Types{
42 Type::getInt1Ty, Type::getInt8Ty, Type::getInt16Ty, Type::getInt32Ty,
43 Type::getInt64Ty, Type::getFloatTy, Type::getDoubleTy};
44
45 std::vector<std::unique_ptr<IRMutationStrategy>> Strategies;
46 Strategies.push_back(
47 llvm::make_unique<InjectorIRStrategy>(
48 InjectorIRStrategy::getDefaultOps()));
49 Strategies.push_back(
50 llvm::make_unique<InstDeleterIRStrategy>());
51
52 return llvm::make_unique<IRMutator>(std::move(Types), std::move(Strategies));
53}
54
55extern "C" LLVM_ATTRIBUTE_USED size_t LLVMFuzzerCustomMutator(
56 uint8_t *Data, size_t Size, size_t MaxSize, unsigned int Seed) {
57
58 assert(Mutator &&
59 "IR mutator should have been created during fuzzer initialization");
60
61 LLVMContext Context;
62 auto M = parseModule(Data, Size, Context);
63 if (!M || verifyModule(*M, &errs())) {
64 errs() << "error: mutator input module is broken!\n";
65 return 0;
66 }
67
68 Mutator->mutateModule(*M, Seed, Size, MaxSize);
69
70#ifndef NDEBUG
71 if (verifyModule(*M, &errs())) {
72 errs() << "mutation result doesn't pass verification\n";
73 M->dump();
74 abort();
75 }
76#endif
77
78 return writeModule(*M, Data, MaxSize);
79}
80
81extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
82 assert(TM && "Should have been created during fuzzer initialization");
83
84 if (Size <= 1)
85 // We get bogus data given an empty corpus - ignore it.
86 return 0;
87
88 // Parse module
89 //
90
91 LLVMContext Context;
92 auto M = parseModule(Data, Size, Context);
93 if (!M || verifyModule(*M, &errs())) {
94 errs() << "error: input module is broken!\n";
95 return 0;
96 }
97
98 // Set up target dependant options
99 //
100
101 M->setTargetTriple(TM->getTargetTriple().normalize());
102 M->setDataLayout(TM->createDataLayout());
103 setFunctionAttributes(TM->getTargetCPU(), TM->getTargetFeatureString(), *M);
104
105 // Create pass pipeline
106 //
107
108 PassBuilder PB(TM.get());
109
110 LoopAnalysisManager LAM;
111 FunctionAnalysisManager FAM;
112 CGSCCAnalysisManager CGAM;
113 ModulePassManager MPM;
114 ModuleAnalysisManager MAM;
115
116 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
117 PB.registerModuleAnalyses(MAM);
118 PB.registerCGSCCAnalyses(CGAM);
119 PB.registerFunctionAnalyses(FAM);
120 PB.registerLoopAnalyses(LAM);
121 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
122
123 bool Ok = PB.parsePassPipeline(MPM, PassPipeline, false, false);
124 assert(Ok && "Should have been checked during fuzzer initialization");
Igor Laevskyc05ee9d2017-11-10 13:19:14 +0000125 (void)Ok; // silence unused variable warning on release builds
Igor Laevsky13cc9952017-11-10 12:19:08 +0000126
127 // Run passes which we need to test
128 //
129
130 MPM.run(*M, MAM);
131
132 // Check that passes resulted in a correct code
133 if (verifyModule(*M, &errs())) {
134 errs() << "Transformation resulted in an invalid module\n";
135 abort();
136 }
137
138 return 0;
139}
140
141static void handleLLVMFatalError(void *, const std::string &Message, bool) {
142 // TODO: Would it be better to call into the fuzzer internals directly?
143 dbgs() << "LLVM ERROR: " << Message << "\n"
144 << "Aborting to trigger fuzzer exit handling.\n";
145 abort();
146}
147
148extern "C" LLVM_ATTRIBUTE_USED int LLVMFuzzerInitialize(
149 int *argc, char ***argv) {
150 EnableDebugBuffering = true;
151
152 // Make sure we print the summary and the current unit when LLVM errors out.
153 install_fatal_error_handler(handleLLVMFatalError, nullptr);
154
155 // Initialize llvm
156 //
157
158 InitializeAllTargets();
159 InitializeAllTargetMCs();
160
161 PassRegistry &Registry = *PassRegistry::getPassRegistry();
162 initializeCore(Registry);
163 initializeCoroutines(Registry);
164 initializeScalarOpts(Registry);
165 initializeObjCARCOpts(Registry);
166 initializeVectorization(Registry);
167 initializeIPO(Registry);
168 initializeAnalysis(Registry);
169 initializeTransformUtils(Registry);
170 initializeInstCombine(Registry);
171 initializeInstrumentation(Registry);
172 initializeTarget(Registry);
173
174 // Parse input options
175 //
176
177 handleExecNameEncodedOptimizerOpts(*argv[0]);
178 parseFuzzerCLOpts(*argc, *argv);
179
180 // Create TargetMachine
181 //
182
183 if (TargetTripleStr.empty()) {
184 errs() << *argv[0] << ": -mtriple must be specified\n";
185 exit(1);
186 }
187 Triple TargetTriple = Triple(Triple::normalize(TargetTripleStr));
188
189 std::string Error;
190 const Target *TheTarget =
191 TargetRegistry::lookupTarget(MArch, TargetTriple, Error);
192 if (!TheTarget) {
193 errs() << *argv[0] << ": " << Error;
194 exit(1);
195 }
196
197 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
198 TM.reset(TheTarget->createTargetMachine(
199 TargetTriple.getTriple(), getCPUStr(), getFeaturesStr(),
200 Options, getRelocModel(), getCodeModel(), CodeGenOpt::Default));
201 assert(TM && "Could not allocate target machine!");
202
203 // Check that pass pipeline is specified and correct
204 //
205
206 if (PassPipeline.empty()) {
207 errs() << *argv[0] << ": at least one pass should be specified\n";
208 exit(1);
209 }
210
211 PassBuilder PB(TM.get());
212 ModulePassManager MPM;
213 if (!PB.parsePassPipeline(MPM, PassPipeline, false, false)) {
214 errs() << *argv[0] << ": can't parse pass pipeline\n";
215 exit(1);
216 }
217
218 // Create mutator
219 //
220
221 Mutator = createOptMutator();
222
223 return 0;
224}