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 boolean 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/LLVMContext.h"
41 #include "llvm/IR/MDBuilder.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Transforms/Scalar.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/ModuleUtils.h"
53 #define DEBUG_TYPE "sancov"
55 static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
56 static const char *const kSanCovName = "__sanitizer_cov";
57 static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
58 static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
59 static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
60 static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
61 static const uint64_t kSanCtorAndDtorPriority = 1;
63 static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
64 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
65 "3: all blocks and critical edges, "
66 "4: above plus indirect calls"),
67 cl::Hidden, cl::init(0));
69 static cl::opt<int> ClCoverageBlockThreshold(
70 "sanitizer-coverage-block-threshold",
71 cl::desc("Add coverage instrumentation only to the entry block if there "
72 "are more than this number of blocks."),
73 cl::Hidden, cl::init(1500));
76 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
77 cl::desc("Experimental basic-block tracing: insert "
78 "callbacks at every basic block"),
79 cl::Hidden, cl::init(false));
83 class SanitizerCoverageModule : public ModulePass {
85 SanitizerCoverageModule(int CoverageLevel = 0)
87 CoverageLevel(std::max(CoverageLevel, (int)ClCoverageLevel)) {}
88 bool runOnModule(Module &M) override;
89 bool runOnFunction(Function &F);
90 static char ID; // Pass identification, replacement for typeid
91 const char *getPassName() const override {
92 return "SanitizerCoverageModule";
95 void getAnalysisUsage(AnalysisUsage &AU) const override {
96 AU.addRequired<DataLayoutPass>();
100 void InjectCoverageForIndirectCalls(Function &F,
101 ArrayRef<Instruction *> IndirCalls);
102 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
103 ArrayRef<Instruction *> IndirCalls);
104 bool InjectTracing(Function &F, ArrayRef<BasicBlock *> AllBlocks);
105 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
106 Function *SanCovFunction;
107 Function *SanCovIndirCallFunction;
108 Function *SanCovModuleInit;
109 Function *SanCovTraceEnter, *SanCovTraceBB;
118 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
119 if (Function *F = dyn_cast<Function>(FuncOrBitcast))
122 raw_string_ostream Stream(Err);
123 Stream << "SanitizerCoverage interface function redefined: "
125 report_fatal_error(Err);
128 bool SanitizerCoverageModule::runOnModule(Module &M) {
129 if (!CoverageLevel) return false;
130 C = &(M.getContext());
131 DataLayoutPass *DLP = &getAnalysis<DataLayoutPass>();
132 IntptrTy = Type::getIntNTy(*C, DLP->getDataLayout().getPointerSizeInBits());
133 Type *VoidTy = Type::getVoidTy(*C);
137 Function::Create(FunctionType::get(VoidTy, false),
138 GlobalValue::InternalLinkage, kSanCovModuleCtorName, &M);
139 ReturnInst::Create(*C, BasicBlock::Create(*C, "", CtorFunc));
140 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
142 SanCovFunction = checkInterfaceFunction(
143 M.getOrInsertFunction(kSanCovName, VoidTy, IRB.getInt8PtrTy(), nullptr));
144 SanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
145 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
146 SanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
147 kSanCovModuleInitName, Type::getVoidTy(*C), IntptrTy, nullptr));
148 SanCovModuleInit->setLinkage(Function::ExternalLinkage);
150 if (ClExperimentalTracing) {
151 SanCovTraceEnter = checkInterfaceFunction(
152 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, IntptrTy, nullptr));
153 SanCovTraceBB = checkInterfaceFunction(
154 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, IntptrTy, nullptr));
160 IRB.SetInsertPoint(CtorFunc->getEntryBlock().getTerminator());
161 IRB.CreateCall(SanCovModuleInit,
162 ConstantInt::get(IntptrTy, SanCovFunction->getNumUses()));
166 bool SanitizerCoverageModule::runOnFunction(Function &F) {
167 if (F.empty()) return false;
168 // For now instrument only functions that will also be asan-instrumented.
169 if (!F.hasFnAttribute(Attribute::SanitizeAddress) &&
170 !F.hasFnAttribute(Attribute::SanitizeMemory))
172 if (CoverageLevel >= 3)
173 SplitAllCriticalEdges(F, this);
174 SmallVector<Instruction*, 8> IndirCalls;
175 SmallVector<BasicBlock*, 16> AllBlocks;
177 AllBlocks.push_back(&BB);
178 if (CoverageLevel >= 4)
179 for (auto &Inst : BB) {
181 if (CS && !CS.getCalledFunction())
182 IndirCalls.push_back(&Inst);
185 InjectCoverage(F, AllBlocks, IndirCalls);
186 InjectTracing(F, AllBlocks);
190 // Experimental support for tracing.
191 // Basicaly, insert a callback at the beginning of every basic block.
192 // Every callback gets a pointer to a uniqie global for internal storage.
193 bool SanitizerCoverageModule::InjectTracing(Function &F,
194 ArrayRef<BasicBlock *> AllBlocks) {
195 if (!ClExperimentalTracing) return false;
196 Type *Ty = ArrayType::get(IntptrTy, 1); // May need to use more words later.
197 for (auto BB : AllBlocks) {
198 IRBuilder<> IRB(BB->getFirstInsertionPt());
199 GlobalVariable *TraceCache = new GlobalVariable(
200 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
201 Constant::getNullValue(Ty), "__sancov_gen_trace_cache");
202 IRB.CreateCall(&F.getEntryBlock() == BB ? SanCovTraceEnter : SanCovTraceBB,
203 IRB.CreatePointerCast(TraceCache, IntptrTy));
209 SanitizerCoverageModule::InjectCoverage(Function &F,
210 ArrayRef<BasicBlock *> AllBlocks,
211 ArrayRef<Instruction *> IndirCalls) {
212 if (!CoverageLevel) return false;
214 if (CoverageLevel == 1 ||
215 (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
216 InjectCoverageAtBlock(F, F.getEntryBlock());
218 for (auto BB : AllBlocks)
219 InjectCoverageAtBlock(F, *BB);
221 InjectCoverageForIndirectCalls(F, IndirCalls);
225 // On every indirect call we call a run-time function
226 // __sanitizer_cov_indir_call* with two parameters:
228 // - global cache array that contains kCacheSize pointers (zero-initialized).
229 // The cache is used to speed up recording the caller-callee pairs.
230 // The address of the caller is passed implicitly via caller PC.
231 // kCacheSize is encoded in the name of the run-time function.
232 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
233 Function &F, ArrayRef<Instruction *> IndirCalls) {
234 if (IndirCalls.empty()) return;
235 const int kCacheSize = 16;
236 const int kCacheAlignment = 64; // Align for better performance.
237 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
238 for (auto I : IndirCalls) {
241 Value *Callee = CS.getCalledValue();
242 if (dyn_cast<InlineAsm>(Callee)) continue;
243 GlobalVariable *CalleeCache = new GlobalVariable(
244 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
245 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
246 CalleeCache->setAlignment(kCacheAlignment);
247 IRB.CreateCall2(SanCovIndirCallFunction,
248 IRB.CreatePointerCast(Callee, IntptrTy),
249 IRB.CreatePointerCast(CalleeCache, IntptrTy));
253 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F,
255 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
256 // Skip static allocas at the top of the entry block so they don't become
257 // dynamic when we split the block. If we used our optimized stack layout,
258 // then there will only be one alloca and it will come first.
259 for (; IP != BE; ++IP) {
260 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
261 if (!AI || !AI->isStaticAlloca())
265 DebugLoc EntryLoc = &BB == &F.getEntryBlock()
266 ? IP->getDebugLoc().getFnDebugLoc(*C)
269 IRB.SetCurrentDebugLocation(EntryLoc);
270 Type *Int8Ty = IRB.getInt8Ty();
271 GlobalVariable *Guard = new GlobalVariable(
272 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
273 Constant::getNullValue(Int8Ty), "__sancov_gen_cov_" + F.getName());
274 LoadInst *Load = IRB.CreateLoad(Guard);
275 Load->setAtomic(Monotonic);
276 Load->setAlignment(1);
277 Load->setMetadata(F.getParent()->getMDKindID("nosanitize"),
278 MDNode::get(*C, None));
279 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
280 Instruction *Ins = SplitBlockAndInsertIfThen(
281 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
282 IRB.SetInsertPoint(Ins);
283 IRB.SetCurrentDebugLocation(EntryLoc);
284 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
285 IRB.CreateCall(SanCovFunction, Guard);
288 char SanitizerCoverageModule::ID = 0;
289 INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
290 "SanitizerCoverage: TODO."
291 "ModulePass", false, false)
292 ModulePass *llvm::createSanitizerCoverageModulePass(int CoverageLevel) {
293 return new SanitizerCoverageModule(CoverageLevel);