blob: 0ba8d5765e8c2110550df63d22eddc5995dc9e82 [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);
Jonathan Metzmane159a0d2019-01-14 21:02:02 +0000267 if (!TargetTriple.isOSBinFormatCOFF())
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000268 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
Jonathan Metzmane159a0d2019-01-14 21:02:02 +0000296 if (TargetTriple.isOSBinFormatCOFF()) {
Jonathan Metzman0b94e882018-10-12 18:11:47 +0000297 // 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
Jonathan Metzmane159a0d2019-01-14 21:02:02 +0000300 // this, give the constructors weak ODR linkage and ensure the linker knows
301 // to include the sancov constructor. This way the linker can deduplicate
302 // the constructors but always leave one copy.
Jonathan Metzman0b94e882018-10-12 18:11:47 +0000303 CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
Jonathan Metzmane159a0d2019-01-14 21:02:02 +0000304 appendToUsed(M, CtorFunc);
Jonathan Metzman0b94e882018-10-12 18:11:47 +0000305 }
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000306 return CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000307}
308
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000309bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000310 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
311 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000312 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000313 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000314 CurModule = &M;
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000315 CurModuleUniqueId = getUniqueModuleId(CurModule);
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000316 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000317 FunctionGuardArray = nullptr;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000318 Function8bitCounterArray = nullptr;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000319 FunctionPCsArray = nullptr;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000320 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000321 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000322 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000323 IRBuilder<> IRB(*C);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000324 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000325 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000326 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000327 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000328 Int32Ty = IRB.getInt32Ty();
Alexander Potapenko52410812017-08-10 15:00:13 +0000329 Int16Ty = IRB.getInt16Ty();
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000330 Int8Ty = IRB.getInt8Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000331
Mike Aizatsky759aca02016-03-18 23:29:29 +0000332 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000333 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000334 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000335 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000336 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000337 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
338 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000339 IRB.getInt16Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000340 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
341 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000342 IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000343 SanCovTraceCmpFunction[3] =
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000344 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000345 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000346
Alexander Potapenko52410812017-08-10 15:00:13 +0000347 SanCovTraceConstCmpFunction[0] =
348 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
349 SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
350 SanCovTraceConstCmpFunction[1] =
351 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
352 SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
353 SanCovTraceConstCmpFunction[2] =
354 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
355 SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
356 SanCovTraceConstCmpFunction[3] =
357 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
358 SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
359
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000360 SanCovTraceDivFunction[0] =
361 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000362 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000363 SanCovTraceDivFunction[1] =
364 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000365 SanCovTraceDiv8, VoidTy, Int64Ty));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000366 SanCovTraceGepFunction =
367 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000368 SanCovTraceGep, VoidTy, IntptrTy));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000369 SanCovTraceSwitchFunction =
370 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000371 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000372
373 Constant *SanCovLowestStackConstant =
374 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000375 SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
376 SanCovLowestStack->setThreadLocalMode(
377 GlobalValue::ThreadLocalMode::InitialExecTLSModel);
378 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
379 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000380
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000381 // Make sure smaller parameters are zero-extended to i64 as required by the
382 // x86_64 ABI.
383 if (TargetTriple.getArch() == Triple::x86_64) {
384 for (int i = 0; i < 3; i++) {
385 SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
386 SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko52410812017-08-10 15:00:13 +0000387 SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
388 SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000389 }
390 SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
391 }
392
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000393
Kostya Serebryany73762942014-12-16 21:24:15 +0000394 // We insert an empty inline asm after cov callbacks to avoid callback merge.
395 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
396 StringRef(""), StringRef(""),
397 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000398
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000399 SanCovTracePC = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000400 M.getOrInsertFunction(SanCovTracePCName, VoidTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000401 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000402 SanCovTracePCGuardName, VoidTy, Int32PtrTy));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000403
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000404 for (auto &F : M)
405 runOnFunction(F);
406
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000407 Function *Ctor = nullptr;
Justin Bogner41e632b2017-02-01 02:38:39 +0000408
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000409 if (FunctionGuardArray)
410 Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
411 SanCovGuardsSectionName);
412 if (Function8bitCounterArray)
413 Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
414 SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000415 if (Ctor && Options.PCTable) {
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000416 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000417 Function *InitFunction = declareSanitizerInitFunction(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000418 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000419 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000420 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000421 }
Kostya Serebryany4192b962017-09-09 05:30:13 +0000422 // We don't reference these arrays directly in any of our runtime functions,
423 // so we need to prevent them from being dead stripped.
424 if (TargetTriple.isOSBinFormatMachO())
425 appendToUsed(M, GlobalsToAppendToUsed);
Matt Morehouse0ea9a902018-06-15 20:12:58 +0000426 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000427 return true;
428}
429
Mike Aizatsky9987f432016-03-23 23:15:03 +0000430// True if block has successors and it dominates all of them.
431static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
432 if (succ_begin(BB) == succ_end(BB))
433 return false;
434
435 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
436 if (!DT->dominates(BB, SUCC))
437 return false;
438 }
439
440 return true;
441}
442
George Karpenkov018472c2017-05-24 00:29:12 +0000443// True if block has predecessors and it postdominates all of them.
444static bool isFullPostDominator(const BasicBlock *BB,
445 const PostDominatorTree *PDT) {
446 if (pred_begin(BB) == pred_end(BB))
447 return false;
448
449 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
450 if (!PDT->dominates(BB, PRED))
451 return false;
452 }
453
454 return true;
455}
456
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000457static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
458 const DominatorTree *DT,
George Karpenkov018472c2017-05-24 00:29:12 +0000459 const PostDominatorTree *PDT,
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000460 const SanitizerCoverageOptions &Options) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000461 // Don't insert coverage for unreachable blocks: we will never call
462 // __sanitizer_cov() for them, so counting them in
463 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
464 // percentage. Also, unreachable instructions frequently have no debug
465 // locations.
466 if (isa<UnreachableInst>(BB->getTerminator()))
467 return false;
468
Reid Kleckner392f0622017-03-23 23:30:41 +0000469 // Don't insert coverage into blocks without a valid insertion point
470 // (catchswitch blocks).
471 if (BB->getFirstInsertionPt() == BB->end())
472 return false;
473
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000474 if (Options.NoPrune || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000475 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000476
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000477 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
478 &F.getEntryBlock() != BB)
479 return false;
480
George Karpenkova1c53272017-05-25 01:41:46 +0000481 // Do not instrument full dominators, or full post-dominators with multiple
482 // predecessors.
483 return !isFullDominator(BB, DT)
484 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
Mike Aizatsky5971f182016-02-26 01:17:22 +0000485}
486
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000487bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000488 if (F.empty())
489 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000490 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000491 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000492 if (F.getName().startswith("__sanitizer_"))
493 return false; // Don't instrument __sanitizer_* callbacks.
Kostya Serebryanybfc83fa2017-07-31 20:00:22 +0000494 // Don't touch available_externally functions, their actual body is elewhere.
495 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
496 return false;
Reid Klecknerec803542016-11-11 19:18:45 +0000497 // Don't instrument MSVC CRT configuration helpers. They may run before normal
498 // initialization.
499 if (F.getName() == "__local_stdio_printf_options" ||
500 F.getName() == "__local_stdio_scanf_options")
501 return false;
Kostya Serebryanya2759322018-05-11 01:09:39 +0000502 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
503 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000504 // Don't instrument functions using SEH for now. Splitting basic blocks like
505 // we do for coverage breaks WinEHPrepare.
506 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
507 if (F.hasPersonalityFn() &&
508 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
509 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000510 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000511 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000512 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000513 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000514 SmallVector<Instruction *, 8> CmpTraceTargets;
515 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000516 SmallVector<BinaryOperator *, 8> DivTraceTargets;
517 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000518
Mike Aizatsky602f7922016-03-21 23:08:16 +0000519 const DominatorTree *DT =
520 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
George Karpenkov018472c2017-05-24 00:29:12 +0000521 const PostDominatorTree *PDT =
522 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
Matt Morehouse034126e2017-08-30 22:49:31 +0000523 bool IsLeafFunc = true;
Mike Aizatsky602f7922016-03-21 23:08:16 +0000524
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000525 for (auto &BB : F) {
George Karpenkov018472c2017-05-24 00:29:12 +0000526 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000527 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000528 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000529 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000530 CallSite CS(&Inst);
531 if (CS && !CS.getCalledFunction())
532 IndirCalls.push_back(&Inst);
533 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000534 if (Options.TraceCmp) {
535 if (isa<ICmpInst>(&Inst))
536 CmpTraceTargets.push_back(&Inst);
537 if (isa<SwitchInst>(&Inst))
538 SwitchTraceTargets.push_back(&Inst);
539 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000540 if (Options.TraceDiv)
541 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
542 if (BO->getOpcode() == Instruction::SDiv ||
543 BO->getOpcode() == Instruction::UDiv)
544 DivTraceTargets.push_back(BO);
545 if (Options.TraceGep)
546 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
547 GepTraceTargets.push_back(GEP);
Matt Morehouse034126e2017-08-30 22:49:31 +0000548 if (Options.StackDepth)
549 if (isa<InvokeInst>(Inst) ||
550 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
551 IsLeafFunc = false;
552 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000553 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000554
Matt Morehouse034126e2017-08-30 22:49:31 +0000555 InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000556 InjectCoverageForIndirectCalls(F, IndirCalls);
557 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000558 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000559 InjectTraceForDiv(F, DivTraceTargets);
560 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000561 return true;
562}
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000563
564GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
565 size_t NumElements, Function &F, Type *Ty, const char *Section) {
566 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
567 auto Array = new GlobalVariable(
568 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
569 Constant::getNullValue(ArrayTy), "__sancov_gen_");
Kostya Serebryanybc504552018-10-12 23:21:48 +0000570
Matt Morehouse19ff35c2019-01-15 21:21:01 +0000571 if (TargetTriple.supportsCOMDAT() && !F.isInterposable())
Reid Klecknerb41b3722018-11-08 00:57:33 +0000572 if (auto Comdat =
573 GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId))
Kostya Serebryanybc504552018-10-12 23:21:48 +0000574 Array->setComdat(Comdat);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000575 Array->setSection(getSectionName(Section));
Kostya Serebryanybb6f0792017-07-31 19:49:45 +0000576 Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
577 : Ty->getPrimitiveSizeInBits() / 8);
Max Moroz4d010ca2018-10-12 13:59:31 +0000578 GlobalsToAppendToUsed.push_back(Array);
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000579 GlobalsToAppendToCompilerUsed.push_back(Array);
580 MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
581 Array->addMetadata(LLVMContext::MD_associated, *MD);
582
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000583 return Array;
584}
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000585
Justin Bogner873a0742017-08-28 23:46:11 +0000586GlobalVariable *
587SanitizerCoverageModule::CreatePCArray(Function &F,
588 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000589 size_t N = AllBlocks.size();
590 assert(N);
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000591 SmallVector<Constant *, 32> PCs;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000592 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000593 for (size_t i = 0; i < N; i++) {
594 if (&F.getEntryBlock() == AllBlocks[i]) {
595 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
596 PCs.push_back((Constant *)IRB.CreateIntToPtr(
597 ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
598 } else {
599 PCs.push_back((Constant *)IRB.CreatePointerCast(
600 BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
601 PCs.push_back((Constant *)IRB.CreateIntToPtr(
602 ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
603 }
604 }
Justin Bogner873a0742017-08-28 23:46:11 +0000605 auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
606 SanCovPCsSectionName);
607 PCArray->setInitializer(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000608 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
Justin Bogner873a0742017-08-28 23:46:11 +0000609 PCArray->setConstant(true);
Justin Bognerad96ff12017-08-25 01:24:54 +0000610
Justin Bogner873a0742017-08-28 23:46:11 +0000611 return PCArray;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000612}
613
614void SanitizerCoverageModule::CreateFunctionLocalArrays(
615 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
Max Moroz4d010ca2018-10-12 13:59:31 +0000616 if (Options.TracePCGuard)
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000617 FunctionGuardArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000618 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
Max Moroz4d010ca2018-10-12 13:59:31 +0000619
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000620 if (Options.Inline8bitCounters)
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000621 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000622 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
Max Moroz4d010ca2018-10-12 13:59:31 +0000623
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000624 if (Options.PCTable)
Justin Bogner873a0742017-08-28 23:46:11 +0000625 FunctionPCsArray = CreatePCArray(F, AllBlocks);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000626}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000627
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000628bool SanitizerCoverageModule::InjectCoverage(Function &F,
Matt Morehouse034126e2017-08-30 22:49:31 +0000629 ArrayRef<BasicBlock *> AllBlocks,
630 bool IsLeafFunc) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000631 if (AllBlocks.empty()) return false;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000632 CreateFunctionLocalArrays(F, AllBlocks);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000633 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
Matt Morehouse034126e2017-08-30 22:49:31 +0000634 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000635 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000636}
637
638// On every indirect call we call a run-time function
639// __sanitizer_cov_indir_call* with two parameters:
640// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000641// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000642// The cache is used to speed up recording the caller-callee pairs.
643// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000644// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000645void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
646 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000647 if (IndirCalls.empty())
648 return;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000649 assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000650 for (auto I : IndirCalls) {
651 IRBuilder<> IRB(I);
652 CallSite CS(I);
653 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000654 if (isa<InlineAsm>(Callee))
655 continue;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000656 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000657 }
658}
659
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000660// For every switch statement we insert a call:
661// __sanitizer_cov_trace_switch(CondValue,
662// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
663
664void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000665 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000666 for (auto I : SwitchTraceTargets) {
667 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
668 IRBuilder<> IRB(I);
669 SmallVector<Constant *, 16> Initializers;
670 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000671 if (Cond->getType()->getScalarSizeInBits() >
672 Int64Ty->getScalarSizeInBits())
673 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000674 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
675 Initializers.push_back(
676 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
677 if (Cond->getType()->getScalarSizeInBits() <
678 Int64Ty->getScalarSizeInBits())
679 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000680 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000681 Constant *C = It.getCaseValue();
682 if (C->getType()->getScalarSizeInBits() <
683 Int64Ty->getScalarSizeInBits())
684 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
685 Initializers.push_back(C);
686 }
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000687 llvm::sort(Initializers.begin() + 2, Initializers.end(),
688 [](const Constant *A, const Constant *B) {
689 return cast<ConstantInt>(A)->getLimitedValue() <
690 cast<ConstantInt>(B)->getLimitedValue();
691 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000692 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
693 GlobalVariable *GV = new GlobalVariable(
694 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
695 ConstantArray::get(ArrayOfInt64Ty, Initializers),
696 "__sancov_gen_cov_switch_values");
697 IRB.CreateCall(SanCovTraceSwitchFunction,
698 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
699 }
700 }
701}
702
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000703void SanitizerCoverageModule::InjectTraceForDiv(
704 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
705 for (auto BO : DivTraceTargets) {
706 IRBuilder<> IRB(BO);
707 Value *A1 = BO->getOperand(1);
708 if (isa<ConstantInt>(A1)) continue;
709 if (!A1->getType()->isIntegerTy())
710 continue;
711 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
712 int CallbackIdx = TypeSize == 32 ? 0 :
713 TypeSize == 64 ? 1 : -1;
714 if (CallbackIdx < 0) continue;
715 auto Ty = Type::getIntNTy(*C, TypeSize);
716 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
717 {IRB.CreateIntCast(A1, Ty, true)});
718 }
719}
720
721void SanitizerCoverageModule::InjectTraceForGep(
722 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
723 for (auto GEP : GepTraceTargets) {
724 IRBuilder<> IRB(GEP);
725 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000726 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000727 IRB.CreateCall(SanCovTraceGepFunction,
728 {IRB.CreateIntCast(*I, IntptrTy, true)});
729 }
730}
731
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000732void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000733 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000734 for (auto I : CmpTraceTargets) {
735 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
736 IRBuilder<> IRB(ICMP);
737 Value *A0 = ICMP->getOperand(0);
738 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000739 if (!A0->getType()->isIntegerTy())
740 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000741 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000742 int CallbackIdx = TypeSize == 8 ? 0 :
743 TypeSize == 16 ? 1 :
744 TypeSize == 32 ? 2 :
745 TypeSize == 64 ? 3 : -1;
746 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000747 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Alexander Potapenko52410812017-08-10 15:00:13 +0000748 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
749 bool FirstIsConst = isa<ConstantInt>(A0);
750 bool SecondIsConst = isa<ConstantInt>(A1);
751 // If both are const, then we don't need such a comparison.
752 if (FirstIsConst && SecondIsConst) continue;
753 // If only one is const, then make it the first callback argument.
754 if (FirstIsConst || SecondIsConst) {
755 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
Justin Bognerbe757de2017-08-28 23:38:12 +0000756 if (SecondIsConst)
Alexander Potapenko52410812017-08-10 15:00:13 +0000757 std::swap(A0, A1);
758 }
759
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000760 auto Ty = Type::getIntNTy(*C, TypeSize);
Justin Bognerbe757de2017-08-28 23:38:12 +0000761 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
Alexander Potapenko52410812017-08-10 15:00:13 +0000762 IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000763 }
764 }
765}
766
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000767void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Matt Morehouse034126e2017-08-30 22:49:31 +0000768 size_t Idx,
769 bool IsLeafFunc) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000770 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000771 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000772 DebugLoc EntryLoc;
773 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000774 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000775 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000776 // Keep static allocas and llvm.localescape calls in the entry block. Even
777 // if we aren't splitting the block, it's nice for allocas to be before
778 // calls.
779 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000780 } else {
781 EntryLoc = IP->getDebugLoc();
782 }
783
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000784 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000785 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000786 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000787 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
788 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000789 }
790 if (Options.TracePCGuard) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000791 auto GuardPtr = IRB.CreateIntToPtr(
792 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
793 ConstantInt::get(IntptrTy, Idx * 4)),
794 Int32PtrTy);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000795 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
796 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000797 }
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000798 if (Options.Inline8bitCounters) {
799 auto CounterPtr = IRB.CreateGEP(
800 Function8bitCounterArray,
801 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
802 auto Load = IRB.CreateLoad(CounterPtr);
803 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
804 auto Store = IRB.CreateStore(Inc, CounterPtr);
805 SetNoSanitizeMetadata(Load);
806 SetNoSanitizeMetadata(Store);
807 }
Matt Morehouse034126e2017-08-30 22:49:31 +0000808 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000809 // Check stack depth. If it's the deepest so far, record it.
810 Function *GetFrameAddr =
811 Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
812 auto FrameAddrPtr =
813 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
814 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000815 auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000816 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
817 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
818 IRBuilder<> ThenIRB(ThenTerm);
Matt Morehouse034126e2017-08-30 22:49:31 +0000819 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
820 SetNoSanitizeMetadata(LowestStack);
821 SetNoSanitizeMetadata(Store);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000822 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000823}
824
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000825std::string
826SanitizerCoverageModule::getSectionName(const std::string &Section) const {
Jonathan Metzmane159a0d2019-01-14 21:02:02 +0000827 if (TargetTriple.isOSBinFormatCOFF()) {
Matt Morehouse7e042bb2018-08-30 15:54:44 +0000828 if (Section == SanCovCountersSectionName)
829 return ".SCOV$CM";
830 if (Section == SanCovPCsSectionName)
831 return ".SCOVP$M";
832 return ".SCOV$GM"; // For SanCovGuardsSectionName.
833 }
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000834 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000835 return "__DATA,__" + Section;
836 return "__" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000837}
838
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000839std::string
840SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000841 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000842 return "\1section$start$__DATA$__" + Section;
843 return "__start___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000844}
845
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000846std::string
847SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000848 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000849 return "\1section$end$__DATA$__" + Section;
850 return "__stop___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000851}
852
853
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000854char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000855INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000856 "SanitizerCoverage: TODO."
857 "ModulePass",
858 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000859INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
George Karpenkov018472c2017-05-24 00:29:12 +0000860INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Mike Aizatsky90562842016-02-27 05:50:40 +0000861INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000862 "SanitizerCoverage: TODO."
863 "ModulePass",
864 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000865ModulePass *llvm::createSanitizerCoverageModulePass(
866 const SanitizerCoverageOptions &Options) {
867 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000868}