blob: 1b88dbde9e903f9905c48b19560cb14f29d0ea7c [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"
Mike Aizatsky5971f182016-02-26 01:17:22 +000034#include "llvm/IR/CFG.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000035#include "llvm/IR/CallSite.h"
36#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000037#include "llvm/IR/DebugInfo.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000038#include "llvm/IR/Dominators.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000039#include "llvm/IR/Function.h"
40#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000041#include "llvm/IR/InlineAsm.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000042#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/MDBuilder.h"
44#include "llvm/IR/Module.h"
45#include "llvm/IR/Type.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Debug.h"
48#include "llvm/Support/raw_ostream.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000049#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000050#include "llvm/Transforms/Scalar.h"
51#include "llvm/Transforms/Utils/BasicBlockUtils.h"
52#include "llvm/Transforms/Utils/ModuleUtils.h"
53
54using namespace llvm;
55
56#define DEBUG_TYPE "sancov"
57
58static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
59static const char *const kSanCovName = "__sanitizer_cov";
Kostya Serebryany77cc7292015-02-04 01:21:45 +000060static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000061static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000062static const char *const kSanCovTracePCIndir = "__sanitizer_cov_trace_pc_indir";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000063static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
64static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000065static const char *const kSanCovTracePC = "__sanitizer_cov_trace_pc";
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000066static const char *const kSanCovTraceCmp = "__sanitizer_cov_trace_cmp";
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +000067static const char *const kSanCovTraceSwitch = "__sanitizer_cov_trace_switch";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000068static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
Evgeniy Stepanov3fdfc7b2015-01-27 15:01:22 +000069static const uint64_t kSanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000070
71static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
72 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
73 "3: all blocks and critical edges, "
74 "4: above plus indirect calls"),
75 cl::Hidden, cl::init(0));
76
Kostya Serebryany77cc7292015-02-04 01:21:45 +000077static cl::opt<unsigned> ClCoverageBlockThreshold(
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000078 "sanitizer-coverage-block-threshold",
Kostya Serebryany77cc7292015-02-04 01:21:45 +000079 cl::desc("Use a callback with a guard check inside it if there are"
80 " more than this number of blocks."),
Kostya Serebryany8fb05ac2015-03-10 01:11:53 +000081 cl::Hidden, cl::init(500));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000082
Kostya Serebryanycb45b122014-11-19 00:22:58 +000083static cl::opt<bool>
84 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
85 cl::desc("Experimental basic-block tracing: insert "
86 "callbacks at every basic block"),
87 cl::Hidden, cl::init(false));
88
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000089static cl::opt<bool> ClExperimentalTracePC("sanitizer-coverage-trace-pc",
90 cl::desc("Experimental pc tracing"),
91 cl::Hidden, cl::init(false));
92
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000093static cl::opt<bool>
94 ClExperimentalCMPTracing("sanitizer-coverage-experimental-trace-compares",
95 cl::desc("Experimental tracing of CMP and similar "
96 "instructions"),
97 cl::Hidden, cl::init(false));
98
Mike Aizatsky5971f182016-02-26 01:17:22 +000099static cl::opt<bool> ClPruneBlocks(
100 "sanitizer-coverage-prune-blocks",
101 cl::desc("Reduce the number of instrumented blocks (experimental)"),
102 cl::Hidden, cl::init(false));
103
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000104// Experimental 8-bit counters used as an additional search heuristic during
105// coverage-guided fuzzing.
106// The counters are not thread-friendly:
107// - contention on these counters may cause significant slowdown;
108// - the counter updates are racy and the results may be inaccurate.
109// They are also inaccurate due to 8-bit integer overflow.
110static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
111 cl::desc("Experimental 8-bit counters"),
112 cl::Hidden, cl::init(false));
113
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000114namespace {
115
Alexey Samsonov3514f272015-05-07 01:00:31 +0000116SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
117 SanitizerCoverageOptions Res;
118 switch (LegacyCoverageLevel) {
119 case 0:
120 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
121 break;
122 case 1:
123 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
124 break;
125 case 2:
126 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
127 break;
128 case 3:
129 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
130 break;
131 case 4:
132 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
133 Res.IndirectCalls = true;
134 break;
135 }
136 return Res;
137}
138
139SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
140 // Sets CoverageType and IndirectCalls.
141 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
142 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
143 Options.IndirectCalls |= CLOpts.IndirectCalls;
144 Options.TraceBB |= ClExperimentalTracing;
145 Options.TraceCmp |= ClExperimentalCMPTracing;
146 Options.Use8bitCounters |= ClUse8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000147 Options.TracePC |= ClExperimentalTracePC;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000148 return Options;
149}
150
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000151class SanitizerCoverageModule : public ModulePass {
152 public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000153 SanitizerCoverageModule(
154 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
155 : ModulePass(ID), Options(OverrideFromCL(Options)) {}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000156 bool runOnModule(Module &M) override;
157 bool runOnFunction(Function &F);
158 static char ID; // Pass identification, replacement for typeid
159 const char *getPassName() const override {
160 return "SanitizerCoverageModule";
161 }
162
Renato Golin9a5419e2016-02-27 14:19:19 +0000163 private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000164 void InjectCoverageForIndirectCalls(Function &F,
165 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000166 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000167 void InjectTraceForSwitch(Function &F,
168 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000169 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000170 void SetNoSanitizeMetadata(Instruction *I);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000171 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000172 unsigned NumberOfInstrumentedBlocks() {
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000173 return SanCovFunction->getNumUses() +
174 SanCovWithCheckFunction->getNumUses() + SanCovTraceBB->getNumUses() +
175 SanCovTraceEnter->getNumUses();
Kostya Serebryany48a40232015-03-10 01:58:27 +0000176 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000177 Function *SanCovFunction;
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000178 Function *SanCovWithCheckFunction;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000179 Function *SanCovIndirCallFunction, *SanCovTracePCIndir;
180 Function *SanCovTraceEnter, *SanCovTraceBB, *SanCovTracePC;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000181 Function *SanCovTraceCmpFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000182 Function *SanCovTraceSwitchFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000183 InlineAsm *EmptyAsm;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000184 Type *IntptrTy, *Int64Ty, *Int64PtrTy;
185 Module *CurModule;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000186 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000187 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000188
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000189 GlobalVariable *GuardArray;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000190 GlobalVariable *EightBitCounterArray;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000191
Alexey Samsonov3514f272015-05-07 01:00:31 +0000192 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000193};
194
195} // namespace
196
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000197bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000198 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
199 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000200 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000201 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000202 CurModule = &M;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000203 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000204 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000205 IRBuilder<> IRB(*C);
Kostya Serebryany88599462015-02-20 00:30:44 +0000206 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000207 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000208 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000209 Int64Ty = IRB.getInt64Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000210
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000211 SanCovFunction = checkSanitizerInterfaceFunction(
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000212 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000213 SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000214 M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000215 SanCovTracePCIndir =
216 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
217 kSanCovTracePCIndir, VoidTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000218 SanCovIndirCallFunction =
219 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
220 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
221 SanCovTraceCmpFunction =
222 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
223 kSanCovTraceCmp, VoidTy, Int64Ty, Int64Ty, Int64Ty, nullptr));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000224 SanCovTraceSwitchFunction =
225 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
226 kSanCovTraceSwitch, VoidTy, Int64Ty, Int64PtrTy, nullptr));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000227
Kostya Serebryany73762942014-12-16 21:24:15 +0000228 // We insert an empty inline asm after cov callbacks to avoid callback merge.
229 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
230 StringRef(""), StringRef(""),
231 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000232
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000233 SanCovTracePC = checkSanitizerInterfaceFunction(
234 M.getOrInsertFunction(kSanCovTracePC, VoidTy, nullptr));
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000235 SanCovTraceEnter = checkSanitizerInterfaceFunction(
236 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
237 SanCovTraceBB = checkSanitizerInterfaceFunction(
238 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000239
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000240 // At this point we create a dummy array of guards because we don't
241 // know how many elements we will need.
242 Type *Int32Ty = IRB.getInt32Ty();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000243 Type *Int8Ty = IRB.getInt8Ty();
244
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000245 GuardArray =
246 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
247 nullptr, "__sancov_gen_cov_tmp");
Alexey Samsonov3514f272015-05-07 01:00:31 +0000248 if (Options.Use8bitCounters)
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000249 EightBitCounterArray =
250 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
251 nullptr, "__sancov_gen_cov_tmp");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000252
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000253 for (auto &F : M)
254 runOnFunction(F);
255
Kostya Serebryany48a40232015-03-10 01:58:27 +0000256 auto N = NumberOfInstrumentedBlocks();
257
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000258 // Now we know how many elements we need. Create an array of guards
259 // with one extra element at the beginning for the size.
Kostya Serebryany48a40232015-03-10 01:58:27 +0000260 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000261 GlobalVariable *RealGuardArray = new GlobalVariable(
262 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
263 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
264
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000265
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000266 // Replace the dummy array with the real one.
267 GuardArray->replaceAllUsesWith(
268 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
269 GuardArray->eraseFromParent();
270
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000271 GlobalVariable *RealEightBitCounterArray;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000272 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000273 // Make sure the array is 16-aligned.
274 static const int kCounterAlignment = 16;
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000275 Type *Int8ArrayNTy = ArrayType::get(Int8Ty, alignTo(N, kCounterAlignment));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000276 RealEightBitCounterArray = new GlobalVariable(
277 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
278 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
279 RealEightBitCounterArray->setAlignment(kCounterAlignment);
280 EightBitCounterArray->replaceAllUsesWith(
281 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
282 EightBitCounterArray->eraseFromParent();
283 }
284
Kostya Serebryany88599462015-02-20 00:30:44 +0000285 // Create variable for module (compilation unit) name
286 Constant *ModNameStrConst =
287 ConstantDataArray::getString(M.getContext(), M.getName(), true);
288 GlobalVariable *ModuleName =
289 new GlobalVariable(M, ModNameStrConst->getType(), true,
290 GlobalValue::PrivateLinkage, ModNameStrConst);
291
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000292 if (!Options.TracePC) {
293 Function *CtorFunc;
294 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
295 M, kSanCovModuleCtorName, kSanCovModuleInitName,
296 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
297 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
298 ConstantInt::get(IntptrTy, N),
299 Options.Use8bitCounters
300 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
301 : Constant::getNullValue(Int8PtrTy),
302 IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000303
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000304 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
305 }
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000306
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000307 return true;
308}
309
Renato Golin9a5419e2016-02-27 14:19:19 +0000310static bool shouldInstrumentBlock(const BasicBlock *BB,
311 const DominatorTree *DT) {
Mike Aizatsky5971f182016-02-26 01:17:22 +0000312 if (!ClPruneBlocks)
313 return true;
Renato Golin9a5419e2016-02-27 14:19:19 +0000314 if (succ_begin(BB) == succ_end(BB))
315 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000316
317 // Check if BB dominates all its successors.
318 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
Renato Golin9a5419e2016-02-27 14:19:19 +0000319 if (!DT->dominates(BB, SUCC))
320 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000321 }
322
Renato Golin9a5419e2016-02-27 14:19:19 +0000323 return false;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000324}
325
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000326bool SanitizerCoverageModule::runOnFunction(Function &F) {
327 if (F.empty()) return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000328 if (F.getName().find(".module_ctor") != std::string::npos)
329 return false; // Should not instrument sanitizer init functions.
Reid Klecknerdf523372015-09-03 20:18:29 +0000330 // Don't instrument functions using SEH for now. Splitting basic blocks like
331 // we do for coverage breaks WinEHPrepare.
332 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
333 if (F.hasPersonalityFn() &&
334 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
335 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000336 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000337 SplitAllCriticalEdges(F);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000338 SmallVector<Instruction*, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000339 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000340 SmallVector<Instruction*, 8> CmpTraceTargets;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000341 SmallVector<Instruction*, 8> SwitchTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000342
Renato Golin9a5419e2016-02-27 14:19:19 +0000343 DominatorTree DT;
344 DT.recalculate(F);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000345 for (auto &BB : F) {
Renato Golin9a5419e2016-02-27 14:19:19 +0000346 if (shouldInstrumentBlock(&BB, &DT))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000347 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000348 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000349 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000350 CallSite CS(&Inst);
351 if (CS && !CS.getCalledFunction())
352 IndirCalls.push_back(&Inst);
353 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000354 if (Options.TraceCmp) {
355 if (isa<ICmpInst>(&Inst))
356 CmpTraceTargets.push_back(&Inst);
357 if (isa<SwitchInst>(&Inst))
358 SwitchTraceTargets.push_back(&Inst);
359 }
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000360 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000361 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000362
363 InjectCoverage(F, BlocksToInstrument);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000364 InjectCoverageForIndirectCalls(F, IndirCalls);
365 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000366 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000367 return true;
368}
369
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000370bool SanitizerCoverageModule::InjectCoverage(Function &F,
371 ArrayRef<BasicBlock *> AllBlocks) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000372 switch (Options.CoverageType) {
373 case SanitizerCoverageOptions::SCK_None:
374 return false;
375 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000376 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000377 return true;
378 default: {
379 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000380 for (auto BB : AllBlocks)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000381 InjectCoverageAtBlock(F, *BB, UseCalls);
382 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000383 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000384 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000385}
386
387// On every indirect call we call a run-time function
388// __sanitizer_cov_indir_call* with two parameters:
389// - callee address,
390// - global cache array that contains kCacheSize pointers (zero-initialized).
391// The cache is used to speed up recording the caller-callee pairs.
392// The address of the caller is passed implicitly via caller PC.
393// kCacheSize is encoded in the name of the run-time function.
394void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
395 Function &F, ArrayRef<Instruction *> IndirCalls) {
396 if (IndirCalls.empty()) return;
397 const int kCacheSize = 16;
398 const int kCacheAlignment = 64; // Align for better performance.
399 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
400 for (auto I : IndirCalls) {
401 IRBuilder<> IRB(I);
402 CallSite CS(I);
403 Value *Callee = CS.getCalledValue();
Benjamin Kramer619c4e52015-04-10 11:24:51 +0000404 if (isa<InlineAsm>(Callee)) continue;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000405 GlobalVariable *CalleeCache = new GlobalVariable(
406 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
407 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
408 CalleeCache->setAlignment(kCacheAlignment);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000409 if (Options.TracePC)
410 IRB.CreateCall(SanCovTracePCIndir,
411 IRB.CreatePointerCast(Callee, IntptrTy));
412 else
413 IRB.CreateCall(SanCovIndirCallFunction,
414 {IRB.CreatePointerCast(Callee, IntptrTy),
415 IRB.CreatePointerCast(CalleeCache, IntptrTy)});
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000416 }
417}
418
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000419// For every switch statement we insert a call:
420// __sanitizer_cov_trace_switch(CondValue,
421// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
422
423void SanitizerCoverageModule::InjectTraceForSwitch(
424 Function &F, ArrayRef<Instruction *> SwitchTraceTargets) {
425 for (auto I : SwitchTraceTargets) {
426 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
427 IRBuilder<> IRB(I);
428 SmallVector<Constant *, 16> Initializers;
429 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000430 if (Cond->getType()->getScalarSizeInBits() >
431 Int64Ty->getScalarSizeInBits())
432 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000433 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
434 Initializers.push_back(
435 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
436 if (Cond->getType()->getScalarSizeInBits() <
437 Int64Ty->getScalarSizeInBits())
438 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
439 for (auto It: SI->cases()) {
440 Constant *C = It.getCaseValue();
441 if (C->getType()->getScalarSizeInBits() <
442 Int64Ty->getScalarSizeInBits())
443 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
444 Initializers.push_back(C);
445 }
446 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
447 GlobalVariable *GV = new GlobalVariable(
448 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
449 ConstantArray::get(ArrayOfInt64Ty, Initializers),
450 "__sancov_gen_cov_switch_values");
451 IRB.CreateCall(SanCovTraceSwitchFunction,
452 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
453 }
454 }
455}
456
457
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000458void SanitizerCoverageModule::InjectTraceForCmp(
459 Function &F, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000460 for (auto I : CmpTraceTargets) {
461 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
462 IRBuilder<> IRB(ICMP);
463 Value *A0 = ICMP->getOperand(0);
464 Value *A1 = ICMP->getOperand(1);
465 if (!A0->getType()->isIntegerTy()) continue;
466 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000467 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
David Blaikieff6409d2015-05-18 22:13:54 +0000468 IRB.CreateCall(
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000469 SanCovTraceCmpFunction,
David Blaikieff6409d2015-05-18 22:13:54 +0000470 {ConstantInt::get(Int64Ty, (TypeSize << 32) | ICMP->getPredicate()),
471 IRB.CreateIntCast(A0, Int64Ty, true),
472 IRB.CreateIntCast(A1, Int64Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000473 }
474 }
475}
476
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000477void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000478 I->setMetadata(
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000479 I->getModule()->getMDKindID("nosanitize"), MDNode::get(*C, None));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000480}
481
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000482void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
483 bool UseCalls) {
Alexey Samsonov342b1e82015-06-30 23:11:45 +0000484 // Don't insert coverage for unreachable blocks: we will never call
485 // __sanitizer_cov() for them, so counting them in
486 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
487 // percentage. Also, unreachable instructions frequently have no debug
488 // locations.
489 if (isa<UnreachableInst>(BB.getTerminator()))
490 return;
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000491 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000492
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000493 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000494 DebugLoc EntryLoc;
495 if (IsEntryBB) {
496 if (auto SP = getDISubprogram(&F))
497 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000498 // Keep static allocas and llvm.localescape calls in the entry block. Even
499 // if we aren't splitting the block, it's nice for allocas to be before
500 // calls.
501 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000502 } else {
503 EntryLoc = IP->getDebugLoc();
504 }
505
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000506 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000507 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000508 Value *GuardP = IRB.CreateAdd(
509 IRB.CreatePointerCast(GuardArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000510 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000511 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
512 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000513 if (Options.TracePC) {
514 IRB.CreateCall(SanCovTracePC);
515 } else if (Options.TraceBB) {
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000516 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
517 } else if (UseCalls) {
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000518 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
519 } else {
520 LoadInst *Load = IRB.CreateLoad(GuardP);
521 Load->setAtomic(Monotonic);
522 Load->setAlignment(4);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000523 SetNoSanitizeMetadata(Load);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000524 Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
525 Instruction *Ins = SplitBlockAndInsertIfThen(
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000526 Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000527 IRB.SetInsertPoint(Ins);
528 IRB.SetCurrentDebugLocation(EntryLoc);
529 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
530 IRB.CreateCall(SanCovFunction, GuardP);
David Blaikieff6409d2015-05-18 22:13:54 +0000531 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000532 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000533
Alexey Samsonov3514f272015-05-07 01:00:31 +0000534 if (Options.Use8bitCounters) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000535 IRB.SetInsertPoint(&*IP);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000536 Value *P = IRB.CreateAdd(
537 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000538 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000539 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000540 LoadInst *LI = IRB.CreateLoad(P);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000541 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000542 StoreInst *SI = IRB.CreateStore(Inc, P);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000543 SetNoSanitizeMetadata(LI);
544 SetNoSanitizeMetadata(SI);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000545 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000546}
547
548char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000549INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
550 "SanitizerCoverage: TODO."
551 "ModulePass", false, false)
552INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
553INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
554INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000555 "SanitizerCoverage: TODO."
556 "ModulePass", false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000557ModulePass *llvm::createSanitizerCoverageModulePass(
558 const SanitizerCoverageOptions &Options) {
559 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000560}