1 //===--- llvm-opt-fuzzer.cpp - Fuzzer for instruction selection ----------===//
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
7 //===----------------------------------------------------------------------===//
9 // Tool to fuzz optimization passes using libFuzzer.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Bitcode/BitcodeReader.h"
14 #include "llvm/Bitcode/BitcodeWriter.h"
15 #include "llvm/CodeGen/CommandFlags.inc"
16 #include "llvm/FuzzMutate/FuzzerCLI.h"
17 #include "llvm/FuzzMutate/IRMutator.h"
18 #include "llvm/IR/Verifier.h"
19 #include "llvm/InitializePasses.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"
27 static cl::opt
<std::string
>
28 TargetTripleStr("mtriple", cl::desc("Override target triple for module"));
30 // Passes to run for this fuzzer instance. Expects new pass manager syntax.
31 static cl::opt
<std::string
> PassPipeline(
33 cl::desc("A textual description of the pass pipeline for testing"));
35 static std::unique_ptr
<IRMutator
> Mutator
;
36 static std::unique_ptr
<TargetMachine
> TM
;
38 std::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
};
43 std::vector
<std::unique_ptr
<IRMutationStrategy
>> Strategies
;
45 std::make_unique
<InjectorIRStrategy
>(
46 InjectorIRStrategy::getDefaultOps()));
48 std::make_unique
<InstDeleterIRStrategy
>());
50 return std::make_unique
<IRMutator
>(std::move(Types
), std::move(Strategies
));
53 extern "C" LLVM_ATTRIBUTE_USED
size_t LLVMFuzzerCustomMutator(
54 uint8_t *Data
, size_t Size
, size_t MaxSize
, unsigned int Seed
) {
57 "IR mutator should have been created during fuzzer initialization");
60 auto M
= parseAndVerify(Data
, Size
, Context
);
62 errs() << "error: mutator input module is broken!\n";
66 Mutator
->mutateModule(*M
, Seed
, Size
, MaxSize
);
68 if (verifyModule(*M
, &errs())) {
69 errs() << "mutation result doesn't pass verification\n";
73 // Avoid adding incorrect test cases to the corpus.
79 raw_string_ostream
OS(Buf
);
80 WriteBitcodeToFile(*M
, OS
);
82 if (Buf
.size() > MaxSize
)
85 // There are some invariants which are not checked by the verifier in favor
86 // of having them checked by the parser. They may be considered as bugs in the
87 // verifier and should be fixed there. However until all of those are covered
88 // we want to check for them explicitly. Otherwise we will add incorrect input
89 // to the corpus and this is going to confuse the fuzzer which will start
90 // exploration of the bitcode reader error handling code.
91 auto NewM
= parseAndVerify(
92 reinterpret_cast<const uint8_t*>(Buf
.data()), Buf
.size(), Context
);
94 errs() << "mutator failed to re-read the module\n";
101 memcpy(Data
, Buf
.data(), Buf
.size());
105 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data
, size_t Size
) {
106 assert(TM
&& "Should have been created during fuzzer initialization");
109 // We get bogus data given an empty corpus - ignore it.
116 auto M
= parseAndVerify(Data
, Size
, Context
);
118 errs() << "error: input module is broken!\n";
122 // Set up target dependant options
125 M
->setTargetTriple(TM
->getTargetTriple().normalize());
126 M
->setDataLayout(TM
->createDataLayout());
127 setFunctionAttributes(TM
->getTargetCPU(), TM
->getTargetFeatureString(), *M
);
129 // Create pass pipeline
132 PassBuilder
PB(TM
.get());
134 LoopAnalysisManager LAM
;
135 FunctionAnalysisManager FAM
;
136 CGSCCAnalysisManager CGAM
;
137 ModulePassManager MPM
;
138 ModuleAnalysisManager MAM
;
140 FAM
.registerPass([&] { return PB
.buildDefaultAAPipeline(); });
141 PB
.registerModuleAnalyses(MAM
);
142 PB
.registerCGSCCAnalyses(CGAM
);
143 PB
.registerFunctionAnalyses(FAM
);
144 PB
.registerLoopAnalyses(LAM
);
145 PB
.crossRegisterProxies(LAM
, FAM
, CGAM
, MAM
);
147 auto Err
= PB
.parsePassPipeline(MPM
, PassPipeline
, false, false);
148 assert(!Err
&& "Should have been checked during fuzzer initialization");
149 // Only fail with assert above, otherwise ignore the parsing error.
150 consumeError(std::move(Err
));
152 // Run passes which we need to test
157 // Check that passes resulted in a correct code
158 if (verifyModule(*M
, &errs())) {
159 errs() << "Transformation resulted in an invalid module\n";
166 static void handleLLVMFatalError(void *, const std::string
&Message
, bool) {
167 // TODO: Would it be better to call into the fuzzer internals directly?
168 dbgs() << "LLVM ERROR: " << Message
<< "\n"
169 << "Aborting to trigger fuzzer exit handling.\n";
173 extern "C" LLVM_ATTRIBUTE_USED
int LLVMFuzzerInitialize(
174 int *argc
, char ***argv
) {
175 EnableDebugBuffering
= true;
177 // Make sure we print the summary and the current unit when LLVM errors out.
178 install_fatal_error_handler(handleLLVMFatalError
, nullptr);
183 InitializeAllTargets();
184 InitializeAllTargetMCs();
186 PassRegistry
&Registry
= *PassRegistry::getPassRegistry();
187 initializeCore(Registry
);
188 initializeCoroutines(Registry
);
189 initializeScalarOpts(Registry
);
190 initializeObjCARCOpts(Registry
);
191 initializeVectorization(Registry
);
192 initializeIPO(Registry
);
193 initializeAnalysis(Registry
);
194 initializeTransformUtils(Registry
);
195 initializeInstCombine(Registry
);
196 initializeAggressiveInstCombine(Registry
);
197 initializeInstrumentation(Registry
);
198 initializeTarget(Registry
);
200 // Parse input options
203 handleExecNameEncodedOptimizerOpts(*argv
[0]);
204 parseFuzzerCLOpts(*argc
, *argv
);
206 // Create TargetMachine
209 if (TargetTripleStr
.empty()) {
210 errs() << *argv
[0] << ": -mtriple must be specified\n";
213 Triple TargetTriple
= Triple(Triple::normalize(TargetTripleStr
));
216 const Target
*TheTarget
=
217 TargetRegistry::lookupTarget(MArch
, TargetTriple
, Error
);
219 errs() << *argv
[0] << ": " << Error
;
223 TargetOptions Options
= InitTargetOptionsFromCodeGenFlags();
224 TM
.reset(TheTarget
->createTargetMachine(
225 TargetTriple
.getTriple(), getCPUStr(), getFeaturesStr(),
226 Options
, getRelocModel(), getCodeModel(), CodeGenOpt::Default
));
227 assert(TM
&& "Could not allocate target machine!");
229 // Check that pass pipeline is specified and correct
232 if (PassPipeline
.empty()) {
233 errs() << *argv
[0] << ": at least one pass should be specified\n";
237 PassBuilder
PB(TM
.get());
238 ModulePassManager MPM
;
239 if (auto Err
= PB
.parsePassPipeline(MPM
, PassPipeline
, false, false)) {
240 errs() << *argv
[0] << ": " << toString(std::move(Err
)) << "\n";
247 Mutator
= createOptMutator();