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 kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
59 static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
60 static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
61 static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
62 static const uint64_t kSanCtorAndDtorPriority = 1;
64 static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
65 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
66 "3: all blocks and critical edges, "
67 "4: above plus indirect calls"),
68 cl::Hidden, cl::init(0));
70 static cl::opt<int> ClCoverageBlockThreshold(
71 "sanitizer-coverage-block-threshold",
72 cl::desc("Add coverage instrumentation only to the entry block if there "
73 "are more than this number of blocks."),
74 cl::Hidden, cl::init(1500));
77 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
78 cl::desc("Experimental basic-block tracing: insert "
79 "callbacks at every basic block"),
80 cl::Hidden, cl::init(false));
84 class SanitizerCoverageModule : public ModulePass {
86 SanitizerCoverageModule(int CoverageLevel = 0)
88 CoverageLevel(std::max(CoverageLevel, (int)ClCoverageLevel)) {}
89 bool runOnModule(Module &M) override;
90 bool runOnFunction(Function &F);
91 static char ID; // Pass identification, replacement for typeid
92 const char *getPassName() const override {
93 return "SanitizerCoverageModule";
96 void getAnalysisUsage(AnalysisUsage &AU) const override {
97 AU.addRequired<DataLayoutPass>();
101 void InjectCoverageForIndirectCalls(Function &F,
102 ArrayRef<Instruction *> IndirCalls);
103 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
104 ArrayRef<Instruction *> IndirCalls);
105 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
106 Function *SanCovFunction;
107 Function *SanCovIndirCallFunction;
108 Function *SanCovModuleInit;
109 Function *SanCovTraceEnter, *SanCovTraceBB;
114 GlobalVariable *GuardArray;
121 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
122 if (Function *F = dyn_cast<Function>(FuncOrBitcast))
125 raw_string_ostream Stream(Err);
126 Stream << "SanitizerCoverage interface function redefined: "
128 report_fatal_error(Err);
131 bool SanitizerCoverageModule::runOnModule(Module &M) {
132 if (!CoverageLevel) return false;
133 C = &(M.getContext());
134 DataLayoutPass *DLP = &getAnalysis<DataLayoutPass>();
135 IntptrTy = Type::getIntNTy(*C, DLP->getDataLayout().getPointerSizeInBits());
136 Type *VoidTy = Type::getVoidTy(*C);
138 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
141 Function::Create(FunctionType::get(VoidTy, false),
142 GlobalValue::InternalLinkage, kSanCovModuleCtorName, &M);
143 ReturnInst::Create(*C, BasicBlock::Create(*C, "", CtorFunc));
144 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
146 SanCovFunction = checkInterfaceFunction(
147 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
148 SanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
149 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
150 SanCovModuleInit = checkInterfaceFunction(
151 M.getOrInsertFunction(kSanCovModuleInitName, Type::getVoidTy(*C),
152 Int32PtrTy, IntptrTy, nullptr));
153 SanCovModuleInit->setLinkage(Function::ExternalLinkage);
154 // We insert an empty inline asm after cov callbacks to avoid callback merge.
155 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
156 StringRef(""), StringRef(""),
157 /*hasSideEffects=*/true);
159 if (ClExperimentalTracing) {
160 SanCovTraceEnter = checkInterfaceFunction(
161 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
162 SanCovTraceBB = checkInterfaceFunction(
163 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
166 // At this point we create a dummy array of guards because we don't
167 // know how many elements we will need.
168 Type *Int32Ty = IRB.getInt32Ty();
170 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
171 nullptr, "__sancov_gen_cov_tmp");
176 // Now we know how many elements we need. Create an array of guards
177 // with one extra element at the beginning for the size.
178 Type *Int32ArrayNTy =
179 ArrayType::get(Int32Ty, SanCovFunction->getNumUses() + 1);
180 GlobalVariable *RealGuardArray = new GlobalVariable(
181 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
182 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
184 // Replace the dummy array with the real one.
185 GuardArray->replaceAllUsesWith(
186 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
187 GuardArray->eraseFromParent();
189 // Call __sanitizer_cov_module_init
190 IRB.SetInsertPoint(CtorFunc->getEntryBlock().getTerminator());
191 IRB.CreateCall2(SanCovModuleInit,
192 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
193 ConstantInt::get(IntptrTy, SanCovFunction->getNumUses()));
197 bool SanitizerCoverageModule::runOnFunction(Function &F) {
198 if (F.empty()) return false;
199 if (F.getName().find(".module_ctor") != std::string::npos)
200 return false; // Should not instrument sanitizer init functions.
201 if (CoverageLevel >= 3)
202 SplitAllCriticalEdges(F, this);
203 SmallVector<Instruction*, 8> IndirCalls;
204 SmallVector<BasicBlock*, 16> AllBlocks;
206 AllBlocks.push_back(&BB);
207 if (CoverageLevel >= 4)
208 for (auto &Inst : BB) {
210 if (CS && !CS.getCalledFunction())
211 IndirCalls.push_back(&Inst);
214 InjectCoverage(F, AllBlocks, IndirCalls);
219 SanitizerCoverageModule::InjectCoverage(Function &F,
220 ArrayRef<BasicBlock *> AllBlocks,
221 ArrayRef<Instruction *> IndirCalls) {
222 if (!CoverageLevel) return false;
224 if (CoverageLevel == 1 ||
225 (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
226 InjectCoverageAtBlock(F, F.getEntryBlock());
228 for (auto BB : AllBlocks)
229 InjectCoverageAtBlock(F, *BB);
231 InjectCoverageForIndirectCalls(F, IndirCalls);
235 // On every indirect call we call a run-time function
236 // __sanitizer_cov_indir_call* with two parameters:
238 // - global cache array that contains kCacheSize pointers (zero-initialized).
239 // The cache is used to speed up recording the caller-callee pairs.
240 // The address of the caller is passed implicitly via caller PC.
241 // kCacheSize is encoded in the name of the run-time function.
242 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
243 Function &F, ArrayRef<Instruction *> IndirCalls) {
244 if (IndirCalls.empty()) return;
245 const int kCacheSize = 16;
246 const int kCacheAlignment = 64; // Align for better performance.
247 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
248 for (auto I : IndirCalls) {
251 Value *Callee = CS.getCalledValue();
252 if (dyn_cast<InlineAsm>(Callee)) continue;
253 GlobalVariable *CalleeCache = new GlobalVariable(
254 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
255 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
256 CalleeCache->setAlignment(kCacheAlignment);
257 IRB.CreateCall2(SanCovIndirCallFunction,
258 IRB.CreatePointerCast(Callee, IntptrTy),
259 IRB.CreatePointerCast(CalleeCache, IntptrTy));
263 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F,
265 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
266 // Skip static allocas at the top of the entry block so they don't become
267 // dynamic when we split the block. If we used our optimized stack layout,
268 // then there will only be one alloca and it will come first.
269 for (; IP != BE; ++IP) {
270 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
271 if (!AI || !AI->isStaticAlloca())
275 bool IsEntryBB = &BB == &F.getEntryBlock();
277 IsEntryBB ? IP->getDebugLoc().getFnDebugLoc(*C) : IP->getDebugLoc();
279 IRB.SetCurrentDebugLocation(EntryLoc);
280 SmallVector<Value *, 1> Indices;
281 Value *GuardP = IRB.CreateAdd(
282 IRB.CreatePointerCast(GuardArray, IntptrTy),
283 ConstantInt::get(IntptrTy, (1 + SanCovFunction->getNumUses()) * 4));
284 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
285 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
286 LoadInst *Load = IRB.CreateLoad(GuardP);
287 Load->setAtomic(Monotonic);
288 Load->setAlignment(4);
289 Load->setMetadata(F.getParent()->getMDKindID("nosanitize"),
290 MDNode::get(*C, None));
291 Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
292 Instruction *Ins = SplitBlockAndInsertIfThen(
293 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
294 IRB.SetInsertPoint(Ins);
295 IRB.SetCurrentDebugLocation(EntryLoc);
296 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
297 IRB.CreateCall(SanCovFunction, GuardP);
298 IRB.CreateCall(EmptyAsm); // Avoids callback merge.
300 if (ClExperimentalTracing) {
301 // Experimental support for tracing.
302 // Insert a callback with the same guard variable as used for coverage.
303 IRB.SetInsertPoint(IP);
304 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
308 char SanitizerCoverageModule::ID = 0;
309 INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
310 "SanitizerCoverage: TODO."
311 "ModulePass", false, false)
312 ModulePass *llvm::createSanitizerCoverageModulePass(int CoverageLevel) {
313 return new SanitizerCoverageModule(CoverageLevel);