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 (SCK_Function)
15 // or all blocks (SCK_BB):
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 SCK_Edge we also split critical edges this effectively
23 // instrumenting all edges.
25 // This coverage implementation provides very limited data:
26 // it only tells if a given function (block) was ever executed. No counters.
27 // But for many use cases this is what we need and the added slowdown small.
29 //===----------------------------------------------------------------------===//
31 #include "llvm/Transforms/Instrumentation.h"
32 #include "llvm/ADT/ArrayRef.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/IRBuilder.h"
38 #include "llvm/IR/InlineAsm.h"
39 #include "llvm/IR/LLVMContext.h"
40 #include "llvm/IR/MDBuilder.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Transforms/Scalar.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/ModuleUtils.h"
52 #define DEBUG_TYPE "sancov"
54 static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
55 static const char *const kSanCovName = "__sanitizer_cov";
56 static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check";
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 kSanCovTraceCmp = "__sanitizer_cov_trace_cmp";
61 static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
62 static const uint64_t kSanCtorAndDtorPriority = 2;
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<unsigned> ClCoverageBlockThreshold(
71 "sanitizer-coverage-block-threshold",
72 cl::desc("Use a callback with a guard check inside it if there are"
73 " more than this number of blocks."),
74 cl::Hidden, cl::init(500));
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));
83 ClExperimentalCMPTracing("sanitizer-coverage-experimental-trace-compares",
84 cl::desc("Experimental tracing of CMP and similar "
86 cl::Hidden, cl::init(false));
88 // Experimental 8-bit counters used as an additional search heuristic during
89 // coverage-guided fuzzing.
90 // The counters are not thread-friendly:
91 // - contention on these counters may cause significant slowdown;
92 // - the counter updates are racy and the results may be inaccurate.
93 // They are also inaccurate due to 8-bit integer overflow.
94 static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
95 cl::desc("Experimental 8-bit counters"),
96 cl::Hidden, cl::init(false));
100 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
101 SanitizerCoverageOptions Res;
102 switch (LegacyCoverageLevel) {
104 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
107 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
110 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
113 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
116 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
117 Res.IndirectCalls = true;
123 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
124 // Sets CoverageType and IndirectCalls.
125 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
126 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
127 Options.IndirectCalls |= CLOpts.IndirectCalls;
128 Options.TraceBB |= ClExperimentalTracing;
129 Options.TraceCmp |= ClExperimentalCMPTracing;
130 Options.Use8bitCounters |= ClUse8bitCounters;
134 class SanitizerCoverageModule : public ModulePass {
136 SanitizerCoverageModule(
137 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
138 : ModulePass(ID), Options(OverrideFromCL(Options)) {}
139 bool runOnModule(Module &M) override;
140 bool runOnFunction(Function &F);
141 static char ID; // Pass identification, replacement for typeid
142 const char *getPassName() const override {
143 return "SanitizerCoverageModule";
147 void InjectCoverageForIndirectCalls(Function &F,
148 ArrayRef<Instruction *> IndirCalls);
149 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
150 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
151 void SetNoSanitizeMetadata(Instruction *I);
152 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
153 unsigned NumberOfInstrumentedBlocks() {
154 return SanCovFunction->getNumUses() + SanCovWithCheckFunction->getNumUses();
156 Function *SanCovFunction;
157 Function *SanCovWithCheckFunction;
158 Function *SanCovIndirCallFunction;
159 Function *SanCovTraceEnter, *SanCovTraceBB;
160 Function *SanCovTraceCmpFunction;
162 Type *IntptrTy, *Int64Ty;
164 const DataLayout *DL;
166 GlobalVariable *GuardArray;
167 GlobalVariable *EightBitCounterArray;
169 SanitizerCoverageOptions Options;
174 bool SanitizerCoverageModule::runOnModule(Module &M) {
175 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
177 C = &(M.getContext());
178 DL = &M.getDataLayout();
179 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
180 Type *VoidTy = Type::getVoidTy(*C);
182 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
183 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
184 Int64Ty = IRB.getInt64Ty();
186 SanCovFunction = checkSanitizerInterfaceFunction(
187 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
188 SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
189 M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
190 SanCovIndirCallFunction =
191 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
192 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
193 SanCovTraceCmpFunction =
194 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
195 kSanCovTraceCmp, VoidTy, Int64Ty, Int64Ty, Int64Ty, nullptr));
197 // We insert an empty inline asm after cov callbacks to avoid callback merge.
198 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
199 StringRef(""), StringRef(""),
200 /*hasSideEffects=*/true);
202 if (Options.TraceBB) {
203 SanCovTraceEnter = checkSanitizerInterfaceFunction(
204 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
205 SanCovTraceBB = checkSanitizerInterfaceFunction(
206 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
209 // At this point we create a dummy array of guards because we don't
210 // know how many elements we will need.
211 Type *Int32Ty = IRB.getInt32Ty();
212 Type *Int8Ty = IRB.getInt8Ty();
215 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
216 nullptr, "__sancov_gen_cov_tmp");
217 if (Options.Use8bitCounters)
218 EightBitCounterArray =
219 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
220 nullptr, "__sancov_gen_cov_tmp");
225 auto N = NumberOfInstrumentedBlocks();
227 // Now we know how many elements we need. Create an array of guards
228 // with one extra element at the beginning for the size.
229 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
230 GlobalVariable *RealGuardArray = new GlobalVariable(
231 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
232 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
235 // Replace the dummy array with the real one.
236 GuardArray->replaceAllUsesWith(
237 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
238 GuardArray->eraseFromParent();
240 GlobalVariable *RealEightBitCounterArray;
241 if (Options.Use8bitCounters) {
242 // Make sure the array is 16-aligned.
243 static const int kCounterAlignment = 16;
245 ArrayType::get(Int8Ty, RoundUpToAlignment(N, kCounterAlignment));
246 RealEightBitCounterArray = new GlobalVariable(
247 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
248 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
249 RealEightBitCounterArray->setAlignment(kCounterAlignment);
250 EightBitCounterArray->replaceAllUsesWith(
251 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
252 EightBitCounterArray->eraseFromParent();
255 // Create variable for module (compilation unit) name
256 Constant *ModNameStrConst =
257 ConstantDataArray::getString(M.getContext(), M.getName(), true);
258 GlobalVariable *ModuleName =
259 new GlobalVariable(M, ModNameStrConst->getType(), true,
260 GlobalValue::PrivateLinkage, ModNameStrConst);
263 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
264 M, kSanCovModuleCtorName, kSanCovModuleInitName,
265 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
266 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
267 ConstantInt::get(IntptrTy, N),
268 Options.Use8bitCounters
269 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
270 : Constant::getNullValue(Int8PtrTy),
271 IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
273 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
278 bool SanitizerCoverageModule::runOnFunction(Function &F) {
279 if (F.empty()) return false;
280 if (F.getName().find(".module_ctor") != std::string::npos)
281 return false; // Should not instrument sanitizer init functions.
282 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
283 SplitAllCriticalEdges(F);
284 SmallVector<Instruction*, 8> IndirCalls;
285 SmallVector<BasicBlock*, 16> AllBlocks;
286 SmallVector<Instruction*, 8> CmpTraceTargets;
288 AllBlocks.push_back(&BB);
289 for (auto &Inst : BB) {
290 if (Options.IndirectCalls) {
292 if (CS && !CS.getCalledFunction())
293 IndirCalls.push_back(&Inst);
295 if (Options.TraceCmp && isa<ICmpInst>(&Inst))
296 CmpTraceTargets.push_back(&Inst);
299 InjectCoverage(F, AllBlocks);
300 InjectCoverageForIndirectCalls(F, IndirCalls);
301 InjectTraceForCmp(F, CmpTraceTargets);
305 bool SanitizerCoverageModule::InjectCoverage(Function &F,
306 ArrayRef<BasicBlock *> AllBlocks) {
307 switch (Options.CoverageType) {
308 case SanitizerCoverageOptions::SCK_None:
310 case SanitizerCoverageOptions::SCK_Function:
311 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
314 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
315 for (auto BB : AllBlocks)
316 InjectCoverageAtBlock(F, *BB, UseCalls);
322 // On every indirect call we call a run-time function
323 // __sanitizer_cov_indir_call* with two parameters:
325 // - global cache array that contains kCacheSize pointers (zero-initialized).
326 // The cache is used to speed up recording the caller-callee pairs.
327 // The address of the caller is passed implicitly via caller PC.
328 // kCacheSize is encoded in the name of the run-time function.
329 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
330 Function &F, ArrayRef<Instruction *> IndirCalls) {
331 if (IndirCalls.empty()) return;
332 const int kCacheSize = 16;
333 const int kCacheAlignment = 64; // Align for better performance.
334 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
335 for (auto I : IndirCalls) {
338 Value *Callee = CS.getCalledValue();
339 if (isa<InlineAsm>(Callee)) continue;
340 GlobalVariable *CalleeCache = new GlobalVariable(
341 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
342 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
343 CalleeCache->setAlignment(kCacheAlignment);
344 IRB.CreateCall2(SanCovIndirCallFunction,
345 IRB.CreatePointerCast(Callee, IntptrTy),
346 IRB.CreatePointerCast(CalleeCache, IntptrTy));
350 void SanitizerCoverageModule::InjectTraceForCmp(
351 Function &F, ArrayRef<Instruction *> CmpTraceTargets) {
352 for (auto I : CmpTraceTargets) {
353 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
354 IRBuilder<> IRB(ICMP);
355 Value *A0 = ICMP->getOperand(0);
356 Value *A1 = ICMP->getOperand(1);
357 if (!A0->getType()->isIntegerTy()) continue;
358 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
359 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
361 SanCovTraceCmpFunction,
362 ConstantInt::get(Int64Ty, (TypeSize << 32) | ICMP->getPredicate()),
363 IRB.CreateIntCast(A0, Int64Ty, true),
364 IRB.CreateIntCast(A1, Int64Ty, true));
369 void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
371 I->getParent()->getParent()->getParent()->getMDKindID("nosanitize"),
372 MDNode::get(*C, None));
375 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
377 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
378 // Skip static allocas at the top of the entry block so they don't become
379 // dynamic when we split the block. If we used our optimized stack layout,
380 // then there will only be one alloca and it will come first.
381 for (; IP != BE; ++IP) {
382 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
383 if (!AI || !AI->isStaticAlloca())
387 bool IsEntryBB = &BB == &F.getEntryBlock();
388 DebugLoc EntryLoc = IsEntryBB && IP->getDebugLoc()
389 ? IP->getDebugLoc().getFnDebugLoc()
392 IRB.SetCurrentDebugLocation(EntryLoc);
393 SmallVector<Value *, 1> Indices;
394 Value *GuardP = IRB.CreateAdd(
395 IRB.CreatePointerCast(GuardArray, IntptrTy),
396 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
397 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
398 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
400 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
402 LoadInst *Load = IRB.CreateLoad(GuardP);
403 Load->setAtomic(Monotonic);
404 Load->setAlignment(4);
405 SetNoSanitizeMetadata(Load);
406 Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
407 Instruction *Ins = SplitBlockAndInsertIfThen(
408 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
409 IRB.SetInsertPoint(Ins);
410 IRB.SetCurrentDebugLocation(EntryLoc);
411 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
412 IRB.CreateCall(SanCovFunction, GuardP);
413 IRB.CreateCall(EmptyAsm); // Avoids callback merge.
416 if (Options.Use8bitCounters) {
417 IRB.SetInsertPoint(IP);
418 Value *P = IRB.CreateAdd(
419 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
420 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
421 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
422 LoadInst *LI = IRB.CreateLoad(P);
423 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
424 StoreInst *SI = IRB.CreateStore(Inc, P);
425 SetNoSanitizeMetadata(LI);
426 SetNoSanitizeMetadata(SI);
429 if (Options.TraceBB) {
430 // Experimental support for tracing.
431 // Insert a callback with the same guard variable as used for coverage.
432 IRB.SetInsertPoint(IP);
433 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
437 char SanitizerCoverageModule::ID = 0;
438 INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
439 "SanitizerCoverage: TODO."
440 "ModulePass", false, false)
441 ModulePass *llvm::createSanitizerCoverageModulePass(
442 const SanitizerCoverageOptions &Options) {
443 return new SanitizerCoverageModule(Options);