Make DataLayout Non-Optional in the Module
[oota-llvm.git] / lib / Transforms / Instrumentation / SanitizerCoverage.cpp
1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
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 // Coverage instrumentation that works with AddressSanitizer
11 // and potentially with other Sanitizers.
12 //
13 // We create a Guard variable with the same linkage
14 // as the function and inject this code into the entry block (CoverageLevel=1)
15 // or all blocks (CoverageLevel>=2):
16 // if (Guard < 0) {
17 //    __sanitizer_cov(&Guard);
18 // }
19 // The accesses to Guard are atomic. The rest of the logic is
20 // in __sanitizer_cov (it's fine to call it more than once).
21 //
22 // With CoverageLevel>=3 we also split critical edges this effectively
23 // instrumenting all edges.
24 //
25 // CoverageLevel>=4 add indirect call profiling implented as a function call.
26 //
27 // This coverage implementation provides very limited data:
28 // it only tells if a given function (block) was ever executed. No counters.
29 // But for many use cases this is what we need and the added slowdown small.
30 //
31 //===----------------------------------------------------------------------===//
32
33 #include "llvm/Transforms/Instrumentation.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/InlineAsm.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/MDBuilder.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Transforms/Scalar.h"
49 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 #include "llvm/Transforms/Utils/ModuleUtils.h"
51
52 using namespace llvm;
53
54 #define DEBUG_TYPE "sancov"
55
56 static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
57 static const char *const kSanCovName = "__sanitizer_cov";
58 static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check";
59 static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
60 static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
61 static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
62 static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
63 static const uint64_t    kSanCtorAndDtorPriority = 2;
64
65 static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
66        cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
67                 "3: all blocks and critical edges, "
68                 "4: above plus indirect calls"),
69        cl::Hidden, cl::init(0));
70
71 static cl::opt<unsigned> ClCoverageBlockThreshold(
72     "sanitizer-coverage-block-threshold",
73     cl::desc("Use a callback with a guard check inside it if there are"
74              " more than this number of blocks."),
75     cl::Hidden, cl::init(1000));
76
77 static cl::opt<bool>
78     ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
79                           cl::desc("Experimental basic-block tracing: insert "
80                                    "callbacks at every basic block"),
81                           cl::Hidden, cl::init(false));
82
83 // Experimental 8-bit counters used as an additional search heuristic during
84 // coverage-guided fuzzing.
85 // The counters are not thread-friendly:
86 //   - contention on these counters may cause significant slowdown;
87 //   - the counter updates are racy and the results may be inaccurate.
88 // They are also inaccurate due to 8-bit integer overflow.
89 static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
90                                        cl::desc("Experimental 8-bit counters"),
91                                        cl::Hidden, cl::init(false));
92
93 namespace {
94
95 class SanitizerCoverageModule : public ModulePass {
96  public:
97    SanitizerCoverageModule(int CoverageLevel = 0)
98        : ModulePass(ID),
99          CoverageLevel(std::max(CoverageLevel, (int)ClCoverageLevel)) {}
100   bool runOnModule(Module &M) override;
101   bool runOnFunction(Function &F);
102   static char ID;  // Pass identification, replacement for typeid
103   const char *getPassName() const override {
104     return "SanitizerCoverageModule";
105   }
106
107  private:
108   void InjectCoverageForIndirectCalls(Function &F,
109                                       ArrayRef<Instruction *> IndirCalls);
110   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
111                       ArrayRef<Instruction *> IndirCalls);
112   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
113   Function *SanCovFunction;
114   Function *SanCovWithCheckFunction;
115   Function *SanCovIndirCallFunction;
116   Function *SanCovModuleInit;
117   Function *SanCovTraceEnter, *SanCovTraceBB;
118   InlineAsm *EmptyAsm;
119   Type *IntptrTy;
120   LLVMContext *C;
121
122   GlobalVariable *GuardArray;
123   GlobalVariable *EightBitCounterArray;
124
125   int CoverageLevel;
126 };
127
128 }  // namespace
129
130 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
131   if (Function *F = dyn_cast<Function>(FuncOrBitcast))
132      return F;
133   std::string Err;
134   raw_string_ostream Stream(Err);
135   Stream << "SanitizerCoverage interface function redefined: "
136          << *FuncOrBitcast;
137   report_fatal_error(Err);
138 }
139
140 bool SanitizerCoverageModule::runOnModule(Module &M) {
141   if (!CoverageLevel) return false;
142   C = &(M.getContext());
143   auto &DL = M.getDataLayout();
144   IntptrTy = Type::getIntNTy(*C, DL.getPointerSizeInBits());
145   Type *VoidTy = Type::getVoidTy(*C);
146   IRBuilder<> IRB(*C);
147   Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
148   Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
149
150   Function *CtorFunc =
151       Function::Create(FunctionType::get(VoidTy, false),
152                        GlobalValue::InternalLinkage, kSanCovModuleCtorName, &M);
153   ReturnInst::Create(*C, BasicBlock::Create(*C, "", CtorFunc));
154   appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
155
156   SanCovFunction = checkInterfaceFunction(
157       M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
158   SanCovWithCheckFunction = checkInterfaceFunction(
159       M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
160   SanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
161       kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
162   SanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
163       kSanCovModuleInitName, Type::getVoidTy(*C), Int32PtrTy, IntptrTy,
164       Int8PtrTy, Int8PtrTy, nullptr));
165   SanCovModuleInit->setLinkage(Function::ExternalLinkage);
166   // We insert an empty inline asm after cov callbacks to avoid callback merge.
167   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
168                             StringRef(""), StringRef(""),
169                             /*hasSideEffects=*/true);
170
171   if (ClExperimentalTracing) {
172     SanCovTraceEnter = checkInterfaceFunction(
173         M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
174     SanCovTraceBB = checkInterfaceFunction(
175         M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
176   }
177
178   // At this point we create a dummy array of guards because we don't
179   // know how many elements we will need.
180   Type *Int32Ty = IRB.getInt32Ty();
181   Type *Int8Ty = IRB.getInt8Ty();
182
183   GuardArray =
184       new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
185                          nullptr, "__sancov_gen_cov_tmp");
186   if (ClUse8bitCounters)
187     EightBitCounterArray =
188         new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
189                            nullptr, "__sancov_gen_cov_tmp");
190
191   for (auto &F : M)
192     runOnFunction(F);
193
194   // Now we know how many elements we need. Create an array of guards
195   // with one extra element at the beginning for the size.
196   Type *Int32ArrayNTy =
197       ArrayType::get(Int32Ty, SanCovFunction->getNumUses() + 1);
198   GlobalVariable *RealGuardArray = new GlobalVariable(
199       M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
200       Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
201
202
203   // Replace the dummy array with the real one.
204   GuardArray->replaceAllUsesWith(
205       IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
206   GuardArray->eraseFromParent();
207
208   GlobalVariable *RealEightBitCounterArray;
209   if (ClUse8bitCounters) {
210     // Make sure the array is 16-aligned.
211     static const int kCounterAlignment = 16;
212     Type *Int8ArrayNTy =
213         ArrayType::get(Int8Ty, RoundUpToAlignment(SanCovFunction->getNumUses(),
214                                                   kCounterAlignment));
215     RealEightBitCounterArray = new GlobalVariable(
216         M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
217         Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
218     RealEightBitCounterArray->setAlignment(kCounterAlignment);
219     EightBitCounterArray->replaceAllUsesWith(
220         IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
221     EightBitCounterArray->eraseFromParent();
222   }
223
224   // Create variable for module (compilation unit) name
225   Constant *ModNameStrConst =
226       ConstantDataArray::getString(M.getContext(), M.getName(), true);
227   GlobalVariable *ModuleName =
228       new GlobalVariable(M, ModNameStrConst->getType(), true,
229                          GlobalValue::PrivateLinkage, ModNameStrConst);
230
231   // Call __sanitizer_cov_module_init
232   IRB.SetInsertPoint(CtorFunc->getEntryBlock().getTerminator());
233   IRB.CreateCall4(
234       SanCovModuleInit, IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
235       ConstantInt::get(IntptrTy, SanCovFunction->getNumUses()),
236       ClUse8bitCounters
237           ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
238           : Constant::getNullValue(Int8PtrTy),
239       IRB.CreatePointerCast(ModuleName, Int8PtrTy));
240   return true;
241 }
242
243 bool SanitizerCoverageModule::runOnFunction(Function &F) {
244   if (F.empty()) return false;
245   if (F.getName().find(".module_ctor") != std::string::npos)
246     return false;  // Should not instrument sanitizer init functions.
247   if (CoverageLevel >= 3)
248     SplitAllCriticalEdges(F);
249   SmallVector<Instruction*, 8> IndirCalls;
250   SmallVector<BasicBlock*, 16> AllBlocks;
251   for (auto &BB : F) {
252     AllBlocks.push_back(&BB);
253     if (CoverageLevel >= 4)
254       for (auto &Inst : BB) {
255         CallSite CS(&Inst);
256         if (CS && !CS.getCalledFunction())
257           IndirCalls.push_back(&Inst);
258       }
259   }
260   InjectCoverage(F, AllBlocks, IndirCalls);
261   return true;
262 }
263
264 bool
265 SanitizerCoverageModule::InjectCoverage(Function &F,
266                                         ArrayRef<BasicBlock *> AllBlocks,
267                                         ArrayRef<Instruction *> IndirCalls) {
268   if (!CoverageLevel) return false;
269
270   if (CoverageLevel == 1) {
271     InjectCoverageAtBlock(F, F.getEntryBlock(), false);
272   } else {
273     for (auto BB : AllBlocks)
274       InjectCoverageAtBlock(F, *BB,
275                             ClCoverageBlockThreshold < AllBlocks.size());
276   }
277   InjectCoverageForIndirectCalls(F, IndirCalls);
278   return true;
279 }
280
281 // On every indirect call we call a run-time function
282 // __sanitizer_cov_indir_call* with two parameters:
283 //   - callee address,
284 //   - global cache array that contains kCacheSize pointers (zero-initialized).
285 //     The cache is used to speed up recording the caller-callee pairs.
286 // The address of the caller is passed implicitly via caller PC.
287 // kCacheSize is encoded in the name of the run-time function.
288 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
289     Function &F, ArrayRef<Instruction *> IndirCalls) {
290   if (IndirCalls.empty()) return;
291   const int kCacheSize = 16;
292   const int kCacheAlignment = 64;  // Align for better performance.
293   Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
294   for (auto I : IndirCalls) {
295     IRBuilder<> IRB(I);
296     CallSite CS(I);
297     Value *Callee = CS.getCalledValue();
298     if (dyn_cast<InlineAsm>(Callee)) continue;
299     GlobalVariable *CalleeCache = new GlobalVariable(
300         *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
301         Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
302     CalleeCache->setAlignment(kCacheAlignment);
303     IRB.CreateCall2(SanCovIndirCallFunction,
304                     IRB.CreatePointerCast(Callee, IntptrTy),
305                     IRB.CreatePointerCast(CalleeCache, IntptrTy));
306   }
307 }
308
309 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
310                                                     bool UseCalls) {
311   BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
312   // Skip static allocas at the top of the entry block so they don't become
313   // dynamic when we split the block.  If we used our optimized stack layout,
314   // then there will only be one alloca and it will come first.
315   for (; IP != BE; ++IP) {
316     AllocaInst *AI = dyn_cast<AllocaInst>(IP);
317     if (!AI || !AI->isStaticAlloca())
318       break;
319   }
320
321   bool IsEntryBB = &BB == &F.getEntryBlock();
322   DebugLoc EntryLoc =
323       IsEntryBB ? IP->getDebugLoc().getFnDebugLoc(*C) : IP->getDebugLoc();
324   IRBuilder<> IRB(IP);
325   IRB.SetCurrentDebugLocation(EntryLoc);
326   SmallVector<Value *, 1> Indices;
327   Value *GuardP = IRB.CreateAdd(
328       IRB.CreatePointerCast(GuardArray, IntptrTy),
329       ConstantInt::get(IntptrTy, (1 + SanCovFunction->getNumUses()) * 4));
330   Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
331   GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
332   if (UseCalls) {
333     IRB.CreateCall(SanCovWithCheckFunction, GuardP);
334   } else {
335     LoadInst *Load = IRB.CreateLoad(GuardP);
336     Load->setAtomic(Monotonic);
337     Load->setAlignment(4);
338     Load->setMetadata(F.getParent()->getMDKindID("nosanitize"),
339                       MDNode::get(*C, None));
340     Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
341     Instruction *Ins = SplitBlockAndInsertIfThen(
342         Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
343     IRB.SetInsertPoint(Ins);
344     IRB.SetCurrentDebugLocation(EntryLoc);
345     // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
346     IRB.CreateCall(SanCovFunction, GuardP);
347     IRB.CreateCall(EmptyAsm);  // Avoids callback merge.
348   }
349
350   if(ClUse8bitCounters) {
351     IRB.SetInsertPoint(IP);
352     Value *P = IRB.CreateAdd(
353         IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
354         ConstantInt::get(IntptrTy, SanCovFunction->getNumUses() - 1));
355     P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
356     Value *LI = IRB.CreateLoad(P);
357     Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
358     IRB.CreateStore(Inc, P);
359   }
360
361   if (ClExperimentalTracing) {
362     // Experimental support for tracing.
363     // Insert a callback with the same guard variable as used for coverage.
364     IRB.SetInsertPoint(IP);
365     IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
366   }
367 }
368
369 char SanitizerCoverageModule::ID = 0;
370 INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
371     "SanitizerCoverage: TODO."
372     "ModulePass", false, false)
373 ModulePass *llvm::createSanitizerCoverageModulePass(int CoverageLevel) {
374   return new SanitizerCoverageModule(CoverageLevel);
375 }