blob: 074ae1347f1a69f25e8c06914876a7e90c261163 [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"
Jonathan Metzman0b94e882018-10-12 18:11:47 +000032#include "llvm/IR/Mangler.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000033#include "llvm/IR/Module.h"
34#include "llvm/IR/Type.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/raw_ostream.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000038#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000039#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);
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000215 std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
216 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;
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000238 std::string CurModuleUniqueId;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000239 Triple TargetTriple;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000240 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000241 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000242
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000243 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000244 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000245 GlobalVariable *FunctionPCsArray; // for pc-table.
Kostya Serebryany4192b962017-09-09 05:30:13 +0000246 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
Matt Morehouse0ea9a902018-06-15 20:12:58 +0000247 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000248
Alexey Samsonov3514f272015-05-07 01:00:31 +0000249 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000250};
251
Mike Aizatsky759aca02016-03-18 23:29:29 +0000252} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000253
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000254std::pair<Value *, Value *>
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000255SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
256 Type *Ty) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000257 GlobalVariable *SecStart =
258 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
259 getSectionStart(Section));
260 SecStart->setVisibility(GlobalValue::HiddenVisibility);
261 GlobalVariable *SecEnd =
262 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
263 nullptr, getSectionEnd(Section));
264 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000265 IRBuilder<> IRB(M.getContext());
266 Value *SecEndPtr = IRB.CreatePointerCast(SecEnd, Ty);
267 if (TargetTriple.getObjectFormat() != Triple::COFF)
268 return std::make_pair(IRB.CreatePointerCast(SecStart, Ty), SecEndPtr);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000269
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000270 // Account for the fact that on windows-msvc __start_* symbols actually
271 // point to a uint64_t before the start of the array.
272 auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
273 auto GEP = IRB.CreateGEP(SecStartI8Ptr,
274 ConstantInt::get(IntptrTy, sizeof(uint64_t)));
275 return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEndPtr);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000276}
277
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000278Function *SanitizerCoverageModule::CreateInitCallsForSections(
279 Module &M, const char *InitFunctionName, Type *Ty,
280 const char *Section) {
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000281 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
282 auto SecStart = SecStartEnd.first;
283 auto SecEnd = SecStartEnd.second;
284 Function *CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000285 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000286 M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd});
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000287
288 if (TargetTriple.supportsCOMDAT()) {
289 // Use comdat to dedup CtorFunc.
290 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
291 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
292 } else {
293 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
294 }
Jonathan Metzman0b94e882018-10-12 18:11:47 +0000295
296 if (TargetTriple.getObjectFormat() == Triple::COFF) {
297 // In COFF files, if the contructors are set as COMDAT (they are because
298 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
299 // functions and data) is used, the constructors get stripped. To prevent
300 // this, give the constructors weak ODR linkage and tell the linker to
301 // always include the sancov constructor. This way the linker can
302 // deduplicate the constructors but always leave one copy.
303 CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
304 SmallString<20> PartialIncDirective("/include:");
305 // Get constructor's mangled name in order to support i386.
306 SmallString<40> MangledName;
307 Mangler().getNameWithPrefix(MangledName, CtorFunc, true);
308 Twine IncDirective = PartialIncDirective + MangledName;
309 Metadata *Args[1] = {MDString::get(*C, IncDirective.str())};
310 MDNode *MetadataNode = MDNode::get(*C, Args);
311 NamedMDNode *NamedMetadata =
312 M.getOrInsertNamedMetadata("llvm.linker.options");
313 NamedMetadata->addOperand(MetadataNode);
314 }
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000315 return CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000316}
317
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000318bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000319 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
320 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000321 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000322 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000323 CurModule = &M;
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000324 CurModuleUniqueId = getUniqueModuleId(CurModule);
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000325 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000326 FunctionGuardArray = nullptr;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000327 Function8bitCounterArray = nullptr;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000328 FunctionPCsArray = nullptr;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000329 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000330 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000331 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000332 IRBuilder<> IRB(*C);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000333 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000334 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000335 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000336 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000337 Int32Ty = IRB.getInt32Ty();
Alexander Potapenko52410812017-08-10 15:00:13 +0000338 Int16Ty = IRB.getInt16Ty();
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000339 Int8Ty = IRB.getInt8Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000340
Mike Aizatsky759aca02016-03-18 23:29:29 +0000341 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000342 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000343 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000344 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000345 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000346 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
347 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000348 IRB.getInt16Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000349 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
350 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000351 IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000352 SanCovTraceCmpFunction[3] =
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000353 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000354 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000355
Alexander Potapenko52410812017-08-10 15:00:13 +0000356 SanCovTraceConstCmpFunction[0] =
357 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
358 SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
359 SanCovTraceConstCmpFunction[1] =
360 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
361 SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
362 SanCovTraceConstCmpFunction[2] =
363 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
364 SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
365 SanCovTraceConstCmpFunction[3] =
366 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
367 SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
368
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000369 SanCovTraceDivFunction[0] =
370 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000371 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000372 SanCovTraceDivFunction[1] =
373 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000374 SanCovTraceDiv8, VoidTy, Int64Ty));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000375 SanCovTraceGepFunction =
376 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000377 SanCovTraceGep, VoidTy, IntptrTy));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000378 SanCovTraceSwitchFunction =
379 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000380 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000381
382 Constant *SanCovLowestStackConstant =
383 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000384 SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
385 SanCovLowestStack->setThreadLocalMode(
386 GlobalValue::ThreadLocalMode::InitialExecTLSModel);
387 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
388 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000389
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000390 // Make sure smaller parameters are zero-extended to i64 as required by the
391 // x86_64 ABI.
392 if (TargetTriple.getArch() == Triple::x86_64) {
393 for (int i = 0; i < 3; i++) {
394 SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
395 SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko52410812017-08-10 15:00:13 +0000396 SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
397 SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000398 }
399 SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
400 }
401
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000402
Kostya Serebryany73762942014-12-16 21:24:15 +0000403 // We insert an empty inline asm after cov callbacks to avoid callback merge.
404 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
405 StringRef(""), StringRef(""),
406 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000407
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000408 SanCovTracePC = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000409 M.getOrInsertFunction(SanCovTracePCName, VoidTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000410 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000411 SanCovTracePCGuardName, VoidTy, Int32PtrTy));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000412
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000413 for (auto &F : M)
414 runOnFunction(F);
415
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000416 Function *Ctor = nullptr;
Justin Bogner41e632b2017-02-01 02:38:39 +0000417
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000418 if (FunctionGuardArray)
419 Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
420 SanCovGuardsSectionName);
421 if (Function8bitCounterArray)
422 Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
423 SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000424 if (Ctor && Options.PCTable) {
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000425 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000426 Function *InitFunction = declareSanitizerInitFunction(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000427 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000428 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000429 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000430 }
Kostya Serebryany4192b962017-09-09 05:30:13 +0000431 // We don't reference these arrays directly in any of our runtime functions,
432 // so we need to prevent them from being dead stripped.
433 if (TargetTriple.isOSBinFormatMachO())
434 appendToUsed(M, GlobalsToAppendToUsed);
Matt Morehouse0ea9a902018-06-15 20:12:58 +0000435 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000436 return true;
437}
438
Mike Aizatsky9987f432016-03-23 23:15:03 +0000439// True if block has successors and it dominates all of them.
440static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
441 if (succ_begin(BB) == succ_end(BB))
442 return false;
443
444 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
445 if (!DT->dominates(BB, SUCC))
446 return false;
447 }
448
449 return true;
450}
451
George Karpenkov018472c2017-05-24 00:29:12 +0000452// True if block has predecessors and it postdominates all of them.
453static bool isFullPostDominator(const BasicBlock *BB,
454 const PostDominatorTree *PDT) {
455 if (pred_begin(BB) == pred_end(BB))
456 return false;
457
458 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
459 if (!PDT->dominates(BB, PRED))
460 return false;
461 }
462
463 return true;
464}
465
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000466static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
467 const DominatorTree *DT,
George Karpenkov018472c2017-05-24 00:29:12 +0000468 const PostDominatorTree *PDT,
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000469 const SanitizerCoverageOptions &Options) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000470 // Don't insert coverage for unreachable blocks: we will never call
471 // __sanitizer_cov() for them, so counting them in
472 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
473 // percentage. Also, unreachable instructions frequently have no debug
474 // locations.
475 if (isa<UnreachableInst>(BB->getTerminator()))
476 return false;
477
Reid Kleckner392f0622017-03-23 23:30:41 +0000478 // Don't insert coverage into blocks without a valid insertion point
479 // (catchswitch blocks).
480 if (BB->getFirstInsertionPt() == BB->end())
481 return false;
482
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000483 if (Options.NoPrune || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000484 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000485
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000486 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
487 &F.getEntryBlock() != BB)
488 return false;
489
George Karpenkova1c53272017-05-25 01:41:46 +0000490 // Do not instrument full dominators, or full post-dominators with multiple
491 // predecessors.
492 return !isFullDominator(BB, DT)
493 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
Mike Aizatsky5971f182016-02-26 01:17:22 +0000494}
495
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000496bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000497 if (F.empty())
498 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000499 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000500 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000501 if (F.getName().startswith("__sanitizer_"))
502 return false; // Don't instrument __sanitizer_* callbacks.
Kostya Serebryanybfc83fa2017-07-31 20:00:22 +0000503 // Don't touch available_externally functions, their actual body is elewhere.
504 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
505 return false;
Reid Klecknerec803542016-11-11 19:18:45 +0000506 // Don't instrument MSVC CRT configuration helpers. They may run before normal
507 // initialization.
508 if (F.getName() == "__local_stdio_printf_options" ||
509 F.getName() == "__local_stdio_scanf_options")
510 return false;
Kostya Serebryanya2759322018-05-11 01:09:39 +0000511 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
512 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000513 // Don't instrument functions using SEH for now. Splitting basic blocks like
514 // we do for coverage breaks WinEHPrepare.
515 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
516 if (F.hasPersonalityFn() &&
517 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
518 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000519 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000520 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000521 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000522 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000523 SmallVector<Instruction *, 8> CmpTraceTargets;
524 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000525 SmallVector<BinaryOperator *, 8> DivTraceTargets;
526 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000527
Mike Aizatsky602f7922016-03-21 23:08:16 +0000528 const DominatorTree *DT =
529 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
George Karpenkov018472c2017-05-24 00:29:12 +0000530 const PostDominatorTree *PDT =
531 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
Matt Morehouse034126e2017-08-30 22:49:31 +0000532 bool IsLeafFunc = true;
Mike Aizatsky602f7922016-03-21 23:08:16 +0000533
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000534 for (auto &BB : F) {
George Karpenkov018472c2017-05-24 00:29:12 +0000535 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000536 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000537 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000538 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000539 CallSite CS(&Inst);
540 if (CS && !CS.getCalledFunction())
541 IndirCalls.push_back(&Inst);
542 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000543 if (Options.TraceCmp) {
544 if (isa<ICmpInst>(&Inst))
545 CmpTraceTargets.push_back(&Inst);
546 if (isa<SwitchInst>(&Inst))
547 SwitchTraceTargets.push_back(&Inst);
548 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000549 if (Options.TraceDiv)
550 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
551 if (BO->getOpcode() == Instruction::SDiv ||
552 BO->getOpcode() == Instruction::UDiv)
553 DivTraceTargets.push_back(BO);
554 if (Options.TraceGep)
555 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
556 GepTraceTargets.push_back(GEP);
Matt Morehouse034126e2017-08-30 22:49:31 +0000557 if (Options.StackDepth)
558 if (isa<InvokeInst>(Inst) ||
559 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
560 IsLeafFunc = false;
561 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000562 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000563
Matt Morehouse034126e2017-08-30 22:49:31 +0000564 InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000565 InjectCoverageForIndirectCalls(F, IndirCalls);
566 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000567 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000568 InjectTraceForDiv(F, DivTraceTargets);
569 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000570 return true;
571}
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000572
573GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
574 size_t NumElements, Function &F, Type *Ty, const char *Section) {
575 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
576 auto Array = new GlobalVariable(
577 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
578 Constant::getNullValue(ArrayTy), "__sancov_gen_");
Kostya Serebryanybc504552018-10-12 23:21:48 +0000579
580 if (TargetTriple.isOSBinFormatELF())
581 if (auto Comdat = GetOrCreateFunctionComdat(F, CurModuleUniqueId))
582 Array->setComdat(Comdat);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000583 Array->setSection(getSectionName(Section));
Kostya Serebryanybb6f0792017-07-31 19:49:45 +0000584 Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
585 : Ty->getPrimitiveSizeInBits() / 8);
Max Moroz4d010ca2018-10-12 13:59:31 +0000586 GlobalsToAppendToUsed.push_back(Array);
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000587 GlobalsToAppendToCompilerUsed.push_back(Array);
588 MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
589 Array->addMetadata(LLVMContext::MD_associated, *MD);
590
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000591 return Array;
592}
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000593
Justin Bogner873a0742017-08-28 23:46:11 +0000594GlobalVariable *
595SanitizerCoverageModule::CreatePCArray(Function &F,
596 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000597 size_t N = AllBlocks.size();
598 assert(N);
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000599 SmallVector<Constant *, 32> PCs;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000600 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000601 for (size_t i = 0; i < N; i++) {
602 if (&F.getEntryBlock() == AllBlocks[i]) {
603 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
604 PCs.push_back((Constant *)IRB.CreateIntToPtr(
605 ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
606 } else {
607 PCs.push_back((Constant *)IRB.CreatePointerCast(
608 BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
609 PCs.push_back((Constant *)IRB.CreateIntToPtr(
610 ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
611 }
612 }
Justin Bogner873a0742017-08-28 23:46:11 +0000613 auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
614 SanCovPCsSectionName);
615 PCArray->setInitializer(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000616 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
Justin Bogner873a0742017-08-28 23:46:11 +0000617 PCArray->setConstant(true);
Justin Bognerad96ff12017-08-25 01:24:54 +0000618
Justin Bogner873a0742017-08-28 23:46:11 +0000619 return PCArray;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000620}
621
622void SanitizerCoverageModule::CreateFunctionLocalArrays(
623 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
Max Moroz4d010ca2018-10-12 13:59:31 +0000624 if (Options.TracePCGuard)
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000625 FunctionGuardArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000626 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
Max Moroz4d010ca2018-10-12 13:59:31 +0000627
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000628 if (Options.Inline8bitCounters)
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000629 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000630 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
Max Moroz4d010ca2018-10-12 13:59:31 +0000631
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000632 if (Options.PCTable)
Justin Bogner873a0742017-08-28 23:46:11 +0000633 FunctionPCsArray = CreatePCArray(F, AllBlocks);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000634}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000635
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000636bool SanitizerCoverageModule::InjectCoverage(Function &F,
Matt Morehouse034126e2017-08-30 22:49:31 +0000637 ArrayRef<BasicBlock *> AllBlocks,
638 bool IsLeafFunc) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000639 if (AllBlocks.empty()) return false;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000640 CreateFunctionLocalArrays(F, AllBlocks);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000641 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
Matt Morehouse034126e2017-08-30 22:49:31 +0000642 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000643 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000644}
645
646// On every indirect call we call a run-time function
647// __sanitizer_cov_indir_call* with two parameters:
648// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000649// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000650// The cache is used to speed up recording the caller-callee pairs.
651// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000652// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000653void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
654 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000655 if (IndirCalls.empty())
656 return;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000657 assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000658 for (auto I : IndirCalls) {
659 IRBuilder<> IRB(I);
660 CallSite CS(I);
661 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000662 if (isa<InlineAsm>(Callee))
663 continue;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000664 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000665 }
666}
667
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000668// For every switch statement we insert a call:
669// __sanitizer_cov_trace_switch(CondValue,
670// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
671
672void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000673 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000674 for (auto I : SwitchTraceTargets) {
675 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
676 IRBuilder<> IRB(I);
677 SmallVector<Constant *, 16> Initializers;
678 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000679 if (Cond->getType()->getScalarSizeInBits() >
680 Int64Ty->getScalarSizeInBits())
681 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000682 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
683 Initializers.push_back(
684 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
685 if (Cond->getType()->getScalarSizeInBits() <
686 Int64Ty->getScalarSizeInBits())
687 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000688 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000689 Constant *C = It.getCaseValue();
690 if (C->getType()->getScalarSizeInBits() <
691 Int64Ty->getScalarSizeInBits())
692 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
693 Initializers.push_back(C);
694 }
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000695 llvm::sort(Initializers.begin() + 2, Initializers.end(),
696 [](const Constant *A, const Constant *B) {
697 return cast<ConstantInt>(A)->getLimitedValue() <
698 cast<ConstantInt>(B)->getLimitedValue();
699 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000700 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
701 GlobalVariable *GV = new GlobalVariable(
702 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
703 ConstantArray::get(ArrayOfInt64Ty, Initializers),
704 "__sancov_gen_cov_switch_values");
705 IRB.CreateCall(SanCovTraceSwitchFunction,
706 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
707 }
708 }
709}
710
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000711void SanitizerCoverageModule::InjectTraceForDiv(
712 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
713 for (auto BO : DivTraceTargets) {
714 IRBuilder<> IRB(BO);
715 Value *A1 = BO->getOperand(1);
716 if (isa<ConstantInt>(A1)) continue;
717 if (!A1->getType()->isIntegerTy())
718 continue;
719 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
720 int CallbackIdx = TypeSize == 32 ? 0 :
721 TypeSize == 64 ? 1 : -1;
722 if (CallbackIdx < 0) continue;
723 auto Ty = Type::getIntNTy(*C, TypeSize);
724 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
725 {IRB.CreateIntCast(A1, Ty, true)});
726 }
727}
728
729void SanitizerCoverageModule::InjectTraceForGep(
730 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
731 for (auto GEP : GepTraceTargets) {
732 IRBuilder<> IRB(GEP);
733 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000734 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000735 IRB.CreateCall(SanCovTraceGepFunction,
736 {IRB.CreateIntCast(*I, IntptrTy, true)});
737 }
738}
739
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000740void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000741 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000742 for (auto I : CmpTraceTargets) {
743 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
744 IRBuilder<> IRB(ICMP);
745 Value *A0 = ICMP->getOperand(0);
746 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000747 if (!A0->getType()->isIntegerTy())
748 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000749 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000750 int CallbackIdx = TypeSize == 8 ? 0 :
751 TypeSize == 16 ? 1 :
752 TypeSize == 32 ? 2 :
753 TypeSize == 64 ? 3 : -1;
754 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000755 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Alexander Potapenko52410812017-08-10 15:00:13 +0000756 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
757 bool FirstIsConst = isa<ConstantInt>(A0);
758 bool SecondIsConst = isa<ConstantInt>(A1);
759 // If both are const, then we don't need such a comparison.
760 if (FirstIsConst && SecondIsConst) continue;
761 // If only one is const, then make it the first callback argument.
762 if (FirstIsConst || SecondIsConst) {
763 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
Justin Bognerbe757de2017-08-28 23:38:12 +0000764 if (SecondIsConst)
Alexander Potapenko52410812017-08-10 15:00:13 +0000765 std::swap(A0, A1);
766 }
767
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000768 auto Ty = Type::getIntNTy(*C, TypeSize);
Justin Bognerbe757de2017-08-28 23:38:12 +0000769 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
Alexander Potapenko52410812017-08-10 15:00:13 +0000770 IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000771 }
772 }
773}
774
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000775void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Matt Morehouse034126e2017-08-30 22:49:31 +0000776 size_t Idx,
777 bool IsLeafFunc) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000778 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000779 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000780 DebugLoc EntryLoc;
781 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000782 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000783 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000784 // Keep static allocas and llvm.localescape calls in the entry block. Even
785 // if we aren't splitting the block, it's nice for allocas to be before
786 // calls.
787 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000788 } else {
789 EntryLoc = IP->getDebugLoc();
790 }
791
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000792 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000793 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000794 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000795 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
796 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000797 }
798 if (Options.TracePCGuard) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000799 auto GuardPtr = IRB.CreateIntToPtr(
800 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
801 ConstantInt::get(IntptrTy, Idx * 4)),
802 Int32PtrTy);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000803 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
804 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000805 }
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000806 if (Options.Inline8bitCounters) {
807 auto CounterPtr = IRB.CreateGEP(
808 Function8bitCounterArray,
809 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
810 auto Load = IRB.CreateLoad(CounterPtr);
811 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
812 auto Store = IRB.CreateStore(Inc, CounterPtr);
813 SetNoSanitizeMetadata(Load);
814 SetNoSanitizeMetadata(Store);
815 }
Matt Morehouse034126e2017-08-30 22:49:31 +0000816 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000817 // Check stack depth. If it's the deepest so far, record it.
818 Function *GetFrameAddr =
819 Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
820 auto FrameAddrPtr =
821 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
822 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000823 auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000824 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
825 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
826 IRBuilder<> ThenIRB(ThenTerm);
Matt Morehouse034126e2017-08-30 22:49:31 +0000827 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
828 SetNoSanitizeMetadata(LowestStack);
829 SetNoSanitizeMetadata(Store);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000830 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000831}
832
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000833std::string
834SanitizerCoverageModule::getSectionName(const std::string &Section) const {
Matt Morehouse7e042bb2018-08-30 15:54:44 +0000835 if (TargetTriple.getObjectFormat() == Triple::COFF) {
836 if (Section == SanCovCountersSectionName)
837 return ".SCOV$CM";
838 if (Section == SanCovPCsSectionName)
839 return ".SCOVP$M";
840 return ".SCOV$GM"; // For SanCovGuardsSectionName.
841 }
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000842 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000843 return "__DATA,__" + Section;
844 return "__" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000845}
846
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000847std::string
848SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000849 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000850 return "\1section$start$__DATA$__" + Section;
851 return "__start___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000852}
853
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000854std::string
855SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000856 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000857 return "\1section$end$__DATA$__" + Section;
858 return "__stop___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000859}
860
861
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000862char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000863INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000864 "SanitizerCoverage: TODO."
865 "ModulePass",
866 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000867INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
George Karpenkov018472c2017-05-24 00:29:12 +0000868INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Mike Aizatsky90562842016-02-27 05:50:40 +0000869INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000870 "SanitizerCoverage: TODO."
871 "ModulePass",
872 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000873ModulePass *llvm::createSanitizerCoverageModulePass(
874 const SanitizerCoverageOptions &Options) {
875 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000876}