blob: 8f7ac9c971e8c3413b5729048a0cc42fbd221413 [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";
Kostya Serebryany524c3f32016-08-18 01:25:28 +000070static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
71static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
72static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
73static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000074static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
75static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
76static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
Mike Aizatsky759aca02016-03-18 23:29:29 +000077static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
78static const char *const SanCovModuleCtorName = "sancov.module_ctor";
79static const uint64_t SanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000080
Kostya Serebryanyda718e52016-09-14 01:39:35 +000081static const char *const SanCovTracePCGuardName =
82 "__sanitizer_cov_trace_pc_guard";
83static const char *const SanCovTracePCGuardInitName =
84 "__sanitizer_cov_trace_pc_guard_init";
85
Mike Aizatsky759aca02016-03-18 23:29:29 +000086static cl::opt<int> ClCoverageLevel(
87 "sanitizer-coverage-level",
88 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
89 "3: all blocks and critical edges, "
90 "4: above plus indirect calls"),
91 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000092
Kostya Serebryany77cc7292015-02-04 01:21:45 +000093static cl::opt<unsigned> ClCoverageBlockThreshold(
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000094 "sanitizer-coverage-block-threshold",
Kostya Serebryany77cc7292015-02-04 01:21:45 +000095 cl::desc("Use a callback with a guard check inside it if there are"
96 " more than this number of blocks."),
Kostya Serebryany4b2ff072017-01-24 00:57:31 +000097 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000098
Kostya Serebryanycb45b122014-11-19 00:22:58 +000099static cl::opt<bool>
100 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
101 cl::desc("Experimental basic-block tracing: insert "
102 "callbacks at every basic block"),
103 cl::Hidden, cl::init(false));
104
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000105static cl::opt<bool> ClExperimentalTracePC("sanitizer-coverage-trace-pc",
106 cl::desc("Experimental pc tracing"),
107 cl::Hidden, cl::init(false));
108
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000109static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
110 cl::desc("pc tracing with a guard"),
111 cl::Hidden, cl::init(false));
112
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000113static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000114 ClCMPTracing("sanitizer-coverage-trace-compares",
115 cl::desc("Tracing of CMP and similar instructions"),
116 cl::Hidden, cl::init(false));
117
118static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
119 cl::desc("Tracing of DIV instructions"),
120 cl::Hidden, cl::init(false));
121
122static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
123 cl::desc("Tracing of GEP instructions"),
124 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000125
Mike Aizatsky70ea4532016-04-06 23:24:37 +0000126static cl::opt<bool>
127 ClPruneBlocks("sanitizer-coverage-prune-blocks",
128 cl::desc("Reduce the number of instrumented blocks"),
129 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000130
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000131// Experimental 8-bit counters used as an additional search heuristic during
132// coverage-guided fuzzing.
133// The counters are not thread-friendly:
134// - contention on these counters may cause significant slowdown;
135// - the counter updates are racy and the results may be inaccurate.
136// They are also inaccurate due to 8-bit integer overflow.
137static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
138 cl::desc("Experimental 8-bit counters"),
139 cl::Hidden, cl::init(false));
140
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000141namespace {
142
Alexey Samsonov3514f272015-05-07 01:00:31 +0000143SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
144 SanitizerCoverageOptions Res;
145 switch (LegacyCoverageLevel) {
146 case 0:
147 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
148 break;
149 case 1:
150 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
151 break;
152 case 2:
153 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
154 break;
155 case 3:
156 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
157 break;
158 case 4:
159 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
160 Res.IndirectCalls = true;
161 break;
162 }
163 return Res;
164}
165
166SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
167 // Sets CoverageType and IndirectCalls.
168 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
169 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
170 Options.IndirectCalls |= CLOpts.IndirectCalls;
171 Options.TraceBB |= ClExperimentalTracing;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000172 Options.TraceCmp |= ClCMPTracing;
173 Options.TraceDiv |= ClDIVTracing;
174 Options.TraceGep |= ClGEPTracing;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000175 Options.Use8bitCounters |= ClUse8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000176 Options.TracePC |= ClExperimentalTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000177 Options.TracePCGuard |= ClTracePCGuard;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000178 return Options;
179}
180
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000181class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000182public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000183 SanitizerCoverageModule(
184 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000185 : ModulePass(ID), Options(OverrideFromCL(Options)) {
186 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
187 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000188 bool runOnModule(Module &M) override;
189 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000190 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000191 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000192
Chandler Carruth30061152016-03-18 22:43:42 +0000193 void getAnalysisUsage(AnalysisUsage &AU) const override {
194 AU.addRequired<DominatorTreeWrapperPass>();
195 AU.addRequired<PostDominatorTreeWrapperPass>();
196 }
197
198private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000199 void InjectCoverageForIndirectCalls(Function &F,
200 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000201 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000202 void InjectTraceForDiv(Function &F,
203 ArrayRef<BinaryOperator *> DivTraceTargets);
204 void InjectTraceForGep(Function &F,
205 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000206 void InjectTraceForSwitch(Function &F,
207 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000208 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000209 void CreateFunctionGuardArray(size_t NumGuards, Function &F);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000210 void SetNoSanitizeMetadata(Instruction *I);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000211 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
212 bool UseCalls);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000213 unsigned NumberOfInstrumentedBlocks() {
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000214 return SanCovFunction->getNumUses() +
215 SanCovWithCheckFunction->getNumUses() + SanCovTraceBB->getNumUses() +
216 SanCovTraceEnter->getNumUses();
Kostya Serebryany48a40232015-03-10 01:58:27 +0000217 }
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000218 StringRef getSanCovTracePCGuardSection() const;
219 StringRef getSanCovTracePCGuardSectionStart() const;
220 StringRef getSanCovTracePCGuardSectionEnd() const;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000221 Function *SanCovFunction;
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000222 Function *SanCovWithCheckFunction;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000223 Function *SanCovIndirCallFunction, *SanCovTracePCIndir;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000224 Function *SanCovTraceEnter, *SanCovTraceBB, *SanCovTracePC, *SanCovTracePCGuard;
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000225 Function *SanCovTraceCmpFunction[4];
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000226 Function *SanCovTraceDivFunction[2];
227 Function *SanCovTraceGepFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000228 Function *SanCovTraceSwitchFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000229 InlineAsm *EmptyAsm;
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000230 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000231 Module *CurModule;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000232 Triple TargetTriple;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000233 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000234 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000235
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000236 GlobalVariable *GuardArray;
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000237 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000238 GlobalVariable *EightBitCounterArray;
Kostya Serebryany186d6182016-09-27 01:08:33 +0000239 bool HasSancovGuardsSection;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000240
Alexey Samsonov3514f272015-05-07 01:00:31 +0000241 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000242};
243
Mike Aizatsky759aca02016-03-18 23:29:29 +0000244} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000245
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000246bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000247 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
248 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000249 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000250 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000251 CurModule = &M;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000252 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany186d6182016-09-27 01:08:33 +0000253 HasSancovGuardsSection = false;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000254 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000255 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000256 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000257 IRBuilder<> IRB(*C);
Kostya Serebryany88599462015-02-20 00:30:44 +0000258 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000259 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000260 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000261 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000262 Int32Ty = IRB.getInt32Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000263
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000264 SanCovFunction = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000265 M.getOrInsertFunction(SanCovName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000266 SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000267 M.getOrInsertFunction(SanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
268 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
269 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000270 SanCovIndirCallFunction =
271 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000272 SanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000273 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000274 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000275 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty(), nullptr));
276 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
277 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
278 IRB.getInt16Ty(), nullptr));
279 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
280 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
281 IRB.getInt32Ty(), nullptr));
282 SanCovTraceCmpFunction[3] =
283 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
284 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty, nullptr));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000285
286 SanCovTraceDivFunction[0] =
287 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
288 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty(), nullptr));
289 SanCovTraceDivFunction[1] =
290 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
291 SanCovTraceDiv8, VoidTy, Int64Ty, nullptr));
292 SanCovTraceGepFunction =
293 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
294 SanCovTraceGep, VoidTy, IntptrTy, nullptr));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000295 SanCovTraceSwitchFunction =
296 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000297 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy, nullptr));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000298
Kostya Serebryany73762942014-12-16 21:24:15 +0000299 // We insert an empty inline asm after cov callbacks to avoid callback merge.
300 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
301 StringRef(""), StringRef(""),
302 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000303
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000304 SanCovTracePC = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000305 M.getOrInsertFunction(SanCovTracePCName, VoidTy, nullptr));
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000306 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000307 SanCovTracePCGuardName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000308 SanCovTraceEnter = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000309 M.getOrInsertFunction(SanCovTraceEnterName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000310 SanCovTraceBB = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000311 M.getOrInsertFunction(SanCovTraceBBName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000312
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000313 // At this point we create a dummy array of guards because we don't
314 // know how many elements we will need.
315 Type *Int32Ty = IRB.getInt32Ty();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000316 Type *Int8Ty = IRB.getInt8Ty();
317
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000318 if (!Options.TracePCGuard)
319 GuardArray =
320 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
321 nullptr, "__sancov_gen_cov_tmp");
Alexey Samsonov3514f272015-05-07 01:00:31 +0000322 if (Options.Use8bitCounters)
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000323 EightBitCounterArray =
324 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
325 nullptr, "__sancov_gen_cov_tmp");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000326
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000327 for (auto &F : M)
328 runOnFunction(F);
329
Kostya Serebryany48a40232015-03-10 01:58:27 +0000330 auto N = NumberOfInstrumentedBlocks();
331
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000332 GlobalVariable *RealGuardArray = nullptr;
333 if (!Options.TracePCGuard) {
334 // Now we know how many elements we need. Create an array of guards
335 // with one extra element at the beginning for the size.
336 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
337 RealGuardArray = new GlobalVariable(
338 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
339 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000340
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000341 // Replace the dummy array with the real one.
342 GuardArray->replaceAllUsesWith(
343 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
344 GuardArray->eraseFromParent();
345 }
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000346
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000347 GlobalVariable *RealEightBitCounterArray;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000348 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000349 // Make sure the array is 16-aligned.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000350 static const int CounterAlignment = 16;
351 Type *Int8ArrayNTy = ArrayType::get(Int8Ty, alignTo(N, CounterAlignment));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000352 RealEightBitCounterArray = new GlobalVariable(
353 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
354 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
Mike Aizatsky759aca02016-03-18 23:29:29 +0000355 RealEightBitCounterArray->setAlignment(CounterAlignment);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000356 EightBitCounterArray->replaceAllUsesWith(
357 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
358 EightBitCounterArray->eraseFromParent();
359 }
360
Kostya Serebryany88599462015-02-20 00:30:44 +0000361 // Create variable for module (compilation unit) name
362 Constant *ModNameStrConst =
363 ConstantDataArray::getString(M.getContext(), M.getName(), true);
Reid Kleckner3a83e762016-11-16 16:50:43 +0000364 GlobalVariable *ModuleName = new GlobalVariable(
365 M, ModNameStrConst->getType(), true, GlobalValue::PrivateLinkage,
366 ModNameStrConst, "__sancov_gen_modname");
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000367 if (Options.TracePCGuard) {
Kostya Serebryany186d6182016-09-27 01:08:33 +0000368 if (HasSancovGuardsSection) {
369 Function *CtorFunc;
Justin Bogner41e632b2017-02-01 02:38:39 +0000370 GlobalVariable *SecStart = new GlobalVariable(
371 M, Int32PtrTy, false, GlobalVariable::ExternalLinkage, nullptr,
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000372 getSanCovTracePCGuardSectionStart());
Justin Bogner41e632b2017-02-01 02:38:39 +0000373 SecStart->setVisibility(GlobalValue::HiddenVisibility);
374 GlobalVariable *SecEnd = new GlobalVariable(
375 M, Int32PtrTy, false, GlobalVariable::ExternalLinkage, nullptr,
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000376 getSanCovTracePCGuardSectionEnd());
Justin Bogner41e632b2017-02-01 02:38:39 +0000377 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
378
Kostya Serebryany186d6182016-09-27 01:08:33 +0000379 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
380 M, SanCovModuleCtorName, SanCovTracePCGuardInitName,
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000381 {Int32PtrTy, Int32PtrTy},
Justin Bogner41e632b2017-02-01 02:38:39 +0000382 {IRB.CreatePointerCast(SecStart, Int32PtrTy),
383 IRB.CreatePointerCast(SecEnd, Int32PtrTy)});
Kostya Serebryany186d6182016-09-27 01:08:33 +0000384
Mike Aizatsky4705ae92017-02-08 23:12:46 +0000385 if (TargetTriple.supportsCOMDAT()) {
386 // Use comdat to dedup CtorFunc.
387 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
388 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
389 } else {
390 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
391 }
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000392 }
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000393 } else if (!Options.TracePC) {
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000394 Function *CtorFunc;
395 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000396 M, SanCovModuleCtorName, SanCovModuleInitName,
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000397 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
398 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
Mike Aizatsky759aca02016-03-18 23:29:29 +0000399 ConstantInt::get(IntptrTy, N),
400 Options.Use8bitCounters
401 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
402 : Constant::getNullValue(Int8PtrTy),
403 IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000404
Mike Aizatsky759aca02016-03-18 23:29:29 +0000405 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000406 }
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000407
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000408 return true;
409}
410
Mike Aizatsky9987f432016-03-23 23:15:03 +0000411// True if block has successors and it dominates all of them.
412static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
413 if (succ_begin(BB) == succ_end(BB))
414 return false;
415
416 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
417 if (!DT->dominates(BB, SUCC))
418 return false;
419 }
420
421 return true;
422}
423
424// True if block has predecessors and it postdominates all of them.
425static bool isFullPostDominator(const BasicBlock *BB,
426 const PostDominatorTree *PDT) {
427 if (pred_begin(BB) == pred_end(BB))
428 return false;
429
430 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
431 if (!PDT->dominates(BB, PRED))
432 return false;
433 }
434
435 return true;
436}
437
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000438static bool shouldInstrumentBlock(const Function& F, const BasicBlock *BB, const DominatorTree *DT,
Mike Aizatsky602f7922016-03-21 23:08:16 +0000439 const PostDominatorTree *PDT) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000440 // Don't insert coverage for unreachable blocks: we will never call
441 // __sanitizer_cov() for them, so counting them in
442 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
443 // percentage. Also, unreachable instructions frequently have no debug
444 // locations.
445 if (isa<UnreachableInst>(BB->getTerminator()))
446 return false;
447
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000448 if (!ClPruneBlocks || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000449 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000450
Mike Aizatsky9987f432016-03-23 23:15:03 +0000451 return !(isFullDominator(BB, DT) || isFullPostDominator(BB, PDT));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000452}
453
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000454bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000455 if (F.empty())
456 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000457 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000458 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000459 if (F.getName().startswith("__sanitizer_"))
460 return false; // Don't instrument __sanitizer_* callbacks.
Reid Klecknerec803542016-11-11 19:18:45 +0000461 // Don't instrument MSVC CRT configuration helpers. They may run before normal
462 // initialization.
463 if (F.getName() == "__local_stdio_printf_options" ||
464 F.getName() == "__local_stdio_scanf_options")
465 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000466 // Don't instrument functions using SEH for now. Splitting basic blocks like
467 // we do for coverage breaks WinEHPrepare.
468 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
469 if (F.hasPersonalityFn() &&
470 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
471 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000472 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000473 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000474 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000475 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000476 SmallVector<Instruction *, 8> CmpTraceTargets;
477 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000478 SmallVector<BinaryOperator *, 8> DivTraceTargets;
479 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000480
Mike Aizatsky602f7922016-03-21 23:08:16 +0000481 const DominatorTree *DT =
482 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
483 const PostDominatorTree *PDT =
484 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
485
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000486 for (auto &BB : F) {
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000487 if (shouldInstrumentBlock(F, &BB, DT, PDT))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000488 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000489 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000490 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000491 CallSite CS(&Inst);
492 if (CS && !CS.getCalledFunction())
493 IndirCalls.push_back(&Inst);
494 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000495 if (Options.TraceCmp) {
496 if (isa<ICmpInst>(&Inst))
497 CmpTraceTargets.push_back(&Inst);
498 if (isa<SwitchInst>(&Inst))
499 SwitchTraceTargets.push_back(&Inst);
500 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000501 if (Options.TraceDiv)
502 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
503 if (BO->getOpcode() == Instruction::SDiv ||
504 BO->getOpcode() == Instruction::UDiv)
505 DivTraceTargets.push_back(BO);
506 if (Options.TraceGep)
507 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
508 GepTraceTargets.push_back(GEP);
509 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000510 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000511
512 InjectCoverage(F, BlocksToInstrument);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000513 InjectCoverageForIndirectCalls(F, IndirCalls);
514 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000515 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000516 InjectTraceForDiv(F, DivTraceTargets);
517 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000518 return true;
519}
Kostya Serebryany4d25ad92016-10-11 19:36:50 +0000520void SanitizerCoverageModule::CreateFunctionGuardArray(size_t NumGuards,
521 Function &F) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000522 if (!Options.TracePCGuard) return;
523 HasSancovGuardsSection = true;
524 ArrayType *ArrayOfInt32Ty = ArrayType::get(Int32Ty, NumGuards);
525 FunctionGuardArray = new GlobalVariable(
Kostya Serebryany4d25ad92016-10-11 19:36:50 +0000526 *CurModule, ArrayOfInt32Ty, false, GlobalVariable::PrivateLinkage,
Kostya Serebryany9d6dc7b2016-11-15 21:12:50 +0000527 Constant::getNullValue(ArrayOfInt32Ty), "__sancov_gen_");
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000528 if (auto Comdat = F.getComdat())
529 FunctionGuardArray->setComdat(Comdat);
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000530 FunctionGuardArray->setSection(getSanCovTracePCGuardSection());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000531}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000532
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000533bool SanitizerCoverageModule::InjectCoverage(Function &F,
534 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000535 if (AllBlocks.empty()) return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000536 switch (Options.CoverageType) {
537 case SanitizerCoverageOptions::SCK_None:
538 return false;
539 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000540 CreateFunctionGuardArray(1, F);
541 InjectCoverageAtBlock(F, F.getEntryBlock(), 0, false);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000542 return true;
543 default: {
544 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000545 CreateFunctionGuardArray(AllBlocks.size(), F);
546 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
547 InjectCoverageAtBlock(F, *AllBlocks[i], i, UseCalls);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000548 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000549 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000550 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000551}
552
553// On every indirect call we call a run-time function
554// __sanitizer_cov_indir_call* with two parameters:
555// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000556// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000557// The cache is used to speed up recording the caller-callee pairs.
558// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000559// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000560void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
561 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000562 if (IndirCalls.empty())
563 return;
564 const int CacheSize = 16;
565 const int CacheAlignment = 64; // Align for better performance.
566 Type *Ty = ArrayType::get(IntptrTy, CacheSize);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000567 for (auto I : IndirCalls) {
568 IRBuilder<> IRB(I);
569 CallSite CS(I);
570 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000571 if (isa<InlineAsm>(Callee))
572 continue;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000573 GlobalVariable *CalleeCache = new GlobalVariable(
574 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
575 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
Mike Aizatsky759aca02016-03-18 23:29:29 +0000576 CalleeCache->setAlignment(CacheAlignment);
Kostya Serebryany66a9c172016-09-15 22:11:08 +0000577 if (Options.TracePC || Options.TracePCGuard)
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000578 IRB.CreateCall(SanCovTracePCIndir,
579 IRB.CreatePointerCast(Callee, IntptrTy));
580 else
581 IRB.CreateCall(SanCovIndirCallFunction,
582 {IRB.CreatePointerCast(Callee, IntptrTy),
Mike Aizatsky759aca02016-03-18 23:29:29 +0000583 IRB.CreatePointerCast(CalleeCache, IntptrTy)});
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000584 }
585}
586
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000587// For every switch statement we insert a call:
588// __sanitizer_cov_trace_switch(CondValue,
589// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
590
591void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000592 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000593 for (auto I : SwitchTraceTargets) {
594 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
595 IRBuilder<> IRB(I);
596 SmallVector<Constant *, 16> Initializers;
597 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000598 if (Cond->getType()->getScalarSizeInBits() >
599 Int64Ty->getScalarSizeInBits())
600 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000601 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
602 Initializers.push_back(
603 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
604 if (Cond->getType()->getScalarSizeInBits() <
605 Int64Ty->getScalarSizeInBits())
606 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000607 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000608 Constant *C = It.getCaseValue();
609 if (C->getType()->getScalarSizeInBits() <
610 Int64Ty->getScalarSizeInBits())
611 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
612 Initializers.push_back(C);
613 }
Kostya Serebryanyf24e52c2016-12-27 21:20:06 +0000614 std::sort(Initializers.begin() + 2, Initializers.end(),
615 [](const Constant *A, const Constant *B) {
616 return cast<ConstantInt>(A)->getLimitedValue() <
617 cast<ConstantInt>(B)->getLimitedValue();
618 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000619 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
620 GlobalVariable *GV = new GlobalVariable(
621 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
622 ConstantArray::get(ArrayOfInt64Ty, Initializers),
623 "__sancov_gen_cov_switch_values");
624 IRB.CreateCall(SanCovTraceSwitchFunction,
625 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
626 }
627 }
628}
629
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000630void SanitizerCoverageModule::InjectTraceForDiv(
631 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
632 for (auto BO : DivTraceTargets) {
633 IRBuilder<> IRB(BO);
634 Value *A1 = BO->getOperand(1);
635 if (isa<ConstantInt>(A1)) continue;
636 if (!A1->getType()->isIntegerTy())
637 continue;
638 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
639 int CallbackIdx = TypeSize == 32 ? 0 :
640 TypeSize == 64 ? 1 : -1;
641 if (CallbackIdx < 0) continue;
642 auto Ty = Type::getIntNTy(*C, TypeSize);
643 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
644 {IRB.CreateIntCast(A1, Ty, true)});
645 }
646}
647
648void SanitizerCoverageModule::InjectTraceForGep(
649 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
650 for (auto GEP : GepTraceTargets) {
651 IRBuilder<> IRB(GEP);
652 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000653 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000654 IRB.CreateCall(SanCovTraceGepFunction,
655 {IRB.CreateIntCast(*I, IntptrTy, true)});
656 }
657}
658
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000659void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000660 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000661 for (auto I : CmpTraceTargets) {
662 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
663 IRBuilder<> IRB(ICMP);
664 Value *A0 = ICMP->getOperand(0);
665 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000666 if (!A0->getType()->isIntegerTy())
667 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000668 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000669 int CallbackIdx = TypeSize == 8 ? 0 :
670 TypeSize == 16 ? 1 :
671 TypeSize == 32 ? 2 :
672 TypeSize == 64 ? 3 : -1;
673 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000674 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000675 auto Ty = Type::getIntNTy(*C, TypeSize);
David Blaikieff6409d2015-05-18 22:13:54 +0000676 IRB.CreateCall(
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000677 SanCovTraceCmpFunction[CallbackIdx],
678 {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000679 }
680 }
681}
682
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000683void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000684 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
685 MDNode::get(*C, None));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000686}
687
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000688void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000689 size_t Idx, bool UseCalls) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000690 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000691 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000692 DebugLoc EntryLoc;
693 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000694 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000695 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000696 // Keep static allocas and llvm.localescape calls in the entry block. Even
697 // if we aren't splitting the block, it's nice for allocas to be before
698 // calls.
699 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000700 } else {
701 EntryLoc = IP->getDebugLoc();
702 }
703
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000704 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000705 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000706 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000707 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
708 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000709 } else if (Options.TracePCGuard) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000710 auto GuardPtr = IRB.CreateIntToPtr(
711 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
712 ConstantInt::get(IntptrTy, Idx * 4)),
713 Int32PtrTy);
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000714 if (!UseCalls) {
715 auto GuardLoad = IRB.CreateLoad(GuardPtr);
716 GuardLoad->setAtomic(AtomicOrdering::Monotonic);
717 GuardLoad->setAlignment(8);
718 SetNoSanitizeMetadata(GuardLoad); // Don't instrument with e.g. asan.
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000719 auto Cmp = IRB.CreateICmpNE(
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000720 GuardLoad, Constant::getNullValue(GuardLoad->getType()));
721 auto Ins = SplitBlockAndInsertIfThen(
722 Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000723 IRB.SetInsertPoint(Ins);
Kostya Serebryany520753a2016-12-03 01:43:30 +0000724 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000725 }
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000726 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
727 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000728 } else {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000729 Value *GuardP = IRB.CreateAdd(
730 IRB.CreatePointerCast(GuardArray, IntptrTy),
731 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
732 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
733 if (Options.TraceBB) {
734 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
735 } else if (UseCalls) {
736 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
737 } else {
738 LoadInst *Load = IRB.CreateLoad(GuardP);
739 Load->setAtomic(AtomicOrdering::Monotonic);
740 Load->setAlignment(4);
741 SetNoSanitizeMetadata(Load);
742 Value *Cmp =
743 IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
744 Instruction *Ins = SplitBlockAndInsertIfThen(
745 Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
746 IRB.SetInsertPoint(Ins);
747 IRB.SetCurrentDebugLocation(EntryLoc);
748 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
749 IRB.CreateCall(SanCovFunction, GuardP);
750 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
751 }
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000752 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000753
Alexey Samsonov3514f272015-05-07 01:00:31 +0000754 if (Options.Use8bitCounters) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000755 IRB.SetInsertPoint(&*IP);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000756 Value *P = IRB.CreateAdd(
757 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000758 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000759 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000760 LoadInst *LI = IRB.CreateLoad(P);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000761 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000762 StoreInst *SI = IRB.CreateStore(Inc, P);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000763 SetNoSanitizeMetadata(LI);
764 SetNoSanitizeMetadata(SI);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000765 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000766}
767
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000768StringRef SanitizerCoverageModule::getSanCovTracePCGuardSection() const {
769 if (TargetTriple.getObjectFormat() == Triple::COFF)
770 return ".SCOV$M";
771 if (TargetTriple.isOSBinFormatMachO())
772 return "__DATA,__sancov_guards";
773 return "__sancov_guards";
774}
775
776StringRef SanitizerCoverageModule::getSanCovTracePCGuardSectionStart() const {
777 if (TargetTriple.isOSBinFormatMachO())
778 return "\1section$start$__DATA$__sancov_guards";
779 return "__start___sancov_guards";
780}
781
782StringRef SanitizerCoverageModule::getSanCovTracePCGuardSectionEnd() const {
783 if (TargetTriple.isOSBinFormatMachO())
784 return "\1section$end$__DATA$__sancov_guards";
785 return "__stop___sancov_guards";
786}
787
788
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000789char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000790INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000791 "SanitizerCoverage: TODO."
792 "ModulePass",
793 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000794INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
795INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
796INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000797 "SanitizerCoverage: TODO."
798 "ModulePass",
799 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000800ModulePass *llvm::createSanitizerCoverageModulePass(
801 const SanitizerCoverageOptions &Options) {
802 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000803}