blob: d950e2e730f27feb4d8b193be4b1f9366cbe6d2c [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//
Kostya Serebryany53b34c82017-05-31 18:27:33 +000010// Coverage instrumentation done on LLVM IR level, works with Sanitizers.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000011//
12//===----------------------------------------------------------------------===//
13
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000014#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/SmallVector.h"
David Majnemer70497c62015-12-02 23:06:39 +000016#include "llvm/Analysis/EHPersonalities.h"
George Karpenkov018472c2017-05-24 00:29:12 +000017#include "llvm/Analysis/PostDominators.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000018#include "llvm/IR/CFG.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000019#include "llvm/IR/CallSite.h"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000020#include "llvm/IR/Constant.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000021#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000022#include "llvm/IR/DebugInfo.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000023#include "llvm/IR/Dominators.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000024#include "llvm/IR/Function.h"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000025#include "llvm/IR/GlobalVariable.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000026#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000027#include "llvm/IR/InlineAsm.h"
Matt Morehouse034126e2017-08-30 22:49:31 +000028#include "llvm/IR/IntrinsicInst.h"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000029#include "llvm/IR/Intrinsics.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000030#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/raw_ostream.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000037#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000038#include "llvm/Transforms/Scalar.h"
39#include "llvm/Transforms/Utils/BasicBlockUtils.h"
40#include "llvm/Transforms/Utils/ModuleUtils.h"
41
42using namespace llvm;
43
44#define DEBUG_TYPE "sancov"
45
Mike Aizatsky759aca02016-03-18 23:29:29 +000046static const char *const SanCovTracePCIndirName =
47 "__sanitizer_cov_trace_pc_indir";
Mike Aizatsky759aca02016-03-18 23:29:29 +000048static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
Kostya Serebryany524c3f32016-08-18 01:25:28 +000049static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
50static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
51static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
52static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
Justin Bognerbe757de2017-08-28 23:38:12 +000053static const char *const SanCovTraceConstCmp1 =
Alexander Potapenko52410812017-08-10 15:00:13 +000054 "__sanitizer_cov_trace_const_cmp1";
Justin Bognerbe757de2017-08-28 23:38:12 +000055static const char *const SanCovTraceConstCmp2 =
Alexander Potapenko52410812017-08-10 15:00:13 +000056 "__sanitizer_cov_trace_const_cmp2";
Justin Bognerbe757de2017-08-28 23:38:12 +000057static const char *const SanCovTraceConstCmp4 =
Alexander Potapenko52410812017-08-10 15:00:13 +000058 "__sanitizer_cov_trace_const_cmp4";
Justin Bognerbe757de2017-08-28 23:38:12 +000059static const char *const SanCovTraceConstCmp8 =
Alexander Potapenko52410812017-08-10 15:00:13 +000060 "__sanitizer_cov_trace_const_cmp8";
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000061static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
62static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
63static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
Mike Aizatsky759aca02016-03-18 23:29:29 +000064static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
65static const char *const SanCovModuleCtorName = "sancov.module_ctor";
66static const uint64_t SanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000067
Kostya Serebryanyda718e52016-09-14 01:39:35 +000068static const char *const SanCovTracePCGuardName =
69 "__sanitizer_cov_trace_pc_guard";
70static const char *const SanCovTracePCGuardInitName =
71 "__sanitizer_cov_trace_pc_guard_init";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000072static const char *const SanCov8bitCountersInitName =
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000073 "__sanitizer_cov_8bit_counters_init";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000074static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
Kostya Serebryanyda718e52016-09-14 01:39:35 +000075
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000076static const char *const SanCovGuardsSectionName = "sancov_guards";
George Karpenkov406c1132017-06-14 23:40:25 +000077static const char *const SanCovCountersSectionName = "sancov_cntrs";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000078static const char *const SanCovPCsSectionName = "sancov_pcs";
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000079
Matt Morehouse5c7fc762017-08-18 18:43:30 +000080static const char *const SanCovLowestStackName = "__sancov_lowest_stack";
Matt Morehouse5c7fc762017-08-18 18:43:30 +000081
Mike Aizatsky759aca02016-03-18 23:29:29 +000082static cl::opt<int> ClCoverageLevel(
83 "sanitizer-coverage-level",
84 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +000085 "3: all blocks and critical edges"),
Mike Aizatsky759aca02016-03-18 23:29:29 +000086 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000087
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000088static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
89 cl::desc("Experimental pc tracing"), cl::Hidden,
90 cl::init(false));
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000091
Kostya Serebryanyda718e52016-09-14 01:39:35 +000092static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
93 cl::desc("pc tracing with a guard"),
94 cl::Hidden, cl::init(false));
95
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000096// If true, we create a global variable that contains PCs of all instrumented
97// BBs, put this global into a named section, and pass this section's bounds
98// to __sanitizer_cov_pcs_init.
99// This way the coverage instrumentation does not need to acquire the PCs
100// at run-time. Works with trace-pc-guard and inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000101static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000102 cl::desc("create a static PC table"),
103 cl::Hidden, cl::init(false));
104
105static cl::opt<bool>
106 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
107 cl::desc("increments 8-bit counter for every edge"),
108 cl::Hidden, cl::init(false));
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000109
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000110static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000111 ClCMPTracing("sanitizer-coverage-trace-compares",
112 cl::desc("Tracing of CMP and similar instructions"),
113 cl::Hidden, cl::init(false));
114
115static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
116 cl::desc("Tracing of DIV instructions"),
117 cl::Hidden, cl::init(false));
118
119static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
120 cl::desc("Tracing of GEP instructions"),
121 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000122
Mike Aizatsky70ea4532016-04-06 23:24:37 +0000123static cl::opt<bool>
124 ClPruneBlocks("sanitizer-coverage-prune-blocks",
125 cl::desc("Reduce the number of instrumented blocks"),
126 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000127
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000128static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
129 cl::desc("max stack depth tracing"),
130 cl::Hidden, cl::init(false));
131
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000132namespace {
133
Alexey Samsonov3514f272015-05-07 01:00:31 +0000134SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
135 SanitizerCoverageOptions Res;
136 switch (LegacyCoverageLevel) {
137 case 0:
138 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
139 break;
140 case 1:
141 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
142 break;
143 case 2:
144 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
145 break;
146 case 3:
147 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
148 break;
149 case 4:
150 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
151 Res.IndirectCalls = true;
152 break;
153 }
154 return Res;
155}
156
157SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
158 // Sets CoverageType and IndirectCalls.
159 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
160 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
161 Options.IndirectCalls |= CLOpts.IndirectCalls;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000162 Options.TraceCmp |= ClCMPTracing;
163 Options.TraceDiv |= ClDIVTracing;
164 Options.TraceGep |= ClGEPTracing;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000165 Options.TracePC |= ClTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000166 Options.TracePCGuard |= ClTracePCGuard;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000167 Options.Inline8bitCounters |= ClInline8bitCounters;
Kostya Serebryany063b6522017-07-28 00:09:29 +0000168 Options.PCTable |= ClCreatePCTable;
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000169 Options.NoPrune |= !ClPruneBlocks;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000170 Options.StackDepth |= ClStackDepth;
171 if (!Options.TracePCGuard && !Options.TracePC &&
172 !Options.Inline8bitCounters && !Options.StackDepth)
173 Options.TracePCGuard = true; // TracePCGuard is default.
Alexey Samsonov3514f272015-05-07 01:00:31 +0000174 return Options;
175}
176
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000177class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000178public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000179 SanitizerCoverageModule(
180 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000181 : ModulePass(ID), Options(OverrideFromCL(Options)) {
182 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
183 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000184 bool runOnModule(Module &M) override;
185 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000186 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000187 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000188
Chandler Carruth30061152016-03-18 22:43:42 +0000189 void getAnalysisUsage(AnalysisUsage &AU) const override {
190 AU.addRequired<DominatorTreeWrapperPass>();
George Karpenkov018472c2017-05-24 00:29:12 +0000191 AU.addRequired<PostDominatorTreeWrapperPass>();
Chandler Carruth30061152016-03-18 22:43:42 +0000192 }
193
194private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000195 void InjectCoverageForIndirectCalls(Function &F,
196 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000197 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000198 void InjectTraceForDiv(Function &F,
199 ArrayRef<BinaryOperator *> DivTraceTargets);
200 void InjectTraceForGep(Function &F,
201 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000202 void InjectTraceForSwitch(Function &F,
203 ArrayRef<Instruction *> SwitchTraceTargets);
Matt Morehouse034126e2017-08-30 22:49:31 +0000204 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
205 bool IsLeafFunc = true);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000206 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
207 Function &F, Type *Ty,
208 const char *Section);
Justin Bogner873a0742017-08-28 23:46:11 +0000209 GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000210 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Matt Morehouse034126e2017-08-30 22:49:31 +0000211 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
212 bool IsLeafFunc = true);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000213 Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
214 Type *Ty, const char *Section);
215 std::pair<GlobalVariable *, GlobalVariable *>
216 CreateSecStartEnd(Module &M, const char *Section, Type *Ty);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000217
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000218 void SetNoSanitizeMetadata(Instruction *I) {
219 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
220 MDNode::get(*C, None));
221 }
222
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000223 std::string getSectionName(const std::string &Section) const;
224 std::string getSectionStart(const std::string &Section) const;
225 std::string getSectionEnd(const std::string &Section) const;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000226 Function *SanCovTracePCIndir;
Kostya Serebryanybe87d482017-04-19 21:48:09 +0000227 Function *SanCovTracePC, *SanCovTracePCGuard;
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000228 Function *SanCovTraceCmpFunction[4];
Alexander Potapenko52410812017-08-10 15:00:13 +0000229 Function *SanCovTraceConstCmpFunction[4];
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000230 Function *SanCovTraceDivFunction[2];
231 Function *SanCovTraceGepFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000232 Function *SanCovTraceSwitchFunction;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000233 GlobalVariable *SanCovLowestStack;
Kostya Serebryany73762942014-12-16 21:24:15 +0000234 InlineAsm *EmptyAsm;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000235 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
Alexander Potapenko52410812017-08-10 15:00:13 +0000236 *Int16Ty, *Int8Ty, *Int8PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000237 Module *CurModule;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000238 Triple TargetTriple;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000239 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000240 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000241
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000242 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000243 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000244 GlobalVariable *FunctionPCsArray; // for pc-table.
Kostya Serebryany4192b962017-09-09 05:30:13 +0000245 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000246
Alexey Samsonov3514f272015-05-07 01:00:31 +0000247 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000248};
249
Mike Aizatsky759aca02016-03-18 23:29:29 +0000250} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000251
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000252std::pair<GlobalVariable *, GlobalVariable *>
253SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
254 Type *Ty) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000255 GlobalVariable *SecStart =
256 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
257 getSectionStart(Section));
258 SecStart->setVisibility(GlobalValue::HiddenVisibility);
259 GlobalVariable *SecEnd =
260 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
261 nullptr, getSectionEnd(Section));
262 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
263
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000264 return std::make_pair(SecStart, SecEnd);
265}
266
267
268Function *SanitizerCoverageModule::CreateInitCallsForSections(
269 Module &M, const char *InitFunctionName, Type *Ty,
270 const char *Section) {
271 IRBuilder<> IRB(M.getContext());
272 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
273 auto SecStart = SecStartEnd.first;
274 auto SecEnd = SecStartEnd.second;
275 Function *CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000276 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
277 M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
278 {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
279
280 if (TargetTriple.supportsCOMDAT()) {
281 // Use comdat to dedup CtorFunc.
282 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
283 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
284 } else {
285 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
286 }
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000287 return CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000288}
289
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000290bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000291 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
292 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000293 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000294 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000295 CurModule = &M;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000296 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000297 FunctionGuardArray = nullptr;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000298 Function8bitCounterArray = nullptr;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000299 FunctionPCsArray = nullptr;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000300 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000301 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000302 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000303 IRBuilder<> IRB(*C);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000304 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000305 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000306 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000307 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000308 Int32Ty = IRB.getInt32Ty();
Alexander Potapenko52410812017-08-10 15:00:13 +0000309 Int16Ty = IRB.getInt16Ty();
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000310 Int8Ty = IRB.getInt8Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000311
Mike Aizatsky759aca02016-03-18 23:29:29 +0000312 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000313 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000314 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000315 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000316 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000317 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
318 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000319 IRB.getInt16Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000320 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
321 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000322 IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000323 SanCovTraceCmpFunction[3] =
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000324 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000325 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000326
Alexander Potapenko52410812017-08-10 15:00:13 +0000327 SanCovTraceConstCmpFunction[0] =
328 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
329 SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
330 SanCovTraceConstCmpFunction[1] =
331 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
332 SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
333 SanCovTraceConstCmpFunction[2] =
334 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
335 SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
336 SanCovTraceConstCmpFunction[3] =
337 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
338 SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
339
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000340 SanCovTraceDivFunction[0] =
341 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000342 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000343 SanCovTraceDivFunction[1] =
344 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000345 SanCovTraceDiv8, VoidTy, Int64Ty));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000346 SanCovTraceGepFunction =
347 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000348 SanCovTraceGep, VoidTy, IntptrTy));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000349 SanCovTraceSwitchFunction =
350 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000351 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000352
353 Constant *SanCovLowestStackConstant =
354 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000355 SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
356 SanCovLowestStack->setThreadLocalMode(
357 GlobalValue::ThreadLocalMode::InitialExecTLSModel);
358 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
359 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000360
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000361 // Make sure smaller parameters are zero-extended to i64 as required by the
362 // x86_64 ABI.
363 if (TargetTriple.getArch() == Triple::x86_64) {
364 for (int i = 0; i < 3; i++) {
365 SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
366 SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko52410812017-08-10 15:00:13 +0000367 SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
368 SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000369 }
370 SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
371 }
372
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000373
Kostya Serebryany73762942014-12-16 21:24:15 +0000374 // We insert an empty inline asm after cov callbacks to avoid callback merge.
375 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
376 StringRef(""), StringRef(""),
377 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000378
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000379 SanCovTracePC = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000380 M.getOrInsertFunction(SanCovTracePCName, VoidTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000381 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000382 SanCovTracePCGuardName, VoidTy, Int32PtrTy));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000383
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000384 for (auto &F : M)
385 runOnFunction(F);
386
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000387 Function *Ctor = nullptr;
Justin Bogner41e632b2017-02-01 02:38:39 +0000388
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000389 if (FunctionGuardArray)
390 Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
391 SanCovGuardsSectionName);
392 if (Function8bitCounterArray)
393 Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
394 SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000395 if (Ctor && Options.PCTable) {
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000396 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000397 Function *InitFunction = declareSanitizerInitFunction(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000398 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000399 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
400 IRBCtor.CreateCall(InitFunction,
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000401 {IRB.CreatePointerCast(SecStartEnd.first, IntptrPtrTy),
402 IRB.CreatePointerCast(SecStartEnd.second, IntptrPtrTy)});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000403 }
Kostya Serebryany4192b962017-09-09 05:30:13 +0000404 // We don't reference these arrays directly in any of our runtime functions,
405 // so we need to prevent them from being dead stripped.
406 if (TargetTriple.isOSBinFormatMachO())
407 appendToUsed(M, GlobalsToAppendToUsed);
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
George Karpenkov018472c2017-05-24 00:29:12 +0000424// 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
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000438static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
439 const DominatorTree *DT,
George Karpenkov018472c2017-05-24 00:29:12 +0000440 const PostDominatorTree *PDT,
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000441 const SanitizerCoverageOptions &Options) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000442 // Don't insert coverage for unreachable blocks: we will never call
443 // __sanitizer_cov() for them, so counting them in
444 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
445 // percentage. Also, unreachable instructions frequently have no debug
446 // locations.
447 if (isa<UnreachableInst>(BB->getTerminator()))
448 return false;
449
Reid Kleckner392f0622017-03-23 23:30:41 +0000450 // Don't insert coverage into blocks without a valid insertion point
451 // (catchswitch blocks).
452 if (BB->getFirstInsertionPt() == BB->end())
453 return false;
454
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000455 if (Options.NoPrune || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000456 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000457
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000458 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
459 &F.getEntryBlock() != BB)
460 return false;
461
George Karpenkova1c53272017-05-25 01:41:46 +0000462 // Do not instrument full dominators, or full post-dominators with multiple
463 // predecessors.
464 return !isFullDominator(BB, DT)
465 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
Mike Aizatsky5971f182016-02-26 01:17:22 +0000466}
467
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000468bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000469 if (F.empty())
470 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000471 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000472 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000473 if (F.getName().startswith("__sanitizer_"))
474 return false; // Don't instrument __sanitizer_* callbacks.
Kostya Serebryanybfc83fa2017-07-31 20:00:22 +0000475 // Don't touch available_externally functions, their actual body is elewhere.
476 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
477 return false;
Reid Klecknerec803542016-11-11 19:18:45 +0000478 // Don't instrument MSVC CRT configuration helpers. They may run before normal
479 // initialization.
480 if (F.getName() == "__local_stdio_printf_options" ||
481 F.getName() == "__local_stdio_scanf_options")
482 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000483 // Don't instrument functions using SEH for now. Splitting basic blocks like
484 // we do for coverage breaks WinEHPrepare.
485 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
486 if (F.hasPersonalityFn() &&
487 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
488 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000489 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000490 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000491 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000492 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000493 SmallVector<Instruction *, 8> CmpTraceTargets;
494 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000495 SmallVector<BinaryOperator *, 8> DivTraceTargets;
496 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000497
Mike Aizatsky602f7922016-03-21 23:08:16 +0000498 const DominatorTree *DT =
499 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
George Karpenkov018472c2017-05-24 00:29:12 +0000500 const PostDominatorTree *PDT =
501 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
Matt Morehouse034126e2017-08-30 22:49:31 +0000502 bool IsLeafFunc = true;
Mike Aizatsky602f7922016-03-21 23:08:16 +0000503
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000504 for (auto &BB : F) {
George Karpenkov018472c2017-05-24 00:29:12 +0000505 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000506 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000507 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000508 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000509 CallSite CS(&Inst);
510 if (CS && !CS.getCalledFunction())
511 IndirCalls.push_back(&Inst);
512 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000513 if (Options.TraceCmp) {
514 if (isa<ICmpInst>(&Inst))
515 CmpTraceTargets.push_back(&Inst);
516 if (isa<SwitchInst>(&Inst))
517 SwitchTraceTargets.push_back(&Inst);
518 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000519 if (Options.TraceDiv)
520 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
521 if (BO->getOpcode() == Instruction::SDiv ||
522 BO->getOpcode() == Instruction::UDiv)
523 DivTraceTargets.push_back(BO);
524 if (Options.TraceGep)
525 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
526 GepTraceTargets.push_back(GEP);
Matt Morehouse034126e2017-08-30 22:49:31 +0000527 if (Options.StackDepth)
528 if (isa<InvokeInst>(Inst) ||
529 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
530 IsLeafFunc = false;
531 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000532 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000533
Matt Morehouse034126e2017-08-30 22:49:31 +0000534 InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000535 InjectCoverageForIndirectCalls(F, IndirCalls);
536 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000537 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000538 InjectTraceForDiv(F, DivTraceTargets);
539 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000540 return true;
541}
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000542
543GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
544 size_t NumElements, Function &F, Type *Ty, const char *Section) {
545 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
546 auto Array = new GlobalVariable(
547 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
548 Constant::getNullValue(ArrayTy), "__sancov_gen_");
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000549 if (auto Comdat = F.getComdat())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000550 Array->setComdat(Comdat);
551 Array->setSection(getSectionName(Section));
Kostya Serebryanybb6f0792017-07-31 19:49:45 +0000552 Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
553 : Ty->getPrimitiveSizeInBits() / 8);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000554 return Array;
555}
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000556
Justin Bogner873a0742017-08-28 23:46:11 +0000557GlobalVariable *
558SanitizerCoverageModule::CreatePCArray(Function &F,
559 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000560 size_t N = AllBlocks.size();
561 assert(N);
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000562 SmallVector<Constant *, 32> PCs;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000563 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000564 for (size_t i = 0; i < N; i++) {
565 if (&F.getEntryBlock() == AllBlocks[i]) {
566 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
567 PCs.push_back((Constant *)IRB.CreateIntToPtr(
568 ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
569 } else {
570 PCs.push_back((Constant *)IRB.CreatePointerCast(
571 BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
572 PCs.push_back((Constant *)IRB.CreateIntToPtr(
573 ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
574 }
575 }
Justin Bogner873a0742017-08-28 23:46:11 +0000576 auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
577 SanCovPCsSectionName);
578 PCArray->setInitializer(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000579 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
Justin Bogner873a0742017-08-28 23:46:11 +0000580 PCArray->setConstant(true);
Justin Bognerad96ff12017-08-25 01:24:54 +0000581
Justin Bogner873a0742017-08-28 23:46:11 +0000582 return PCArray;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000583}
584
585void SanitizerCoverageModule::CreateFunctionLocalArrays(
586 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
Justin Bognerf1a54a42017-08-29 00:11:05 +0000587 if (Options.TracePCGuard) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000588 FunctionGuardArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000589 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
Kostya Serebryany4192b962017-09-09 05:30:13 +0000590 GlobalsToAppendToUsed.push_back(FunctionGuardArray);
Justin Bognerf1a54a42017-08-29 00:11:05 +0000591 }
592 if (Options.Inline8bitCounters) {
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000593 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000594 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
Kostya Serebryany4192b962017-09-09 05:30:13 +0000595 GlobalsToAppendToUsed.push_back(Function8bitCounterArray);
Justin Bognerf1a54a42017-08-29 00:11:05 +0000596 }
597 if (Options.PCTable) {
Justin Bogner873a0742017-08-28 23:46:11 +0000598 FunctionPCsArray = CreatePCArray(F, AllBlocks);
Kostya Serebryany4192b962017-09-09 05:30:13 +0000599 GlobalsToAppendToUsed.push_back(FunctionPCsArray);
Justin Bognerf1a54a42017-08-29 00:11:05 +0000600 }
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000601}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000602
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000603bool SanitizerCoverageModule::InjectCoverage(Function &F,
Matt Morehouse034126e2017-08-30 22:49:31 +0000604 ArrayRef<BasicBlock *> AllBlocks,
605 bool IsLeafFunc) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000606 if (AllBlocks.empty()) return false;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000607 CreateFunctionLocalArrays(F, AllBlocks);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000608 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
Matt Morehouse034126e2017-08-30 22:49:31 +0000609 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000610 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000611}
612
613// On every indirect call we call a run-time function
614// __sanitizer_cov_indir_call* with two parameters:
615// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000616// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000617// The cache is used to speed up recording the caller-callee pairs.
618// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000619// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000620void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
621 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000622 if (IndirCalls.empty())
623 return;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000624 assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000625 for (auto I : IndirCalls) {
626 IRBuilder<> IRB(I);
627 CallSite CS(I);
628 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000629 if (isa<InlineAsm>(Callee))
630 continue;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000631 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000632 }
633}
634
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000635// For every switch statement we insert a call:
636// __sanitizer_cov_trace_switch(CondValue,
637// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
638
639void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000640 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000641 for (auto I : SwitchTraceTargets) {
642 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
643 IRBuilder<> IRB(I);
644 SmallVector<Constant *, 16> Initializers;
645 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000646 if (Cond->getType()->getScalarSizeInBits() >
647 Int64Ty->getScalarSizeInBits())
648 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000649 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
650 Initializers.push_back(
651 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
652 if (Cond->getType()->getScalarSizeInBits() <
653 Int64Ty->getScalarSizeInBits())
654 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000655 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000656 Constant *C = It.getCaseValue();
657 if (C->getType()->getScalarSizeInBits() <
658 Int64Ty->getScalarSizeInBits())
659 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
660 Initializers.push_back(C);
661 }
Kostya Serebryanyf24e52c2016-12-27 21:20:06 +0000662 std::sort(Initializers.begin() + 2, Initializers.end(),
663 [](const Constant *A, const Constant *B) {
664 return cast<ConstantInt>(A)->getLimitedValue() <
665 cast<ConstantInt>(B)->getLimitedValue();
666 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000667 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
668 GlobalVariable *GV = new GlobalVariable(
669 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
670 ConstantArray::get(ArrayOfInt64Ty, Initializers),
671 "__sancov_gen_cov_switch_values");
672 IRB.CreateCall(SanCovTraceSwitchFunction,
673 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
674 }
675 }
676}
677
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000678void SanitizerCoverageModule::InjectTraceForDiv(
679 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
680 for (auto BO : DivTraceTargets) {
681 IRBuilder<> IRB(BO);
682 Value *A1 = BO->getOperand(1);
683 if (isa<ConstantInt>(A1)) continue;
684 if (!A1->getType()->isIntegerTy())
685 continue;
686 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
687 int CallbackIdx = TypeSize == 32 ? 0 :
688 TypeSize == 64 ? 1 : -1;
689 if (CallbackIdx < 0) continue;
690 auto Ty = Type::getIntNTy(*C, TypeSize);
691 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
692 {IRB.CreateIntCast(A1, Ty, true)});
693 }
694}
695
696void SanitizerCoverageModule::InjectTraceForGep(
697 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
698 for (auto GEP : GepTraceTargets) {
699 IRBuilder<> IRB(GEP);
700 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000701 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000702 IRB.CreateCall(SanCovTraceGepFunction,
703 {IRB.CreateIntCast(*I, IntptrTy, true)});
704 }
705}
706
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000707void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000708 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000709 for (auto I : CmpTraceTargets) {
710 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
711 IRBuilder<> IRB(ICMP);
712 Value *A0 = ICMP->getOperand(0);
713 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000714 if (!A0->getType()->isIntegerTy())
715 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000716 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000717 int CallbackIdx = TypeSize == 8 ? 0 :
718 TypeSize == 16 ? 1 :
719 TypeSize == 32 ? 2 :
720 TypeSize == 64 ? 3 : -1;
721 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000722 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Alexander Potapenko52410812017-08-10 15:00:13 +0000723 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
724 bool FirstIsConst = isa<ConstantInt>(A0);
725 bool SecondIsConst = isa<ConstantInt>(A1);
726 // If both are const, then we don't need such a comparison.
727 if (FirstIsConst && SecondIsConst) continue;
728 // If only one is const, then make it the first callback argument.
729 if (FirstIsConst || SecondIsConst) {
730 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
Justin Bognerbe757de2017-08-28 23:38:12 +0000731 if (SecondIsConst)
Alexander Potapenko52410812017-08-10 15:00:13 +0000732 std::swap(A0, A1);
733 }
734
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000735 auto Ty = Type::getIntNTy(*C, TypeSize);
Justin Bognerbe757de2017-08-28 23:38:12 +0000736 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
Alexander Potapenko52410812017-08-10 15:00:13 +0000737 IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000738 }
739 }
740}
741
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000742void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Matt Morehouse034126e2017-08-30 22:49:31 +0000743 size_t Idx,
744 bool IsLeafFunc) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000745 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000746 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000747 DebugLoc EntryLoc;
748 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000749 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000750 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000751 // Keep static allocas and llvm.localescape calls in the entry block. Even
752 // if we aren't splitting the block, it's nice for allocas to be before
753 // calls.
754 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000755 } else {
756 EntryLoc = IP->getDebugLoc();
757 }
758
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000759 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000760 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000761 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000762 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
763 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000764 }
765 if (Options.TracePCGuard) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000766 auto GuardPtr = IRB.CreateIntToPtr(
767 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
768 ConstantInt::get(IntptrTy, Idx * 4)),
769 Int32PtrTy);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000770 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
771 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000772 }
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000773 if (Options.Inline8bitCounters) {
774 auto CounterPtr = IRB.CreateGEP(
775 Function8bitCounterArray,
776 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
777 auto Load = IRB.CreateLoad(CounterPtr);
778 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
779 auto Store = IRB.CreateStore(Inc, CounterPtr);
780 SetNoSanitizeMetadata(Load);
781 SetNoSanitizeMetadata(Store);
782 }
Matt Morehouse034126e2017-08-30 22:49:31 +0000783 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000784 // Check stack depth. If it's the deepest so far, record it.
785 Function *GetFrameAddr =
786 Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
787 auto FrameAddrPtr =
788 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
789 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000790 auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000791 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
792 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
793 IRBuilder<> ThenIRB(ThenTerm);
Matt Morehouse034126e2017-08-30 22:49:31 +0000794 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
795 SetNoSanitizeMetadata(LowestStack);
796 SetNoSanitizeMetadata(Store);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000797 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000798}
799
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000800std::string
801SanitizerCoverageModule::getSectionName(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000802 if (TargetTriple.getObjectFormat() == Triple::COFF)
803 return ".SCOV$M";
804 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000805 return "__DATA,__" + Section;
806 return "__" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000807}
808
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000809std::string
810SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000811 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000812 return "\1section$start$__DATA$__" + Section;
813 return "__start___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000814}
815
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000816std::string
817SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000818 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000819 return "\1section$end$__DATA$__" + Section;
820 return "__stop___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000821}
822
823
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000824char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000825INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000826 "SanitizerCoverage: TODO."
827 "ModulePass",
828 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000829INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
George Karpenkov018472c2017-05-24 00:29:12 +0000830INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Mike Aizatsky90562842016-02-27 05:50:40 +0000831INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000832 "SanitizerCoverage: TODO."
833 "ModulePass",
834 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000835ModulePass *llvm::createSanitizerCoverageModulePass(
836 const SanitizerCoverageOptions &Options) {
837 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000838}