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));
85 class SanitizerCoverageModule : public ModulePass {
87 SanitizerCoverageModule(int CoverageLevel = 0)
89 CoverageLevel(std::max(CoverageLevel, (int)ClCoverageLevel)) {}
90 bool runOnModule(Module &M) override;
91 bool runOnFunction(Function &F);
92 static char ID; // Pass identification, replacement for typeid
93 const char *getPassName() const override {
94 return "SanitizerCoverageModule";
97 void getAnalysisUsage(AnalysisUsage &AU) const override {
98 AU.addRequired<DataLayoutPass>();
102 void InjectCoverageForIndirectCalls(Function &F,
103 ArrayRef<Instruction *> IndirCalls);
104 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
105 ArrayRef<Instruction *> IndirCalls);
106 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
107 Function *SanCovFunction;
108 Function *SanCovWithCheckFunction;
109 Function *SanCovIndirCallFunction;
110 Function *SanCovModuleInit;
111 Function *SanCovTraceEnter, *SanCovTraceBB;
116 GlobalVariable *GuardArray;
123 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
124 if (Function *F = dyn_cast<Function>(FuncOrBitcast))
127 raw_string_ostream Stream(Err);
128 Stream << "SanitizerCoverage interface function redefined: "
130 report_fatal_error(Err);
133 bool SanitizerCoverageModule::runOnModule(Module &M) {
134 if (!CoverageLevel) return false;
135 C = &(M.getContext());
136 DataLayoutPass *DLP = &getAnalysis<DataLayoutPass>();
137 IntptrTy = Type::getIntNTy(*C, DLP->getDataLayout().getPointerSizeInBits());
138 Type *VoidTy = Type::getVoidTy(*C);
140 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
143 Function::Create(FunctionType::get(VoidTy, false),
144 GlobalValue::InternalLinkage, kSanCovModuleCtorName, &M);
145 ReturnInst::Create(*C, BasicBlock::Create(*C, "", CtorFunc));
146 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
148 SanCovFunction = checkInterfaceFunction(
149 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
150 SanCovWithCheckFunction = checkInterfaceFunction(
151 M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
152 SanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
153 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
154 SanCovModuleInit = checkInterfaceFunction(
155 M.getOrInsertFunction(kSanCovModuleInitName, Type::getVoidTy(*C),
156 Int32PtrTy, IntptrTy, nullptr));
157 SanCovModuleInit->setLinkage(Function::ExternalLinkage);
158 // We insert an empty inline asm after cov callbacks to avoid callback merge.
159 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
160 StringRef(""), StringRef(""),
161 /*hasSideEffects=*/true);
163 if (ClExperimentalTracing) {
164 SanCovTraceEnter = checkInterfaceFunction(
165 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
166 SanCovTraceBB = checkInterfaceFunction(
167 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
170 // At this point we create a dummy array of guards because we don't
171 // know how many elements we will need.
172 Type *Int32Ty = IRB.getInt32Ty();
174 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
175 nullptr, "__sancov_gen_cov_tmp");
180 // Now we know how many elements we need. Create an array of guards
181 // with one extra element at the beginning for the size.
182 Type *Int32ArrayNTy =
183 ArrayType::get(Int32Ty, SanCovFunction->getNumUses() + 1);
184 GlobalVariable *RealGuardArray = new GlobalVariable(
185 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
186 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
188 // Replace the dummy array with the real one.
189 GuardArray->replaceAllUsesWith(
190 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
191 GuardArray->eraseFromParent();
193 // Call __sanitizer_cov_module_init
194 IRB.SetInsertPoint(CtorFunc->getEntryBlock().getTerminator());
195 IRB.CreateCall2(SanCovModuleInit,
196 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
197 ConstantInt::get(IntptrTy, SanCovFunction->getNumUses()));
201 bool SanitizerCoverageModule::runOnFunction(Function &F) {
202 if (F.empty()) return false;
203 if (F.getName().find(".module_ctor") != std::string::npos)
204 return false; // Should not instrument sanitizer init functions.
205 if (CoverageLevel >= 3)
206 SplitAllCriticalEdges(F);
207 SmallVector<Instruction*, 8> IndirCalls;
208 SmallVector<BasicBlock*, 16> AllBlocks;
210 AllBlocks.push_back(&BB);
211 if (CoverageLevel >= 4)
212 for (auto &Inst : BB) {
214 if (CS && !CS.getCalledFunction())
215 IndirCalls.push_back(&Inst);
218 InjectCoverage(F, AllBlocks, IndirCalls);
223 SanitizerCoverageModule::InjectCoverage(Function &F,
224 ArrayRef<BasicBlock *> AllBlocks,
225 ArrayRef<Instruction *> IndirCalls) {
226 if (!CoverageLevel) return false;
228 if (CoverageLevel == 1) {
229 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
231 for (auto BB : AllBlocks)
232 InjectCoverageAtBlock(F, *BB,
233 ClCoverageBlockThreshold < AllBlocks.size());
235 InjectCoverageForIndirectCalls(F, IndirCalls);
239 // On every indirect call we call a run-time function
240 // __sanitizer_cov_indir_call* with two parameters:
242 // - global cache array that contains kCacheSize pointers (zero-initialized).
243 // The cache is used to speed up recording the caller-callee pairs.
244 // The address of the caller is passed implicitly via caller PC.
245 // kCacheSize is encoded in the name of the run-time function.
246 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
247 Function &F, ArrayRef<Instruction *> IndirCalls) {
248 if (IndirCalls.empty()) return;
249 const int kCacheSize = 16;
250 const int kCacheAlignment = 64; // Align for better performance.
251 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
252 for (auto I : IndirCalls) {
255 Value *Callee = CS.getCalledValue();
256 if (dyn_cast<InlineAsm>(Callee)) continue;
257 GlobalVariable *CalleeCache = new GlobalVariable(
258 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
259 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
260 CalleeCache->setAlignment(kCacheAlignment);
261 IRB.CreateCall2(SanCovIndirCallFunction,
262 IRB.CreatePointerCast(Callee, IntptrTy),
263 IRB.CreatePointerCast(CalleeCache, IntptrTy));
267 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
269 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
270 // Skip static allocas at the top of the entry block so they don't become
271 // dynamic when we split the block. If we used our optimized stack layout,
272 // then there will only be one alloca and it will come first.
273 for (; IP != BE; ++IP) {
274 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
275 if (!AI || !AI->isStaticAlloca())
279 bool IsEntryBB = &BB == &F.getEntryBlock();
281 IsEntryBB ? IP->getDebugLoc().getFnDebugLoc(*C) : IP->getDebugLoc();
283 IRB.SetCurrentDebugLocation(EntryLoc);
284 SmallVector<Value *, 1> Indices;
285 Value *GuardP = IRB.CreateAdd(
286 IRB.CreatePointerCast(GuardArray, IntptrTy),
287 ConstantInt::get(IntptrTy, (1 + SanCovFunction->getNumUses()) * 4));
288 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
289 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
291 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
293 LoadInst *Load = IRB.CreateLoad(GuardP);
294 Load->setAtomic(Monotonic);
295 Load->setAlignment(4);
296 Load->setMetadata(F.getParent()->getMDKindID("nosanitize"),
297 MDNode::get(*C, None));
298 Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
299 Instruction *Ins = SplitBlockAndInsertIfThen(
300 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
301 IRB.SetInsertPoint(Ins);
302 IRB.SetCurrentDebugLocation(EntryLoc);
303 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
304 IRB.CreateCall(SanCovFunction, GuardP);
305 IRB.CreateCall(EmptyAsm); // Avoids callback merge.
308 if (ClExperimentalTracing) {
309 // Experimental support for tracing.
310 // Insert a callback with the same guard variable as used for coverage.
311 IRB.SetInsertPoint(IP);
312 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
316 char SanitizerCoverageModule::ID = 0;
317 INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
318 "SanitizerCoverage: TODO."
319 "ModulePass", false, false)
320 ModulePass *llvm::createSanitizerCoverageModulePass(int CoverageLevel) {
321 return new SanitizerCoverageModule(CoverageLevel);