blob: 60d7f9f69d7567f75757cf5213a54a0e5686bfbb [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"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/MDBuilder.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Type.h"
44#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Support/raw_ostream.h"
47#include "llvm/Transforms/Scalar.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/ModuleUtils.h"
50
51using namespace llvm;
52
53#define DEBUG_TYPE "sancov"
54
55static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
56static const char *const kSanCovName = "__sanitizer_cov";
57static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000058static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
59static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000060static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
61static const uint64_t kSanCtorAndDtorPriority = 1;
62
63static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
64 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
65 "3: all blocks and critical edges, "
66 "4: above plus indirect calls"),
67 cl::Hidden, cl::init(0));
68
69static cl::opt<int> ClCoverageBlockThreshold(
70 "sanitizer-coverage-block-threshold",
71 cl::desc("Add coverage instrumentation only to the entry block if there "
72 "are more than this number of blocks."),
73 cl::Hidden, cl::init(1500));
74
Kostya Serebryanycb45b122014-11-19 00:22:58 +000075static cl::opt<bool>
76 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
77 cl::desc("Experimental basic-block tracing: insert "
78 "callbacks at every basic block"),
79 cl::Hidden, cl::init(false));
80
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000081namespace {
82
83class SanitizerCoverageModule : public ModulePass {
84 public:
Kostya Serebryanycb45b122014-11-19 00:22:58 +000085 SanitizerCoverageModule(int CoverageLevel = 0)
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000086 : ModulePass(ID),
Kostya Serebryanycb45b122014-11-19 00:22:58 +000087 CoverageLevel(std::max(CoverageLevel, (int)ClCoverageLevel)) {}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000088 bool runOnModule(Module &M) override;
89 bool runOnFunction(Function &F);
90 static char ID; // Pass identification, replacement for typeid
91 const char *getPassName() const override {
92 return "SanitizerCoverageModule";
93 }
94
95 void getAnalysisUsage(AnalysisUsage &AU) const override {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000096 AU.addRequired<DataLayoutPass>();
97 }
98
99 private:
100 void InjectCoverageForIndirectCalls(Function &F,
101 ArrayRef<Instruction *> IndirCalls);
102 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
103 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000104 bool InjectTracing(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000105 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
106 Function *SanCovFunction;
107 Function *SanCovIndirCallFunction;
108 Function *SanCovModuleInit;
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000109 Function *SanCovTraceEnter, *SanCovTraceBB;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000110 Type *IntptrTy;
111 LLVMContext *C;
112
113 int CoverageLevel;
114};
115
116} // namespace
117
118static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
119 if (Function *F = dyn_cast<Function>(FuncOrBitcast))
120 return F;
121 std::string Err;
122 raw_string_ostream Stream(Err);
123 Stream << "SanitizerCoverage interface function redefined: "
124 << *FuncOrBitcast;
125 report_fatal_error(Err);
126}
127
128bool SanitizerCoverageModule::runOnModule(Module &M) {
129 if (!CoverageLevel) return false;
130 C = &(M.getContext());
131 DataLayoutPass *DLP = &getAnalysis<DataLayoutPass>();
132 IntptrTy = Type::getIntNTy(*C, DLP->getDataLayout().getPointerSizeInBits());
133 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000134 IRBuilder<> IRB(*C);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000135
136 Function *CtorFunc =
137 Function::Create(FunctionType::get(VoidTy, false),
138 GlobalValue::InternalLinkage, kSanCovModuleCtorName, &M);
139 ReturnInst::Create(*C, BasicBlock::Create(*C, "", CtorFunc));
140 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
141
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000142 SanCovFunction = checkInterfaceFunction(
143 M.getOrInsertFunction(kSanCovName, VoidTy, IRB.getInt8PtrTy(), nullptr));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000144 SanCovIndirCallFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000145 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000146 SanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000147 kSanCovModuleInitName, Type::getVoidTy(*C), IntptrTy, nullptr));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000148 SanCovModuleInit->setLinkage(Function::ExternalLinkage);
149
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000150 if (ClExperimentalTracing) {
151 SanCovTraceEnter = checkInterfaceFunction(
152 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, IntptrTy, nullptr));
153 SanCovTraceBB = checkInterfaceFunction(
154 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, IntptrTy, nullptr));
155 }
156
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000157 for (auto &F : M)
158 runOnFunction(F);
159
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000160 IRB.SetInsertPoint(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000161 IRB.CreateCall(SanCovModuleInit,
162 ConstantInt::get(IntptrTy, SanCovFunction->getNumUses()));
163 return true;
164}
165
166bool SanitizerCoverageModule::runOnFunction(Function &F) {
167 if (F.empty()) return false;
168 // For now instrument only functions that will also be asan-instrumented.
169 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
170 return false;
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000171 if (CoverageLevel >= 3)
172 SplitAllCriticalEdges(F, this);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000173 SmallVector<Instruction*, 8> IndirCalls;
174 SmallVector<BasicBlock*, 16> AllBlocks;
175 for (auto &BB : F) {
176 AllBlocks.push_back(&BB);
177 if (CoverageLevel >= 4)
178 for (auto &Inst : BB) {
179 CallSite CS(&Inst);
180 if (CS && !CS.getCalledFunction())
181 IndirCalls.push_back(&Inst);
182 }
183 }
184 InjectCoverage(F, AllBlocks, IndirCalls);
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000185 InjectTracing(F, AllBlocks);
186 return true;
187}
188
189// Experimental support for tracing.
190// Basicaly, insert a callback at the beginning of every basic block.
191// Every callback gets a pointer to a uniqie global for internal storage.
192bool SanitizerCoverageModule::InjectTracing(Function &F,
193 ArrayRef<BasicBlock *> AllBlocks) {
194 if (!ClExperimentalTracing) return false;
195 Type *Ty = ArrayType::get(IntptrTy, 1); // May need to use more words later.
196 for (auto BB : AllBlocks) {
197 IRBuilder<> IRB(BB->getFirstInsertionPt());
198 GlobalVariable *TraceCache = new GlobalVariable(
199 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
200 Constant::getNullValue(Ty), "__sancov_gen_trace_cache");
201 IRB.CreateCall(&F.getEntryBlock() == BB ? SanCovTraceEnter : SanCovTraceBB,
202 IRB.CreatePointerCast(TraceCache, IntptrTy));
203 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000204 return true;
205}
206
207bool
208SanitizerCoverageModule::InjectCoverage(Function &F,
209 ArrayRef<BasicBlock *> AllBlocks,
210 ArrayRef<Instruction *> IndirCalls) {
211 if (!CoverageLevel) return false;
212
213 if (CoverageLevel == 1 ||
214 (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
215 InjectCoverageAtBlock(F, F.getEntryBlock());
216 } else {
217 for (auto BB : AllBlocks)
218 InjectCoverageAtBlock(F, *BB);
219 }
220 InjectCoverageForIndirectCalls(F, IndirCalls);
221 return true;
222}
223
224// On every indirect call we call a run-time function
225// __sanitizer_cov_indir_call* with two parameters:
226// - callee address,
227// - global cache array that contains kCacheSize pointers (zero-initialized).
228// The cache is used to speed up recording the caller-callee pairs.
229// The address of the caller is passed implicitly via caller PC.
230// kCacheSize is encoded in the name of the run-time function.
231void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
232 Function &F, ArrayRef<Instruction *> IndirCalls) {
233 if (IndirCalls.empty()) return;
234 const int kCacheSize = 16;
235 const int kCacheAlignment = 64; // Align for better performance.
236 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
237 for (auto I : IndirCalls) {
238 IRBuilder<> IRB(I);
239 CallSite CS(I);
240 Value *Callee = CS.getCalledValue();
241 if (dyn_cast<InlineAsm>(Callee)) continue;
242 GlobalVariable *CalleeCache = new GlobalVariable(
243 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
244 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
245 CalleeCache->setAlignment(kCacheAlignment);
246 IRB.CreateCall2(SanCovIndirCallFunction,
247 IRB.CreatePointerCast(Callee, IntptrTy),
248 IRB.CreatePointerCast(CalleeCache, IntptrTy));
249 }
250}
251
252void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F,
253 BasicBlock &BB) {
254 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
255 // Skip static allocas at the top of the entry block so they don't become
256 // dynamic when we split the block. If we used our optimized stack layout,
257 // then there will only be one alloca and it will come first.
258 for (; IP != BE; ++IP) {
259 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
260 if (!AI || !AI->isStaticAlloca())
261 break;
262 }
263
264 DebugLoc EntryLoc = &BB == &F.getEntryBlock()
265 ? IP->getDebugLoc().getFnDebugLoc(*C)
266 : IP->getDebugLoc();
267 IRBuilder<> IRB(IP);
268 IRB.SetCurrentDebugLocation(EntryLoc);
269 Type *Int8Ty = IRB.getInt8Ty();
270 GlobalVariable *Guard = new GlobalVariable(
271 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
272 Constant::getNullValue(Int8Ty), "__sancov_gen_cov_" + F.getName());
273 LoadInst *Load = IRB.CreateLoad(Guard);
274 Load->setAtomic(Monotonic);
275 Load->setAlignment(1);
276 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
277 Instruction *Ins = SplitBlockAndInsertIfThen(
278 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
279 IRB.SetInsertPoint(Ins);
280 IRB.SetCurrentDebugLocation(EntryLoc);
281 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000282 IRB.CreateCall(SanCovFunction, Guard);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000283}
284
285char SanitizerCoverageModule::ID = 0;
286INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
287 "SanitizerCoverage: TODO."
288 "ModulePass", false, false)
289ModulePass *llvm::createSanitizerCoverageModulePass(int CoverageLevel) {
290 return new SanitizerCoverageModule(CoverageLevel);
291}