blob: 798cd55f87e7270dcdc1f76470c36be1109c1ad1 [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 Serebryany9fdeb372014-12-23 22:32:17 +0000140 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000141
142 Function *CtorFunc =
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);
147
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000148 SanCovFunction = checkInterfaceFunction(
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000149 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000150 SanCovWithCheckFunction = checkInterfaceFunction(
151 M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000152 SanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000153 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000154 SanCovModuleInit = checkInterfaceFunction(
155 M.getOrInsertFunction(kSanCovModuleInitName, Type::getVoidTy(*C),
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000156 Int32PtrTy, IntptrTy, nullptr));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000157 SanCovModuleInit->setLinkage(Function::ExternalLinkage);
Kostya Serebryany73762942014-12-16 21:24:15 +0000158 // 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);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000162
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000163 if (ClExperimentalTracing) {
164 SanCovTraceEnter = checkInterfaceFunction(
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000165 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000166 SanCovTraceBB = checkInterfaceFunction(
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000167 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000168 }
169
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000170 // 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();
173 GuardArray =
174 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
175 nullptr, "__sancov_gen_cov_tmp");
176
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000177 for (auto &F : M)
178 runOnFunction(F);
179
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000180 // 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");
187
188 // Replace the dummy array with the real one.
189 GuardArray->replaceAllUsesWith(
190 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
191 GuardArray->eraseFromParent();
192
193 // Call __sanitizer_cov_module_init
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000194 IRB.SetInsertPoint(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000195 IRB.CreateCall2(SanCovModuleInit,
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000196 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
197 ConstantInt::get(IntptrTy, SanCovFunction->getNumUses()));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000198 return true;
199}
200
201bool SanitizerCoverageModule::runOnFunction(Function &F) {
202 if (F.empty()) return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000203 if (F.getName().find(".module_ctor") != std::string::npos)
204 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000205 if (CoverageLevel >= 3)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000206 SplitAllCriticalEdges(F);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000207 SmallVector<Instruction*, 8> IndirCalls;
208 SmallVector<BasicBlock*, 16> AllBlocks;
209 for (auto &BB : F) {
210 AllBlocks.push_back(&BB);
211 if (CoverageLevel >= 4)
212 for (auto &Inst : BB) {
213 CallSite CS(&Inst);
214 if (CS && !CS.getCalledFunction())
215 IndirCalls.push_back(&Inst);
216 }
217 }
218 InjectCoverage(F, AllBlocks, IndirCalls);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000219 return true;
220}
221
222bool
223SanitizerCoverageModule::InjectCoverage(Function &F,
224 ArrayRef<BasicBlock *> AllBlocks,
225 ArrayRef<Instruction *> IndirCalls) {
226 if (!CoverageLevel) return false;
227
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000228 if (CoverageLevel == 1) {
229 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000230 } else {
231 for (auto BB : AllBlocks)
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000232 InjectCoverageAtBlock(F, *BB,
233 ClCoverageBlockThreshold < AllBlocks.size());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000234 }
235 InjectCoverageForIndirectCalls(F, IndirCalls);
236 return true;
237}
238
239// On every indirect call we call a run-time function
240// __sanitizer_cov_indir_call* with two parameters:
241// - callee address,
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.
246void 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) {
253 IRBuilder<> IRB(I);
254 CallSite CS(I);
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));
264 }
265}
266
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000267void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
268 bool UseCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000269 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())
276 break;
277 }
278
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000279 bool IsEntryBB = &BB == &F.getEntryBlock();
280 DebugLoc EntryLoc =
281 IsEntryBB ? IP->getDebugLoc().getFnDebugLoc(*C) : IP->getDebugLoc();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000282 IRBuilder<> IRB(IP);
283 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000284 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);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000290 if (UseCalls) {
291 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
292 } else {
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.
306 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000307
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);
313 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000314}
315
316char SanitizerCoverageModule::ID = 0;
317INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
318 "SanitizerCoverage: TODO."
319 "ModulePass", false, false)
320ModulePass *llvm::createSanitizerCoverageModulePass(int CoverageLevel) {
321 return new SanitizerCoverageModule(CoverageLevel);
322}