llvm-project
226 строк · 6.5 Кб
1//===--- llvm-opt-fuzzer.cpp - Fuzzer for instruction selection ----------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// Tool to fuzz optimization passes using libFuzzer.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Bitcode/BitcodeReader.h"
14#include "llvm/Bitcode/BitcodeWriter.h"
15#include "llvm/CodeGen/CommandFlags.h"
16#include "llvm/FuzzMutate/FuzzerCLI.h"
17#include "llvm/FuzzMutate/IRMutator.h"
18#include "llvm/IR/Verifier.h"
19#include "llvm/MC/TargetRegistry.h"
20#include "llvm/Passes/PassBuilder.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/SourceMgr.h"
23#include "llvm/Support/TargetSelect.h"
24#include "llvm/Target/TargetMachine.h"
25
26using namespace llvm;
27
28static codegen::RegisterCodeGenFlags CGF;
29
30static cl::opt<std::string>
31TargetTripleStr("mtriple", cl::desc("Override target triple for module"));
32
33// Passes to run for this fuzzer instance. Expects new pass manager syntax.
34static cl::opt<std::string> PassPipeline(
35"passes",
36cl::desc("A textual description of the pass pipeline for testing"));
37
38static std::unique_ptr<IRMutator> Mutator;
39static std::unique_ptr<TargetMachine> TM;
40
41std::unique_ptr<IRMutator> createOptMutator() {
42std::vector<TypeGetter> Types{
43Type::getInt1Ty, Type::getInt8Ty, Type::getInt16Ty, Type::getInt32Ty,
44Type::getInt64Ty, Type::getFloatTy, Type::getDoubleTy};
45
46std::vector<std::unique_ptr<IRMutationStrategy>> Strategies;
47Strategies.push_back(std::make_unique<InjectorIRStrategy>(
48InjectorIRStrategy::getDefaultOps()));
49Strategies.push_back(std::make_unique<InstDeleterIRStrategy>());
50Strategies.push_back(std::make_unique<InstModificationIRStrategy>());
51
52return std::make_unique<IRMutator>(std::move(Types), std::move(Strategies));
53}
54
55extern "C" LLVM_ATTRIBUTE_USED size_t LLVMFuzzerCustomMutator(
56uint8_t *Data, size_t Size, size_t MaxSize, unsigned int Seed) {
57
58assert(Mutator &&
59"IR mutator should have been created during fuzzer initialization");
60
61LLVMContext Context;
62auto M = parseAndVerify(Data, Size, Context);
63if (!M) {
64errs() << "error: mutator input module is broken!\n";
65return 0;
66}
67
68Mutator->mutateModule(*M, Seed, MaxSize);
69
70if (verifyModule(*M, &errs())) {
71errs() << "mutation result doesn't pass verification\n";
72#ifndef NDEBUG
73M->dump();
74#endif
75// Avoid adding incorrect test cases to the corpus.
76return 0;
77}
78
79std::string Buf;
80{
81raw_string_ostream OS(Buf);
82WriteBitcodeToFile(*M, OS);
83}
84if (Buf.size() > MaxSize)
85return 0;
86
87// There are some invariants which are not checked by the verifier in favor
88// of having them checked by the parser. They may be considered as bugs in the
89// verifier and should be fixed there. However until all of those are covered
90// we want to check for them explicitly. Otherwise we will add incorrect input
91// to the corpus and this is going to confuse the fuzzer which will start
92// exploration of the bitcode reader error handling code.
93auto NewM = parseAndVerify(reinterpret_cast<const uint8_t *>(Buf.data()),
94Buf.size(), Context);
95if (!NewM) {
96errs() << "mutator failed to re-read the module\n";
97#ifndef NDEBUG
98M->dump();
99#endif
100return 0;
101}
102
103memcpy(Data, Buf.data(), Buf.size());
104return Buf.size();
105}
106
107extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
108assert(TM && "Should have been created during fuzzer initialization");
109
110if (Size <= 1)
111// We get bogus data given an empty corpus - ignore it.
112return 0;
113
114// Parse module
115//
116
117LLVMContext Context;
118auto M = parseAndVerify(Data, Size, Context);
119if (!M) {
120errs() << "error: input module is broken!\n";
121return 0;
122}
123
124// Set up target dependant options
125//
126
127M->setTargetTriple(TM->getTargetTriple().normalize());
128M->setDataLayout(TM->createDataLayout());
129codegen::setFunctionAttributes(TM->getTargetCPU(),
130TM->getTargetFeatureString(), *M);
131
132// Create pass pipeline
133//
134
135PassBuilder PB(TM.get());
136
137LoopAnalysisManager LAM;
138FunctionAnalysisManager FAM;
139CGSCCAnalysisManager CGAM;
140ModulePassManager MPM;
141ModuleAnalysisManager MAM;
142
143PB.registerModuleAnalyses(MAM);
144PB.registerCGSCCAnalyses(CGAM);
145PB.registerFunctionAnalyses(FAM);
146PB.registerLoopAnalyses(LAM);
147PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
148
149auto Err = PB.parsePassPipeline(MPM, PassPipeline);
150assert(!Err && "Should have been checked during fuzzer initialization");
151// Only fail with assert above, otherwise ignore the parsing error.
152consumeError(std::move(Err));
153
154// Run passes which we need to test
155//
156
157MPM.run(*M, MAM);
158
159// Check that passes resulted in a correct code
160if (verifyModule(*M, &errs())) {
161errs() << "Transformation resulted in an invalid module\n";
162abort();
163}
164
165return 0;
166}
167
168static void handleLLVMFatalError(void *, const char *Message, bool) {
169// TODO: Would it be better to call into the fuzzer internals directly?
170dbgs() << "LLVM ERROR: " << Message << "\n"
171<< "Aborting to trigger fuzzer exit handling.\n";
172abort();
173}
174
175extern "C" LLVM_ATTRIBUTE_USED int LLVMFuzzerInitialize(int *argc,
176char ***argv) {
177EnableDebugBuffering = true;
178
179// Make sure we print the summary and the current unit when LLVM errors out.
180install_fatal_error_handler(handleLLVMFatalError, nullptr);
181
182// Initialize llvm
183//
184
185InitializeAllTargets();
186InitializeAllTargetMCs();
187
188// Parse input options
189//
190
191handleExecNameEncodedOptimizerOpts(*argv[0]);
192parseFuzzerCLOpts(*argc, *argv);
193
194// Create TargetMachine
195//
196
197if (TargetTripleStr.empty()) {
198errs() << *argv[0] << ": -mtriple must be specified\n";
199exit(1);
200}
201ExitOnError ExitOnErr(std::string(*argv[0]) + ": error:");
202TM = ExitOnErr(codegen::createTargetMachineForTriple(
203Triple::normalize(TargetTripleStr)));
204
205// Check that pass pipeline is specified and correct
206//
207
208if (PassPipeline.empty()) {
209errs() << *argv[0] << ": at least one pass should be specified\n";
210exit(1);
211}
212
213PassBuilder PB(TM.get());
214ModulePassManager MPM;
215if (auto Err = PB.parsePassPipeline(MPM, PassPipeline)) {
216errs() << *argv[0] << ": " << toString(std::move(Err)) << "\n";
217exit(1);
218}
219
220// Create mutator
221//
222
223Mutator = createOptMutator();
224
225return 0;
226}
227