blob: 8c56e8709e2e650684aa21d9dac319fc85debd9d [file] [log] [blame]
Kostya Serebryany29a18dc2014-11-11 22:14:37 +00001//===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Coverage instrumentation that works with AddressSanitizer
11// and potentially with other Sanitizers.
12//
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000013// We create a Guard variable with the same linkage
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000014// as the function and inject this code into the entry block (CoverageLevel=1)
15// or all blocks (CoverageLevel>=2):
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000016// if (Guard < 0) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +000017// __sanitizer_cov(&Guard);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000018// }
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).
21//
22// With CoverageLevel>=3 we also split critical edges this effectively
23// instrumenting all edges.
24//
25// CoverageLevel>=4 add indirect call profiling implented as a function call.
26//
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.
30//
31//===----------------------------------------------------------------------===//
32
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"
Kostya Serebryany73762942014-12-16 21:24:15 +000040#include "llvm/IR/InlineAsm.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000041#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"
51
52using namespace llvm;
53
54#define DEBUG_TYPE "sancov"
55
56static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
57static const char *const kSanCovName = "__sanitizer_cov";
Kostya Serebryany77cc7292015-02-04 01:21:45 +000058static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000059static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000060static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
61static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000062static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
Evgeniy Stepanov3fdfc7b2015-01-27 15:01:22 +000063static const uint64_t kSanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000064
65static 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));
70
Kostya Serebryany77cc7292015-02-04 01:21:45 +000071static cl::opt<unsigned> ClCoverageBlockThreshold(
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000072 "sanitizer-coverage-block-threshold",
Kostya Serebryany77cc7292015-02-04 01:21:45 +000073 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));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000076
Kostya Serebryanycb45b122014-11-19 00:22:58 +000077static cl::opt<bool>
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));
82
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000083namespace {
84
85class SanitizerCoverageModule : public ModulePass {
86 public:
Kostya Serebryanycb45b122014-11-19 00:22:58 +000087 SanitizerCoverageModule(int CoverageLevel = 0)
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000088 : ModulePass(ID),
Kostya Serebryanycb45b122014-11-19 00:22:58 +000089 CoverageLevel(std::max(CoverageLevel, (int)ClCoverageLevel)) {}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000090 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";
95 }
96
97 void getAnalysisUsage(AnalysisUsage &AU) const override {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000098 AU.addRequired<DataLayoutPass>();
99 }
100
101 private:
102 void InjectCoverageForIndirectCalls(Function &F,
103 ArrayRef<Instruction *> IndirCalls);
104 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
105 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000106 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000107 Function *SanCovFunction;
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000108 Function *SanCovWithCheckFunction;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000109 Function *SanCovIndirCallFunction;
110 Function *SanCovModuleInit;
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000111 Function *SanCovTraceEnter, *SanCovTraceBB;
Kostya Serebryany73762942014-12-16 21:24:15 +0000112 InlineAsm *EmptyAsm;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000113 Type *IntptrTy;
114 LLVMContext *C;
115
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000116 GlobalVariable *GuardArray;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000117
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000118 int CoverageLevel;
119};
120
121} // namespace
122
123static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
124 if (Function *F = dyn_cast<Function>(FuncOrBitcast))
125 return F;
126 std::string Err;
127 raw_string_ostream Stream(Err);
128 Stream << "SanitizerCoverage interface function redefined: "
129 << *FuncOrBitcast;
130 report_fatal_error(Err);
131}
132
133bool 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);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000139 IRBuilder<> IRB(*C);
Kostya Serebryany88599462015-02-20 00:30:44 +0000140 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000141 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000142
143 Function *CtorFunc =
144 Function::Create(FunctionType::get(VoidTy, false),
145 GlobalValue::InternalLinkage, kSanCovModuleCtorName, &M);
146 ReturnInst::Create(*C, BasicBlock::Create(*C, "", CtorFunc));
147 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
148
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000149 SanCovFunction = checkInterfaceFunction(
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000150 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000151 SanCovWithCheckFunction = checkInterfaceFunction(
152 M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000153 SanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000154 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000155 SanCovModuleInit = checkInterfaceFunction(
156 M.getOrInsertFunction(kSanCovModuleInitName, Type::getVoidTy(*C),
Kostya Serebryany88599462015-02-20 00:30:44 +0000157 Int32PtrTy, IntptrTy, Int8PtrTy, nullptr));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000158 SanCovModuleInit->setLinkage(Function::ExternalLinkage);
Kostya Serebryany73762942014-12-16 21:24:15 +0000159 // We insert an empty inline asm after cov callbacks to avoid callback merge.
160 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
161 StringRef(""), StringRef(""),
162 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000163
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000164 if (ClExperimentalTracing) {
165 SanCovTraceEnter = checkInterfaceFunction(
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000166 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000167 SanCovTraceBB = checkInterfaceFunction(
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000168 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000169 }
170
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000171 // At this point we create a dummy array of guards because we don't
172 // know how many elements we will need.
173 Type *Int32Ty = IRB.getInt32Ty();
174 GuardArray =
175 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
176 nullptr, "__sancov_gen_cov_tmp");
177
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000178 for (auto &F : M)
179 runOnFunction(F);
180
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000181 // Now we know how many elements we need. Create an array of guards
182 // with one extra element at the beginning for the size.
183 Type *Int32ArrayNTy =
184 ArrayType::get(Int32Ty, SanCovFunction->getNumUses() + 1);
185 GlobalVariable *RealGuardArray = new GlobalVariable(
186 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
187 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
188
189 // Replace the dummy array with the real one.
190 GuardArray->replaceAllUsesWith(
191 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
192 GuardArray->eraseFromParent();
193
Kostya Serebryany88599462015-02-20 00:30:44 +0000194 // Create variable for module (compilation unit) name
195 Constant *ModNameStrConst =
196 ConstantDataArray::getString(M.getContext(), M.getName(), true);
197 GlobalVariable *ModuleName =
198 new GlobalVariable(M, ModNameStrConst->getType(), true,
199 GlobalValue::PrivateLinkage, ModNameStrConst);
200
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000201 // Call __sanitizer_cov_module_init
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000202 IRB.SetInsertPoint(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany88599462015-02-20 00:30:44 +0000203 IRB.CreateCall3(SanCovModuleInit,
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000204 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
Kostya Serebryany88599462015-02-20 00:30:44 +0000205 ConstantInt::get(IntptrTy, SanCovFunction->getNumUses()),
206 IRB.CreatePointerCast(ModuleName, Int8PtrTy));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000207 return true;
208}
209
210bool SanitizerCoverageModule::runOnFunction(Function &F) {
211 if (F.empty()) return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000212 if (F.getName().find(".module_ctor") != std::string::npos)
213 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000214 if (CoverageLevel >= 3)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000215 SplitAllCriticalEdges(F);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000216 SmallVector<Instruction*, 8> IndirCalls;
217 SmallVector<BasicBlock*, 16> AllBlocks;
218 for (auto &BB : F) {
219 AllBlocks.push_back(&BB);
220 if (CoverageLevel >= 4)
221 for (auto &Inst : BB) {
222 CallSite CS(&Inst);
223 if (CS && !CS.getCalledFunction())
224 IndirCalls.push_back(&Inst);
225 }
226 }
227 InjectCoverage(F, AllBlocks, IndirCalls);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000228 return true;
229}
230
231bool
232SanitizerCoverageModule::InjectCoverage(Function &F,
233 ArrayRef<BasicBlock *> AllBlocks,
234 ArrayRef<Instruction *> IndirCalls) {
235 if (!CoverageLevel) return false;
236
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000237 if (CoverageLevel == 1) {
238 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000239 } else {
240 for (auto BB : AllBlocks)
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000241 InjectCoverageAtBlock(F, *BB,
242 ClCoverageBlockThreshold < AllBlocks.size());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000243 }
244 InjectCoverageForIndirectCalls(F, IndirCalls);
245 return true;
246}
247
248// On every indirect call we call a run-time function
249// __sanitizer_cov_indir_call* with two parameters:
250// - callee address,
251// - global cache array that contains kCacheSize pointers (zero-initialized).
252// The cache is used to speed up recording the caller-callee pairs.
253// The address of the caller is passed implicitly via caller PC.
254// kCacheSize is encoded in the name of the run-time function.
255void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
256 Function &F, ArrayRef<Instruction *> IndirCalls) {
257 if (IndirCalls.empty()) return;
258 const int kCacheSize = 16;
259 const int kCacheAlignment = 64; // Align for better performance.
260 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
261 for (auto I : IndirCalls) {
262 IRBuilder<> IRB(I);
263 CallSite CS(I);
264 Value *Callee = CS.getCalledValue();
265 if (dyn_cast<InlineAsm>(Callee)) continue;
266 GlobalVariable *CalleeCache = new GlobalVariable(
267 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
268 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
269 CalleeCache->setAlignment(kCacheAlignment);
270 IRB.CreateCall2(SanCovIndirCallFunction,
271 IRB.CreatePointerCast(Callee, IntptrTy),
272 IRB.CreatePointerCast(CalleeCache, IntptrTy));
273 }
274}
275
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000276void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
277 bool UseCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000278 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
279 // Skip static allocas at the top of the entry block so they don't become
280 // dynamic when we split the block. If we used our optimized stack layout,
281 // then there will only be one alloca and it will come first.
282 for (; IP != BE; ++IP) {
283 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
284 if (!AI || !AI->isStaticAlloca())
285 break;
286 }
287
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000288 bool IsEntryBB = &BB == &F.getEntryBlock();
289 DebugLoc EntryLoc =
290 IsEntryBB ? IP->getDebugLoc().getFnDebugLoc(*C) : IP->getDebugLoc();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000291 IRBuilder<> IRB(IP);
292 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000293 SmallVector<Value *, 1> Indices;
294 Value *GuardP = IRB.CreateAdd(
295 IRB.CreatePointerCast(GuardArray, IntptrTy),
296 ConstantInt::get(IntptrTy, (1 + SanCovFunction->getNumUses()) * 4));
297 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
298 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000299 if (UseCalls) {
300 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
301 } else {
302 LoadInst *Load = IRB.CreateLoad(GuardP);
303 Load->setAtomic(Monotonic);
304 Load->setAlignment(4);
305 Load->setMetadata(F.getParent()->getMDKindID("nosanitize"),
306 MDNode::get(*C, None));
307 Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
308 Instruction *Ins = SplitBlockAndInsertIfThen(
309 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
310 IRB.SetInsertPoint(Ins);
311 IRB.SetCurrentDebugLocation(EntryLoc);
312 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
313 IRB.CreateCall(SanCovFunction, GuardP);
314 IRB.CreateCall(EmptyAsm); // Avoids callback merge.
315 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000316
317 if (ClExperimentalTracing) {
318 // Experimental support for tracing.
319 // Insert a callback with the same guard variable as used for coverage.
320 IRB.SetInsertPoint(IP);
321 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
322 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000323}
324
325char SanitizerCoverageModule::ID = 0;
326INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
327 "SanitizerCoverage: TODO."
328 "ModulePass", false, false)
329ModulePass *llvm::createSanitizerCoverageModulePass(int CoverageLevel) {
330 return new SanitizerCoverageModule(CoverageLevel);
331}