blob: f7bf44c662bea1dab5b2bb491268c574f290998f [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
Alexey Samsonov3514f272015-05-07 01:00:31 +000014// as the function and inject this code into the entry block (SCK_Function)
15// or all blocks (SCK_BB):
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//
Alexey Samsonov3514f272015-05-07 01:00:31 +000022// With SCK_Edge we also split critical edges this effectively
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000023// instrumenting all edges.
24//
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000025// 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.
28//
29//===----------------------------------------------------------------------===//
30
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000031#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/SmallVector.h"
David Majnemer70497c62015-12-02 23:06:39 +000033#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruth30061152016-03-18 22:43:42 +000034#include "llvm/Analysis/PostDominators.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000035#include "llvm/IR/CFG.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000036#include "llvm/IR/CallSite.h"
37#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000038#include "llvm/IR/DebugInfo.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000039#include "llvm/IR/Dominators.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000040#include "llvm/IR/Function.h"
41#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000042#include "llvm/IR/InlineAsm.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000043#include "llvm/IR/LLVMContext.h"
44#include "llvm/IR/MDBuilder.h"
45#include "llvm/IR/Module.h"
46#include "llvm/IR/Type.h"
47#include "llvm/Support/CommandLine.h"
48#include "llvm/Support/Debug.h"
49#include "llvm/Support/raw_ostream.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000050#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000051#include "llvm/Transforms/Scalar.h"
52#include "llvm/Transforms/Utils/BasicBlockUtils.h"
53#include "llvm/Transforms/Utils/ModuleUtils.h"
54
55using namespace llvm;
56
57#define DEBUG_TYPE "sancov"
58
Mike Aizatsky759aca02016-03-18 23:29:29 +000059static const char *const SanCovModuleInitName = "__sanitizer_cov_module_init";
60static const char *const SanCovName = "__sanitizer_cov";
61static const char *const SanCovWithCheckName = "__sanitizer_cov_with_check";
62static const char *const SanCovIndirCallName = "__sanitizer_cov_indir_call16";
63static const char *const SanCovTracePCIndirName =
64 "__sanitizer_cov_trace_pc_indir";
65static const char *const SanCovTraceEnterName =
66 "__sanitizer_cov_trace_func_enter";
67static const char *const SanCovTraceBBName =
68 "__sanitizer_cov_trace_basic_block";
69static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
70static const char *const SanCovTraceCmpName = "__sanitizer_cov_trace_cmp";
71static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
72static const char *const SanCovModuleCtorName = "sancov.module_ctor";
73static const uint64_t SanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000074
Mike Aizatsky759aca02016-03-18 23:29:29 +000075static cl::opt<int> ClCoverageLevel(
76 "sanitizer-coverage-level",
77 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
78 "3: all blocks and critical edges, "
79 "4: above plus indirect calls"),
80 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000081
Kostya Serebryany77cc7292015-02-04 01:21:45 +000082static cl::opt<unsigned> ClCoverageBlockThreshold(
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000083 "sanitizer-coverage-block-threshold",
Kostya Serebryany77cc7292015-02-04 01:21:45 +000084 cl::desc("Use a callback with a guard check inside it if there are"
85 " more than this number of blocks."),
Kostya Serebryany8fb05ac2015-03-10 01:11:53 +000086 cl::Hidden, cl::init(500));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000087
Kostya Serebryanycb45b122014-11-19 00:22:58 +000088static cl::opt<bool>
89 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
90 cl::desc("Experimental basic-block tracing: insert "
91 "callbacks at every basic block"),
92 cl::Hidden, cl::init(false));
93
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000094static cl::opt<bool> ClExperimentalTracePC("sanitizer-coverage-trace-pc",
95 cl::desc("Experimental pc tracing"),
96 cl::Hidden, cl::init(false));
97
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000098static cl::opt<bool>
99 ClExperimentalCMPTracing("sanitizer-coverage-experimental-trace-compares",
100 cl::desc("Experimental tracing of CMP and similar "
101 "instructions"),
102 cl::Hidden, cl::init(false));
103
Mike Aizatsky5971f182016-02-26 01:17:22 +0000104static cl::opt<bool> ClPruneBlocks(
105 "sanitizer-coverage-prune-blocks",
106 cl::desc("Reduce the number of instrumented blocks (experimental)"),
107 cl::Hidden, cl::init(false));
108
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000109// Experimental 8-bit counters used as an additional search heuristic during
110// coverage-guided fuzzing.
111// The counters are not thread-friendly:
112// - contention on these counters may cause significant slowdown;
113// - the counter updates are racy and the results may be inaccurate.
114// They are also inaccurate due to 8-bit integer overflow.
115static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
116 cl::desc("Experimental 8-bit counters"),
117 cl::Hidden, cl::init(false));
118
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000119namespace {
120
Alexey Samsonov3514f272015-05-07 01:00:31 +0000121SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
122 SanitizerCoverageOptions Res;
123 switch (LegacyCoverageLevel) {
124 case 0:
125 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
126 break;
127 case 1:
128 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
129 break;
130 case 2:
131 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
132 break;
133 case 3:
134 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
135 break;
136 case 4:
137 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
138 Res.IndirectCalls = true;
139 break;
140 }
141 return Res;
142}
143
144SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
145 // Sets CoverageType and IndirectCalls.
146 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
147 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
148 Options.IndirectCalls |= CLOpts.IndirectCalls;
149 Options.TraceBB |= ClExperimentalTracing;
150 Options.TraceCmp |= ClExperimentalCMPTracing;
151 Options.Use8bitCounters |= ClUse8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000152 Options.TracePC |= ClExperimentalTracePC;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000153 return Options;
154}
155
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000156class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000157public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000158 SanitizerCoverageModule(
159 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000160 : ModulePass(ID), Options(OverrideFromCL(Options)) {
161 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
162 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000163 bool runOnModule(Module &M) override;
164 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000165 static char ID; // Pass identification, replacement for typeid
166 const char *getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000167
Chandler Carruth30061152016-03-18 22:43:42 +0000168 void getAnalysisUsage(AnalysisUsage &AU) const override {
169 AU.addRequired<DominatorTreeWrapperPass>();
170 AU.addRequired<PostDominatorTreeWrapperPass>();
171 }
172
173private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000174 void InjectCoverageForIndirectCalls(Function &F,
175 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000176 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000177 void InjectTraceForSwitch(Function &F,
178 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000179 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000180 void SetNoSanitizeMetadata(Instruction *I);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000181 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000182 unsigned NumberOfInstrumentedBlocks() {
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000183 return SanCovFunction->getNumUses() +
184 SanCovWithCheckFunction->getNumUses() + SanCovTraceBB->getNumUses() +
185 SanCovTraceEnter->getNumUses();
Kostya Serebryany48a40232015-03-10 01:58:27 +0000186 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000187 Function *SanCovFunction;
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000188 Function *SanCovWithCheckFunction;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000189 Function *SanCovIndirCallFunction, *SanCovTracePCIndir;
190 Function *SanCovTraceEnter, *SanCovTraceBB, *SanCovTracePC;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000191 Function *SanCovTraceCmpFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000192 Function *SanCovTraceSwitchFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000193 InlineAsm *EmptyAsm;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000194 Type *IntptrTy, *Int64Ty, *Int64PtrTy;
195 Module *CurModule;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000196 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000197 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000198
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000199 GlobalVariable *GuardArray;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000200 GlobalVariable *EightBitCounterArray;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000201
Alexey Samsonov3514f272015-05-07 01:00:31 +0000202 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000203};
204
Mike Aizatsky759aca02016-03-18 23:29:29 +0000205} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000206
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000207bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000208 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
209 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000210 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000211 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000212 CurModule = &M;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000213 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000214 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000215 IRBuilder<> IRB(*C);
Kostya Serebryany88599462015-02-20 00:30:44 +0000216 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000217 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000218 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000219 Int64Ty = IRB.getInt64Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000220
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000221 SanCovFunction = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000222 M.getOrInsertFunction(SanCovName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000223 SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000224 M.getOrInsertFunction(SanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
225 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
226 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000227 SanCovIndirCallFunction =
228 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000229 SanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000230 SanCovTraceCmpFunction =
231 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000232 SanCovTraceCmpName, VoidTy, Int64Ty, Int64Ty, Int64Ty, nullptr));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000233 SanCovTraceSwitchFunction =
234 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000235 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy, nullptr));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000236
Kostya Serebryany73762942014-12-16 21:24:15 +0000237 // We insert an empty inline asm after cov callbacks to avoid callback merge.
238 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
239 StringRef(""), StringRef(""),
240 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000241
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000242 SanCovTracePC = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000243 M.getOrInsertFunction(SanCovTracePCName, VoidTy, nullptr));
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000244 SanCovTraceEnter = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000245 M.getOrInsertFunction(SanCovTraceEnterName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000246 SanCovTraceBB = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000247 M.getOrInsertFunction(SanCovTraceBBName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000248
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000249 // At this point we create a dummy array of guards because we don't
250 // know how many elements we will need.
251 Type *Int32Ty = IRB.getInt32Ty();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000252 Type *Int8Ty = IRB.getInt8Ty();
253
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000254 GuardArray =
255 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
256 nullptr, "__sancov_gen_cov_tmp");
Alexey Samsonov3514f272015-05-07 01:00:31 +0000257 if (Options.Use8bitCounters)
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000258 EightBitCounterArray =
259 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
260 nullptr, "__sancov_gen_cov_tmp");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000261
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000262 for (auto &F : M)
263 runOnFunction(F);
264
Kostya Serebryany48a40232015-03-10 01:58:27 +0000265 auto N = NumberOfInstrumentedBlocks();
266
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000267 // Now we know how many elements we need. Create an array of guards
268 // with one extra element at the beginning for the size.
Kostya Serebryany48a40232015-03-10 01:58:27 +0000269 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000270 GlobalVariable *RealGuardArray = new GlobalVariable(
271 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
272 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
273
274 // Replace the dummy array with the real one.
275 GuardArray->replaceAllUsesWith(
276 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
277 GuardArray->eraseFromParent();
278
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000279 GlobalVariable *RealEightBitCounterArray;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000280 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000281 // Make sure the array is 16-aligned.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000282 static const int CounterAlignment = 16;
283 Type *Int8ArrayNTy = ArrayType::get(Int8Ty, alignTo(N, CounterAlignment));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000284 RealEightBitCounterArray = new GlobalVariable(
285 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
286 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
Mike Aizatsky759aca02016-03-18 23:29:29 +0000287 RealEightBitCounterArray->setAlignment(CounterAlignment);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000288 EightBitCounterArray->replaceAllUsesWith(
289 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
290 EightBitCounterArray->eraseFromParent();
291 }
292
Kostya Serebryany88599462015-02-20 00:30:44 +0000293 // Create variable for module (compilation unit) name
294 Constant *ModNameStrConst =
295 ConstantDataArray::getString(M.getContext(), M.getName(), true);
296 GlobalVariable *ModuleName =
297 new GlobalVariable(M, ModNameStrConst->getType(), true,
298 GlobalValue::PrivateLinkage, ModNameStrConst);
299
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000300 if (!Options.TracePC) {
301 Function *CtorFunc;
302 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000303 M, SanCovModuleCtorName, SanCovModuleInitName,
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000304 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
305 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
Mike Aizatsky759aca02016-03-18 23:29:29 +0000306 ConstantInt::get(IntptrTy, N),
307 Options.Use8bitCounters
308 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
309 : Constant::getNullValue(Int8PtrTy),
310 IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000311
Mike Aizatsky759aca02016-03-18 23:29:29 +0000312 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000313 }
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000314
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000315 return true;
316}
317
Mike Aizatsky9987f432016-03-23 23:15:03 +0000318// True if block has successors and it dominates all of them.
319static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
320 if (succ_begin(BB) == succ_end(BB))
321 return false;
322
323 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
324 if (!DT->dominates(BB, SUCC))
325 return false;
326 }
327
328 return true;
329}
330
331// True if block has predecessors and it postdominates all of them.
332static bool isFullPostDominator(const BasicBlock *BB,
333 const PostDominatorTree *PDT) {
334 if (pred_begin(BB) == pred_end(BB))
335 return false;
336
337 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
338 if (!PDT->dominates(BB, PRED))
339 return false;
340 }
341
342 return true;
343}
344
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000345static bool shouldInstrumentBlock(const Function& F, const BasicBlock *BB, const DominatorTree *DT,
Mike Aizatsky602f7922016-03-21 23:08:16 +0000346 const PostDominatorTree *PDT) {
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000347 if (!ClPruneBlocks || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000348 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000349
Mike Aizatsky9987f432016-03-23 23:15:03 +0000350 return !(isFullDominator(BB, DT) || isFullPostDominator(BB, PDT));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000351}
352
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000353bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000354 if (F.empty())
355 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000356 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000357 return false; // Should not instrument sanitizer init functions.
Reid Klecknerdf523372015-09-03 20:18:29 +0000358 // Don't instrument functions using SEH for now. Splitting basic blocks like
359 // we do for coverage breaks WinEHPrepare.
360 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
361 if (F.hasPersonalityFn() &&
362 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
363 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000364 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000365 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000366 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000367 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000368 SmallVector<Instruction *, 8> CmpTraceTargets;
369 SmallVector<Instruction *, 8> SwitchTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000370
Mike Aizatsky602f7922016-03-21 23:08:16 +0000371 const DominatorTree *DT =
372 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
373 const PostDominatorTree *PDT =
374 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
375
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000376 for (auto &BB : F) {
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000377 if (shouldInstrumentBlock(F, &BB, DT, PDT))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000378 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000379 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000380 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000381 CallSite CS(&Inst);
382 if (CS && !CS.getCalledFunction())
383 IndirCalls.push_back(&Inst);
384 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000385 if (Options.TraceCmp) {
386 if (isa<ICmpInst>(&Inst))
387 CmpTraceTargets.push_back(&Inst);
388 if (isa<SwitchInst>(&Inst))
389 SwitchTraceTargets.push_back(&Inst);
390 }
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000391 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000392 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000393
394 InjectCoverage(F, BlocksToInstrument);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000395 InjectCoverageForIndirectCalls(F, IndirCalls);
396 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000397 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000398 return true;
399}
400
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000401bool SanitizerCoverageModule::InjectCoverage(Function &F,
402 ArrayRef<BasicBlock *> AllBlocks) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000403 switch (Options.CoverageType) {
404 case SanitizerCoverageOptions::SCK_None:
405 return false;
406 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000407 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000408 return true;
409 default: {
410 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000411 for (auto BB : AllBlocks)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000412 InjectCoverageAtBlock(F, *BB, UseCalls);
413 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000414 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000415 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000416}
417
418// On every indirect call we call a run-time function
419// __sanitizer_cov_indir_call* with two parameters:
420// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000421// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000422// The cache is used to speed up recording the caller-callee pairs.
423// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000424// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000425void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
426 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000427 if (IndirCalls.empty())
428 return;
429 const int CacheSize = 16;
430 const int CacheAlignment = 64; // Align for better performance.
431 Type *Ty = ArrayType::get(IntptrTy, CacheSize);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000432 for (auto I : IndirCalls) {
433 IRBuilder<> IRB(I);
434 CallSite CS(I);
435 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000436 if (isa<InlineAsm>(Callee))
437 continue;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000438 GlobalVariable *CalleeCache = new GlobalVariable(
439 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
440 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
Mike Aizatsky759aca02016-03-18 23:29:29 +0000441 CalleeCache->setAlignment(CacheAlignment);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000442 if (Options.TracePC)
443 IRB.CreateCall(SanCovTracePCIndir,
444 IRB.CreatePointerCast(Callee, IntptrTy));
445 else
446 IRB.CreateCall(SanCovIndirCallFunction,
447 {IRB.CreatePointerCast(Callee, IntptrTy),
Mike Aizatsky759aca02016-03-18 23:29:29 +0000448 IRB.CreatePointerCast(CalleeCache, IntptrTy)});
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000449 }
450}
451
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000452// For every switch statement we insert a call:
453// __sanitizer_cov_trace_switch(CondValue,
454// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
455
456void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000457 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000458 for (auto I : SwitchTraceTargets) {
459 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
460 IRBuilder<> IRB(I);
461 SmallVector<Constant *, 16> Initializers;
462 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000463 if (Cond->getType()->getScalarSizeInBits() >
464 Int64Ty->getScalarSizeInBits())
465 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000466 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
467 Initializers.push_back(
468 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
469 if (Cond->getType()->getScalarSizeInBits() <
470 Int64Ty->getScalarSizeInBits())
471 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000472 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000473 Constant *C = It.getCaseValue();
474 if (C->getType()->getScalarSizeInBits() <
475 Int64Ty->getScalarSizeInBits())
476 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
477 Initializers.push_back(C);
478 }
479 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
480 GlobalVariable *GV = new GlobalVariable(
481 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
482 ConstantArray::get(ArrayOfInt64Ty, Initializers),
483 "__sancov_gen_cov_switch_values");
484 IRB.CreateCall(SanCovTraceSwitchFunction,
485 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
486 }
487 }
488}
489
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000490void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000491 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000492 for (auto I : CmpTraceTargets) {
493 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
494 IRBuilder<> IRB(ICMP);
495 Value *A0 = ICMP->getOperand(0);
496 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000497 if (!A0->getType()->isIntegerTy())
498 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000499 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000500 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
David Blaikieff6409d2015-05-18 22:13:54 +0000501 IRB.CreateCall(
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000502 SanCovTraceCmpFunction,
David Blaikieff6409d2015-05-18 22:13:54 +0000503 {ConstantInt::get(Int64Ty, (TypeSize << 32) | ICMP->getPredicate()),
504 IRB.CreateIntCast(A0, Int64Ty, true),
505 IRB.CreateIntCast(A1, Int64Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000506 }
507 }
508}
509
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000510void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000511 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
512 MDNode::get(*C, None));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000513}
514
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000515void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
516 bool UseCalls) {
Alexey Samsonov342b1e82015-06-30 23:11:45 +0000517 // Don't insert coverage for unreachable blocks: we will never call
518 // __sanitizer_cov() for them, so counting them in
519 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
520 // percentage. Also, unreachable instructions frequently have no debug
521 // locations.
522 if (isa<UnreachableInst>(BB.getTerminator()))
523 return;
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000524 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000525
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000526 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000527 DebugLoc EntryLoc;
528 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000529 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000530 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000531 // Keep static allocas and llvm.localescape calls in the entry block. Even
532 // if we aren't splitting the block, it's nice for allocas to be before
533 // calls.
534 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000535 } else {
536 EntryLoc = IP->getDebugLoc();
537 }
538
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000539 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000540 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000541 Value *GuardP = IRB.CreateAdd(
542 IRB.CreatePointerCast(GuardArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000543 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000544 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
545 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000546 if (Options.TracePC) {
547 IRB.CreateCall(SanCovTracePC);
548 } else if (Options.TraceBB) {
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000549 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
550 } else if (UseCalls) {
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000551 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
552 } else {
553 LoadInst *Load = IRB.CreateLoad(GuardP);
JF Bastien800f87a2016-04-06 21:19:33 +0000554 Load->setAtomic(AtomicOrdering::Monotonic);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000555 Load->setAlignment(4);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000556 SetNoSanitizeMetadata(Load);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000557 Value *Cmp =
558 IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000559 Instruction *Ins = SplitBlockAndInsertIfThen(
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000560 Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000561 IRB.SetInsertPoint(Ins);
562 IRB.SetCurrentDebugLocation(EntryLoc);
563 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
564 IRB.CreateCall(SanCovFunction, GuardP);
David Blaikieff6409d2015-05-18 22:13:54 +0000565 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000566 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000567
Alexey Samsonov3514f272015-05-07 01:00:31 +0000568 if (Options.Use8bitCounters) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000569 IRB.SetInsertPoint(&*IP);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000570 Value *P = IRB.CreateAdd(
571 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000572 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000573 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000574 LoadInst *LI = IRB.CreateLoad(P);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000575 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000576 StoreInst *SI = IRB.CreateStore(Inc, P);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000577 SetNoSanitizeMetadata(LI);
578 SetNoSanitizeMetadata(SI);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000579 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000580}
581
582char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000583INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000584 "SanitizerCoverage: TODO."
585 "ModulePass",
586 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000587INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
588INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
589INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000590 "SanitizerCoverage: TODO."
591 "ModulePass",
592 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000593ModulePass *llvm::createSanitizerCoverageModulePass(
594 const SanitizerCoverageOptions &Options) {
595 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000596}