blob: 07223d4df5c01992c3fd6b1a2462f47afcef6f8b [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//
13// We create a Guard boolean 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):
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +000016// if (Guard) {
17// __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";
58static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000059static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
60static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000061static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
62static const uint64_t kSanCtorAndDtorPriority = 1;
63
64static 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));
69
70static 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));
75
Kostya Serebryanycb45b122014-11-19 00:22:58 +000076static cl::opt<bool>
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));
81
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000082namespace {
83
84class SanitizerCoverageModule : public ModulePass {
85 public:
Kostya Serebryanycb45b122014-11-19 00:22:58 +000086 SanitizerCoverageModule(int CoverageLevel = 0)
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000087 : ModulePass(ID),
Kostya Serebryanycb45b122014-11-19 00:22:58 +000088 CoverageLevel(std::max(CoverageLevel, (int)ClCoverageLevel)) {}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000089 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";
94 }
95
96 void getAnalysisUsage(AnalysisUsage &AU) const override {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000097 AU.addRequired<DataLayoutPass>();
98 }
99
100 private:
101 void InjectCoverageForIndirectCalls(Function &F,
102 ArrayRef<Instruction *> IndirCalls);
103 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
104 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000105 bool InjectTracing(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000106 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
107 Function *SanCovFunction;
108 Function *SanCovIndirCallFunction;
109 Function *SanCovModuleInit;
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000110 Function *SanCovTraceEnter, *SanCovTraceBB;
Kostya Serebryany73762942014-12-16 21:24:15 +0000111 InlineAsm *EmptyAsm;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000112 Type *IntptrTy;
113 LLVMContext *C;
114
115 int CoverageLevel;
116};
117
118} // namespace
119
120static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
121 if (Function *F = dyn_cast<Function>(FuncOrBitcast))
122 return F;
123 std::string Err;
124 raw_string_ostream Stream(Err);
125 Stream << "SanitizerCoverage interface function redefined: "
126 << *FuncOrBitcast;
127 report_fatal_error(Err);
128}
129
130bool SanitizerCoverageModule::runOnModule(Module &M) {
131 if (!CoverageLevel) return false;
132 C = &(M.getContext());
133 DataLayoutPass *DLP = &getAnalysis<DataLayoutPass>();
134 IntptrTy = Type::getIntNTy(*C, DLP->getDataLayout().getPointerSizeInBits());
135 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000136 IRBuilder<> IRB(*C);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000137
138 Function *CtorFunc =
139 Function::Create(FunctionType::get(VoidTy, false),
140 GlobalValue::InternalLinkage, kSanCovModuleCtorName, &M);
141 ReturnInst::Create(*C, BasicBlock::Create(*C, "", CtorFunc));
142 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
143
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000144 SanCovFunction = checkInterfaceFunction(
145 M.getOrInsertFunction(kSanCovName, VoidTy, IRB.getInt8PtrTy(), nullptr));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000146 SanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000147 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000148 SanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000149 kSanCovModuleInitName, Type::getVoidTy(*C), IntptrTy, nullptr));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000150 SanCovModuleInit->setLinkage(Function::ExternalLinkage);
Kostya Serebryany73762942014-12-16 21:24:15 +0000151 // We insert an empty inline asm after cov callbacks to avoid callback merge.
152 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
153 StringRef(""), StringRef(""),
154 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000155
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000156 if (ClExperimentalTracing) {
157 SanCovTraceEnter = checkInterfaceFunction(
158 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, IntptrTy, nullptr));
159 SanCovTraceBB = checkInterfaceFunction(
160 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, IntptrTy, nullptr));
161 }
162
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000163 for (auto &F : M)
164 runOnFunction(F);
165
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000166 IRB.SetInsertPoint(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000167 IRB.CreateCall(SanCovModuleInit,
168 ConstantInt::get(IntptrTy, SanCovFunction->getNumUses()));
169 return true;
170}
171
172bool SanitizerCoverageModule::runOnFunction(Function &F) {
173 if (F.empty()) return false;
174 // For now instrument only functions that will also be asan-instrumented.
Kostya Serebryany543f3db2014-12-03 23:28:26 +0000175 if (!F.hasFnAttribute(Attribute::SanitizeAddress) &&
176 !F.hasFnAttribute(Attribute::SanitizeMemory))
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000177 return false;
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000178 if (CoverageLevel >= 3)
179 SplitAllCriticalEdges(F, this);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000180 SmallVector<Instruction*, 8> IndirCalls;
181 SmallVector<BasicBlock*, 16> AllBlocks;
182 for (auto &BB : F) {
183 AllBlocks.push_back(&BB);
184 if (CoverageLevel >= 4)
185 for (auto &Inst : BB) {
186 CallSite CS(&Inst);
187 if (CS && !CS.getCalledFunction())
188 IndirCalls.push_back(&Inst);
189 }
190 }
191 InjectCoverage(F, AllBlocks, IndirCalls);
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000192 InjectTracing(F, AllBlocks);
193 return true;
194}
195
196// Experimental support for tracing.
197// Basicaly, insert a callback at the beginning of every basic block.
198// Every callback gets a pointer to a uniqie global for internal storage.
199bool SanitizerCoverageModule::InjectTracing(Function &F,
200 ArrayRef<BasicBlock *> AllBlocks) {
201 if (!ClExperimentalTracing) return false;
202 Type *Ty = ArrayType::get(IntptrTy, 1); // May need to use more words later.
203 for (auto BB : AllBlocks) {
204 IRBuilder<> IRB(BB->getFirstInsertionPt());
205 GlobalVariable *TraceCache = new GlobalVariable(
206 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
207 Constant::getNullValue(Ty), "__sancov_gen_trace_cache");
208 IRB.CreateCall(&F.getEntryBlock() == BB ? SanCovTraceEnter : SanCovTraceBB,
209 IRB.CreatePointerCast(TraceCache, IntptrTy));
210 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000211 return true;
212}
213
214bool
215SanitizerCoverageModule::InjectCoverage(Function &F,
216 ArrayRef<BasicBlock *> AllBlocks,
217 ArrayRef<Instruction *> IndirCalls) {
218 if (!CoverageLevel) return false;
219
220 if (CoverageLevel == 1 ||
221 (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
222 InjectCoverageAtBlock(F, F.getEntryBlock());
223 } else {
224 for (auto BB : AllBlocks)
225 InjectCoverageAtBlock(F, *BB);
226 }
227 InjectCoverageForIndirectCalls(F, IndirCalls);
228 return true;
229}
230
231// On every indirect call we call a run-time function
232// __sanitizer_cov_indir_call* with two parameters:
233// - callee address,
234// - global cache array that contains kCacheSize pointers (zero-initialized).
235// The cache is used to speed up recording the caller-callee pairs.
236// The address of the caller is passed implicitly via caller PC.
237// kCacheSize is encoded in the name of the run-time function.
238void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
239 Function &F, ArrayRef<Instruction *> IndirCalls) {
240 if (IndirCalls.empty()) return;
241 const int kCacheSize = 16;
242 const int kCacheAlignment = 64; // Align for better performance.
243 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
244 for (auto I : IndirCalls) {
245 IRBuilder<> IRB(I);
246 CallSite CS(I);
247 Value *Callee = CS.getCalledValue();
248 if (dyn_cast<InlineAsm>(Callee)) continue;
249 GlobalVariable *CalleeCache = new GlobalVariable(
250 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
251 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
252 CalleeCache->setAlignment(kCacheAlignment);
253 IRB.CreateCall2(SanCovIndirCallFunction,
254 IRB.CreatePointerCast(Callee, IntptrTy),
255 IRB.CreatePointerCast(CalleeCache, IntptrTy));
256 }
257}
258
259void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F,
260 BasicBlock &BB) {
261 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
262 // Skip static allocas at the top of the entry block so they don't become
263 // dynamic when we split the block. If we used our optimized stack layout,
264 // then there will only be one alloca and it will come first.
265 for (; IP != BE; ++IP) {
266 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
267 if (!AI || !AI->isStaticAlloca())
268 break;
269 }
270
271 DebugLoc EntryLoc = &BB == &F.getEntryBlock()
272 ? IP->getDebugLoc().getFnDebugLoc(*C)
273 : IP->getDebugLoc();
274 IRBuilder<> IRB(IP);
275 IRB.SetCurrentDebugLocation(EntryLoc);
276 Type *Int8Ty = IRB.getInt8Ty();
277 GlobalVariable *Guard = new GlobalVariable(
278 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
279 Constant::getNullValue(Int8Ty), "__sancov_gen_cov_" + F.getName());
280 LoadInst *Load = IRB.CreateLoad(Guard);
281 Load->setAtomic(Monotonic);
282 Load->setAlignment(1);
Kostya Serebryany543f3db2014-12-03 23:28:26 +0000283 Load->setMetadata(F.getParent()->getMDKindID("nosanitize"),
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000284 MDNode::get(*C, None));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000285 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
286 Instruction *Ins = SplitBlockAndInsertIfThen(
287 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
288 IRB.SetInsertPoint(Ins);
289 IRB.SetCurrentDebugLocation(EntryLoc);
290 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000291 IRB.CreateCall(SanCovFunction, Guard);
Kostya Serebryany73762942014-12-16 21:24:15 +0000292 IRB.CreateCall(EmptyAsm); // Avoids callback merge.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000293}
294
295char SanitizerCoverageModule::ID = 0;
296INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
297 "SanitizerCoverage: TODO."
298 "ModulePass", false, false)
299ModulePass *llvm::createSanitizerCoverageModulePass(int CoverageLevel) {
300 return new SanitizerCoverageModule(CoverageLevel);
301}