1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Coverage instrumentation that works with AddressSanitizer
11 // and potentially with other Sanitizers.
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):
17 // __sanitizer_cov(&Guard);
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).
22 // With CoverageLevel>=3 we also split critical edges this effectively
23 // instrumenting all edges.
25 // CoverageLevel>=4 add indirect call profiling implented as a function call.
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.
31 //===----------------------------------------------------------------------===//
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"
54 #define DEBUG_TYPE "sancov"
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;
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));
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));
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));
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));
95 class SanitizerCoverageModule : public ModulePass {
97 SanitizerCoverageModule(int CoverageLevel = 0)
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";
107 void getAnalysisUsage(AnalysisUsage &AU) const override {
108 AU.addRequired<DataLayoutPass>();
112 void InjectCoverageForIndirectCalls(Function &F,
113 ArrayRef<Instruction *> IndirCalls);
114 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
115 ArrayRef<Instruction *> IndirCalls);
116 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
117 Function *SanCovFunction;
118 Function *SanCovWithCheckFunction;
119 Function *SanCovIndirCallFunction;
120 Function *SanCovModuleInit;
121 Function *SanCovTraceEnter, *SanCovTraceBB;
126 GlobalVariable *GuardArray;
127 GlobalVariable *EightBitCounterArray;
134 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
135 if (Function *F = dyn_cast<Function>(FuncOrBitcast))
138 raw_string_ostream Stream(Err);
139 Stream << "SanitizerCoverage interface function redefined: "
141 report_fatal_error(Err);
144 bool SanitizerCoverageModule::runOnModule(Module &M) {
145 if (!CoverageLevel) return false;
146 C = &(M.getContext());
147 DataLayoutPass *DLP = &getAnalysis<DataLayoutPass>();
148 IntptrTy = Type::getIntNTy(*C, DLP->getDataLayout().getPointerSizeInBits());
149 Type *VoidTy = Type::getVoidTy(*C);
151 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
152 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
155 Function::Create(FunctionType::get(VoidTy, false),
156 GlobalValue::InternalLinkage, kSanCovModuleCtorName, &M);
157 ReturnInst::Create(*C, BasicBlock::Create(*C, "", CtorFunc));
158 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
160 SanCovFunction = checkInterfaceFunction(
161 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
162 SanCovWithCheckFunction = checkInterfaceFunction(
163 M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
164 SanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
165 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
166 SanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
167 kSanCovModuleInitName, Type::getVoidTy(*C), Int32PtrTy, IntptrTy,
168 Int8PtrTy, Int8PtrTy, nullptr));
169 SanCovModuleInit->setLinkage(Function::ExternalLinkage);
170 // We insert an empty inline asm after cov callbacks to avoid callback merge.
171 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
172 StringRef(""), StringRef(""),
173 /*hasSideEffects=*/true);
175 if (ClExperimentalTracing) {
176 SanCovTraceEnter = checkInterfaceFunction(
177 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
178 SanCovTraceBB = checkInterfaceFunction(
179 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
182 // At this point we create a dummy array of guards because we don't
183 // know how many elements we will need.
184 Type *Int32Ty = IRB.getInt32Ty();
185 Type *Int8Ty = IRB.getInt8Ty();
188 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
189 nullptr, "__sancov_gen_cov_tmp");
190 if (ClUse8bitCounters)
191 EightBitCounterArray =
192 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
193 nullptr, "__sancov_gen_cov_tmp");
198 // Now we know how many elements we need. Create an array of guards
199 // with one extra element at the beginning for the size.
200 Type *Int32ArrayNTy =
201 ArrayType::get(Int32Ty, SanCovFunction->getNumUses() + 1);
202 GlobalVariable *RealGuardArray = new GlobalVariable(
203 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
204 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
207 // Replace the dummy array with the real one.
208 GuardArray->replaceAllUsesWith(
209 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
210 GuardArray->eraseFromParent();
212 GlobalVariable *RealEightBitCounterArray;
213 if (ClUse8bitCounters) {
214 // Make sure the array is 16-aligned.
215 static const int kCounterAlignment = 16;
217 ArrayType::get(Int8Ty, RoundUpToAlignment(SanCovFunction->getNumUses(),
219 RealEightBitCounterArray = new GlobalVariable(
220 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
221 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
222 RealEightBitCounterArray->setAlignment(kCounterAlignment);
223 EightBitCounterArray->replaceAllUsesWith(
224 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
225 EightBitCounterArray->eraseFromParent();
228 // Create variable for module (compilation unit) name
229 Constant *ModNameStrConst =
230 ConstantDataArray::getString(M.getContext(), M.getName(), true);
231 GlobalVariable *ModuleName =
232 new GlobalVariable(M, ModNameStrConst->getType(), true,
233 GlobalValue::PrivateLinkage, ModNameStrConst);
235 // Call __sanitizer_cov_module_init
236 IRB.SetInsertPoint(CtorFunc->getEntryBlock().getTerminator());
238 SanCovModuleInit, IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
239 ConstantInt::get(IntptrTy, SanCovFunction->getNumUses()),
241 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
242 : Constant::getNullValue(Int8PtrTy),
243 IRB.CreatePointerCast(ModuleName, Int8PtrTy));
247 bool SanitizerCoverageModule::runOnFunction(Function &F) {
248 if (F.empty()) return false;
249 if (F.getName().find(".module_ctor") != std::string::npos)
250 return false; // Should not instrument sanitizer init functions.
251 if (CoverageLevel >= 3)
252 SplitAllCriticalEdges(F);
253 SmallVector<Instruction*, 8> IndirCalls;
254 SmallVector<BasicBlock*, 16> AllBlocks;
256 AllBlocks.push_back(&BB);
257 if (CoverageLevel >= 4)
258 for (auto &Inst : BB) {
260 if (CS && !CS.getCalledFunction())
261 IndirCalls.push_back(&Inst);
264 InjectCoverage(F, AllBlocks, IndirCalls);
269 SanitizerCoverageModule::InjectCoverage(Function &F,
270 ArrayRef<BasicBlock *> AllBlocks,
271 ArrayRef<Instruction *> IndirCalls) {
272 if (!CoverageLevel) return false;
274 if (CoverageLevel == 1) {
275 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
277 for (auto BB : AllBlocks)
278 InjectCoverageAtBlock(F, *BB,
279 ClCoverageBlockThreshold < AllBlocks.size());
281 InjectCoverageForIndirectCalls(F, IndirCalls);
285 // On every indirect call we call a run-time function
286 // __sanitizer_cov_indir_call* with two parameters:
288 // - global cache array that contains kCacheSize pointers (zero-initialized).
289 // The cache is used to speed up recording the caller-callee pairs.
290 // The address of the caller is passed implicitly via caller PC.
291 // kCacheSize is encoded in the name of the run-time function.
292 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
293 Function &F, ArrayRef<Instruction *> IndirCalls) {
294 if (IndirCalls.empty()) return;
295 const int kCacheSize = 16;
296 const int kCacheAlignment = 64; // Align for better performance.
297 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
298 for (auto I : IndirCalls) {
301 Value *Callee = CS.getCalledValue();
302 if (dyn_cast<InlineAsm>(Callee)) continue;
303 GlobalVariable *CalleeCache = new GlobalVariable(
304 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
305 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
306 CalleeCache->setAlignment(kCacheAlignment);
307 IRB.CreateCall2(SanCovIndirCallFunction,
308 IRB.CreatePointerCast(Callee, IntptrTy),
309 IRB.CreatePointerCast(CalleeCache, IntptrTy));
313 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
315 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
316 // Skip static allocas at the top of the entry block so they don't become
317 // dynamic when we split the block. If we used our optimized stack layout,
318 // then there will only be one alloca and it will come first.
319 for (; IP != BE; ++IP) {
320 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
321 if (!AI || !AI->isStaticAlloca())
325 bool IsEntryBB = &BB == &F.getEntryBlock();
327 IsEntryBB ? IP->getDebugLoc().getFnDebugLoc(*C) : IP->getDebugLoc();
329 IRB.SetCurrentDebugLocation(EntryLoc);
330 SmallVector<Value *, 1> Indices;
331 Value *GuardP = IRB.CreateAdd(
332 IRB.CreatePointerCast(GuardArray, IntptrTy),
333 ConstantInt::get(IntptrTy, (1 + SanCovFunction->getNumUses()) * 4));
334 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
335 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
337 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
339 LoadInst *Load = IRB.CreateLoad(GuardP);
340 Load->setAtomic(Monotonic);
341 Load->setAlignment(4);
342 Load->setMetadata(F.getParent()->getMDKindID("nosanitize"),
343 MDNode::get(*C, None));
344 Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
345 Instruction *Ins = SplitBlockAndInsertIfThen(
346 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
347 IRB.SetInsertPoint(Ins);
348 IRB.SetCurrentDebugLocation(EntryLoc);
349 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
350 IRB.CreateCall(SanCovFunction, GuardP);
351 IRB.CreateCall(EmptyAsm); // Avoids callback merge.
354 if(ClUse8bitCounters) {
355 IRB.SetInsertPoint(IP);
356 Value *P = IRB.CreateAdd(
357 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
358 ConstantInt::get(IntptrTy, SanCovFunction->getNumUses() - 1));
359 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
360 Value *LI = IRB.CreateLoad(P);
361 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
362 IRB.CreateStore(Inc, P);
365 if (ClExperimentalTracing) {
366 // Experimental support for tracing.
367 // Insert a callback with the same guard variable as used for coverage.
368 IRB.SetInsertPoint(IP);
369 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
373 char SanitizerCoverageModule::ID = 0;
374 INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
375 "SanitizerCoverage: TODO."
376 "ModulePass", false, false)
377 ModulePass *llvm::createSanitizerCoverageModulePass(int CoverageLevel) {
378 return new SanitizerCoverageModule(CoverageLevel);