blob: e0c1365ce5eb979fb3ee020c7f7449b7db5a2acc [file] [log] [blame]
Kostya Serebryany29a18dc2014-11-11 22:14:37 +00001//===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Kostya Serebryany29a18dc2014-11-11 22:14:37 +00006//
7//===----------------------------------------------------------------------===//
8//
Kostya Serebryany53b34c82017-05-31 18:27:33 +00009// Coverage instrumentation done on LLVM IR level, works with Sanitizers.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000010//
11//===----------------------------------------------------------------------===//
12
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000013#include "llvm/ADT/ArrayRef.h"
14#include "llvm/ADT/SmallVector.h"
David Majnemer70497c62015-12-02 23:06:39 +000015#include "llvm/Analysis/EHPersonalities.h"
George Karpenkov018472c2017-05-24 00:29:12 +000016#include "llvm/Analysis/PostDominators.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000017#include "llvm/IR/CFG.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000018#include "llvm/IR/CallSite.h"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000019#include "llvm/IR/Constant.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000020#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000021#include "llvm/IR/DebugInfo.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000022#include "llvm/IR/Dominators.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000023#include "llvm/IR/Function.h"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000024#include "llvm/IR/GlobalVariable.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000025#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000026#include "llvm/IR/InlineAsm.h"
Matt Morehouse034126e2017-08-30 22:49:31 +000027#include "llvm/IR/IntrinsicInst.h"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000028#include "llvm/IR/Intrinsics.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000029#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/MDBuilder.h"
Jonathan Metzman0b94e882018-10-12 18:11:47 +000031#include "llvm/IR/Mangler.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000032#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/raw_ostream.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000037#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
39#include "llvm/Transforms/Utils/ModuleUtils.h"
40
41using namespace llvm;
42
43#define DEBUG_TYPE "sancov"
44
Mike Aizatsky759aca02016-03-18 23:29:29 +000045static const char *const SanCovTracePCIndirName =
46 "__sanitizer_cov_trace_pc_indir";
Mike Aizatsky759aca02016-03-18 23:29:29 +000047static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
Kostya Serebryany524c3f32016-08-18 01:25:28 +000048static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
49static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
50static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
51static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
Justin Bognerbe757de2017-08-28 23:38:12 +000052static const char *const SanCovTraceConstCmp1 =
Alexander Potapenko52410812017-08-10 15:00:13 +000053 "__sanitizer_cov_trace_const_cmp1";
Justin Bognerbe757de2017-08-28 23:38:12 +000054static const char *const SanCovTraceConstCmp2 =
Alexander Potapenko52410812017-08-10 15:00:13 +000055 "__sanitizer_cov_trace_const_cmp2";
Justin Bognerbe757de2017-08-28 23:38:12 +000056static const char *const SanCovTraceConstCmp4 =
Alexander Potapenko52410812017-08-10 15:00:13 +000057 "__sanitizer_cov_trace_const_cmp4";
Justin Bognerbe757de2017-08-28 23:38:12 +000058static const char *const SanCovTraceConstCmp8 =
Alexander Potapenko52410812017-08-10 15:00:13 +000059 "__sanitizer_cov_trace_const_cmp8";
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000060static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
61static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
62static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
Mike Aizatsky759aca02016-03-18 23:29:29 +000063static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
64static const char *const SanCovModuleCtorName = "sancov.module_ctor";
65static const uint64_t SanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000066
Kostya Serebryanyda718e52016-09-14 01:39:35 +000067static const char *const SanCovTracePCGuardName =
68 "__sanitizer_cov_trace_pc_guard";
69static const char *const SanCovTracePCGuardInitName =
70 "__sanitizer_cov_trace_pc_guard_init";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000071static const char *const SanCov8bitCountersInitName =
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000072 "__sanitizer_cov_8bit_counters_init";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000073static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
Kostya Serebryanyda718e52016-09-14 01:39:35 +000074
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000075static const char *const SanCovGuardsSectionName = "sancov_guards";
George Karpenkov406c1132017-06-14 23:40:25 +000076static const char *const SanCovCountersSectionName = "sancov_cntrs";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000077static const char *const SanCovPCsSectionName = "sancov_pcs";
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000078
Matt Morehouse5c7fc762017-08-18 18:43:30 +000079static const char *const SanCovLowestStackName = "__sancov_lowest_stack";
Matt Morehouse5c7fc762017-08-18 18:43:30 +000080
Mike Aizatsky759aca02016-03-18 23:29:29 +000081static cl::opt<int> ClCoverageLevel(
82 "sanitizer-coverage-level",
83 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +000084 "3: all blocks and critical edges"),
Mike Aizatsky759aca02016-03-18 23:29:29 +000085 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000086
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000087static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
88 cl::desc("Experimental pc tracing"), cl::Hidden,
89 cl::init(false));
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000090
Kostya Serebryanyda718e52016-09-14 01:39:35 +000091static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
92 cl::desc("pc tracing with a guard"),
93 cl::Hidden, cl::init(false));
94
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000095// If true, we create a global variable that contains PCs of all instrumented
96// BBs, put this global into a named section, and pass this section's bounds
97// to __sanitizer_cov_pcs_init.
98// This way the coverage instrumentation does not need to acquire the PCs
99// at run-time. Works with trace-pc-guard and inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000100static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000101 cl::desc("create a static PC table"),
102 cl::Hidden, cl::init(false));
103
104static cl::opt<bool>
105 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
106 cl::desc("increments 8-bit counter for every edge"),
107 cl::Hidden, cl::init(false));
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000108
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000109static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000110 ClCMPTracing("sanitizer-coverage-trace-compares",
111 cl::desc("Tracing of CMP and similar instructions"),
112 cl::Hidden, cl::init(false));
113
114static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
115 cl::desc("Tracing of DIV instructions"),
116 cl::Hidden, cl::init(false));
117
118static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
119 cl::desc("Tracing of GEP instructions"),
120 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000121
Mike Aizatsky70ea4532016-04-06 23:24:37 +0000122static cl::opt<bool>
123 ClPruneBlocks("sanitizer-coverage-prune-blocks",
124 cl::desc("Reduce the number of instrumented blocks"),
125 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000126
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000127static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
128 cl::desc("max stack depth tracing"),
129 cl::Hidden, cl::init(false));
130
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000131namespace {
132
Alexey Samsonov3514f272015-05-07 01:00:31 +0000133SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
134 SanitizerCoverageOptions Res;
135 switch (LegacyCoverageLevel) {
136 case 0:
137 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
138 break;
139 case 1:
140 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
141 break;
142 case 2:
143 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
144 break;
145 case 3:
146 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
147 break;
148 case 4:
149 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
150 Res.IndirectCalls = true;
151 break;
152 }
153 return Res;
154}
155
156SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
157 // Sets CoverageType and IndirectCalls.
158 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
159 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
160 Options.IndirectCalls |= CLOpts.IndirectCalls;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000161 Options.TraceCmp |= ClCMPTracing;
162 Options.TraceDiv |= ClDIVTracing;
163 Options.TraceGep |= ClGEPTracing;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000164 Options.TracePC |= ClTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000165 Options.TracePCGuard |= ClTracePCGuard;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000166 Options.Inline8bitCounters |= ClInline8bitCounters;
Kostya Serebryany063b6522017-07-28 00:09:29 +0000167 Options.PCTable |= ClCreatePCTable;
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000168 Options.NoPrune |= !ClPruneBlocks;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000169 Options.StackDepth |= ClStackDepth;
170 if (!Options.TracePCGuard && !Options.TracePC &&
171 !Options.Inline8bitCounters && !Options.StackDepth)
172 Options.TracePCGuard = true; // TracePCGuard is default.
Alexey Samsonov3514f272015-05-07 01:00:31 +0000173 return Options;
174}
175
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000176class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000177public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000178 SanitizerCoverageModule(
179 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000180 : ModulePass(ID), Options(OverrideFromCL(Options)) {
181 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
182 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000183 bool runOnModule(Module &M) override;
184 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000185 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000186 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000187
Chandler Carruth30061152016-03-18 22:43:42 +0000188 void getAnalysisUsage(AnalysisUsage &AU) const override {
189 AU.addRequired<DominatorTreeWrapperPass>();
George Karpenkov018472c2017-05-24 00:29:12 +0000190 AU.addRequired<PostDominatorTreeWrapperPass>();
Chandler Carruth30061152016-03-18 22:43:42 +0000191 }
192
193private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000194 void InjectCoverageForIndirectCalls(Function &F,
195 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000196 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000197 void InjectTraceForDiv(Function &F,
198 ArrayRef<BinaryOperator *> DivTraceTargets);
199 void InjectTraceForGep(Function &F,
200 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000201 void InjectTraceForSwitch(Function &F,
202 ArrayRef<Instruction *> SwitchTraceTargets);
Matt Morehouse034126e2017-08-30 22:49:31 +0000203 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
204 bool IsLeafFunc = true);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000205 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
206 Function &F, Type *Ty,
207 const char *Section);
Justin Bogner873a0742017-08-28 23:46:11 +0000208 GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000209 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Matt Morehouse034126e2017-08-30 22:49:31 +0000210 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
211 bool IsLeafFunc = true);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000212 Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
213 Type *Ty, const char *Section);
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000214 std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
215 Type *Ty);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000216
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000217 void SetNoSanitizeMetadata(Instruction *I) {
218 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
219 MDNode::get(*C, None));
220 }
221
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000222 std::string getSectionName(const std::string &Section) const;
223 std::string getSectionStart(const std::string &Section) const;
224 std::string getSectionEnd(const std::string &Section) const;
James Y Knightf47d6b32019-01-31 20:35:56 +0000225 FunctionCallee SanCovTracePCIndir;
226 FunctionCallee SanCovTracePC, SanCovTracePCGuard;
227 FunctionCallee SanCovTraceCmpFunction[4];
228 FunctionCallee SanCovTraceConstCmpFunction[4];
229 FunctionCallee SanCovTraceDivFunction[2];
230 FunctionCallee SanCovTraceGepFunction;
231 FunctionCallee SanCovTraceSwitchFunction;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000232 GlobalVariable *SanCovLowestStack;
Kostya Serebryany73762942014-12-16 21:24:15 +0000233 InlineAsm *EmptyAsm;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000234 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
Alexander Potapenko52410812017-08-10 15:00:13 +0000235 *Int16Ty, *Int8Ty, *Int8PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000236 Module *CurModule;
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000237 std::string CurModuleUniqueId;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000238 Triple TargetTriple;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000239 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000240 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000241
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000242 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000243 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000244 GlobalVariable *FunctionPCsArray; // for pc-table.
Kostya Serebryany4192b962017-09-09 05:30:13 +0000245 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
Matt Morehouse0ea9a902018-06-15 20:12:58 +0000246 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000247
Alexey Samsonov3514f272015-05-07 01:00:31 +0000248 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000249};
250
Mike Aizatsky759aca02016-03-18 23:29:29 +0000251} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000252
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000253std::pair<Value *, Value *>
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000254SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
255 Type *Ty) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000256 GlobalVariable *SecStart =
257 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
258 getSectionStart(Section));
259 SecStart->setVisibility(GlobalValue::HiddenVisibility);
260 GlobalVariable *SecEnd =
261 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
262 nullptr, getSectionEnd(Section));
263 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000264 IRBuilder<> IRB(M.getContext());
265 Value *SecEndPtr = IRB.CreatePointerCast(SecEnd, Ty);
Jonathan Metzmane159a0d2019-01-14 21:02:02 +0000266 if (!TargetTriple.isOSBinFormatCOFF())
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000267 return std::make_pair(IRB.CreatePointerCast(SecStart, Ty), SecEndPtr);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000268
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000269 // Account for the fact that on windows-msvc __start_* symbols actually
270 // point to a uint64_t before the start of the array.
271 auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
272 auto GEP = IRB.CreateGEP(SecStartI8Ptr,
273 ConstantInt::get(IntptrTy, sizeof(uint64_t)));
274 return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEndPtr);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000275}
276
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000277Function *SanitizerCoverageModule::CreateInitCallsForSections(
278 Module &M, const char *InitFunctionName, Type *Ty,
279 const char *Section) {
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000280 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
281 auto SecStart = SecStartEnd.first;
282 auto SecEnd = SecStartEnd.second;
283 Function *CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000284 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000285 M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd});
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000286
287 if (TargetTriple.supportsCOMDAT()) {
288 // Use comdat to dedup CtorFunc.
289 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
290 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
291 } else {
292 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
293 }
Jonathan Metzman0b94e882018-10-12 18:11:47 +0000294
Jonathan Metzmane159a0d2019-01-14 21:02:02 +0000295 if (TargetTriple.isOSBinFormatCOFF()) {
Jonathan Metzman0b94e882018-10-12 18:11:47 +0000296 // In COFF files, if the contructors are set as COMDAT (they are because
297 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
298 // functions and data) is used, the constructors get stripped. To prevent
Jonathan Metzmane159a0d2019-01-14 21:02:02 +0000299 // this, give the constructors weak ODR linkage and ensure the linker knows
300 // to include the sancov constructor. This way the linker can deduplicate
301 // the constructors but always leave one copy.
Jonathan Metzman0b94e882018-10-12 18:11:47 +0000302 CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
Jonathan Metzmane159a0d2019-01-14 21:02:02 +0000303 appendToUsed(M, CtorFunc);
Jonathan Metzman0b94e882018-10-12 18:11:47 +0000304 }
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000305 return CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000306}
307
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000308bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000309 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
310 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000311 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000312 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000313 CurModule = &M;
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000314 CurModuleUniqueId = getUniqueModuleId(CurModule);
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000315 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000316 FunctionGuardArray = nullptr;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000317 Function8bitCounterArray = nullptr;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000318 FunctionPCsArray = nullptr;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000319 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000320 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000321 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000322 IRBuilder<> IRB(*C);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000323 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000324 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000325 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000326 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000327 Int32Ty = IRB.getInt32Ty();
Alexander Potapenko52410812017-08-10 15:00:13 +0000328 Int16Ty = IRB.getInt16Ty();
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000329 Int8Ty = IRB.getInt8Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000330
James Y Knightf47d6b32019-01-31 20:35:56 +0000331 SanCovTracePCIndir =
332 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
333 // Make sure smaller parameters are zero-extended to i64 as required by the
334 // x86_64 ABI.
335 AttributeList SanCovTraceCmpZeroExtAL;
336 if (TargetTriple.getArch() == Triple::x86_64) {
337 SanCovTraceCmpZeroExtAL =
338 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
339 SanCovTraceCmpZeroExtAL =
340 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
341 }
342
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000343 SanCovTraceCmpFunction[0] =
James Y Knightf47d6b32019-01-31 20:35:56 +0000344 M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
345 IRB.getInt8Ty(), IRB.getInt8Ty());
346 SanCovTraceCmpFunction[1] =
347 M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
348 IRB.getInt16Ty(), IRB.getInt16Ty());
349 SanCovTraceCmpFunction[2] =
350 M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
351 IRB.getInt32Ty(), IRB.getInt32Ty());
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000352 SanCovTraceCmpFunction[3] =
James Y Knightf47d6b32019-01-31 20:35:56 +0000353 M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000354
James Y Knightf47d6b32019-01-31 20:35:56 +0000355 SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
356 SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
357 SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
358 SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
359 SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
360 SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
Alexander Potapenko52410812017-08-10 15:00:13 +0000361 SanCovTraceConstCmpFunction[3] =
James Y Knightf47d6b32019-01-31 20:35:56 +0000362 M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
Alexander Potapenko52410812017-08-10 15:00:13 +0000363
James Y Knightf47d6b32019-01-31 20:35:56 +0000364 {
365 AttributeList AL;
366 if (TargetTriple.getArch() == Triple::x86_64)
367 AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
368 SanCovTraceDivFunction[0] =
369 M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
370 }
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000371 SanCovTraceDivFunction[1] =
James Y Knightf47d6b32019-01-31 20:35:56 +0000372 M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000373 SanCovTraceGepFunction =
James Y Knightf47d6b32019-01-31 20:35:56 +0000374 M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000375 SanCovTraceSwitchFunction =
James Y Knightf47d6b32019-01-31 20:35:56 +0000376 M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000377
378 Constant *SanCovLowestStackConstant =
379 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000380 SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
381 SanCovLowestStack->setThreadLocalMode(
382 GlobalValue::ThreadLocalMode::InitialExecTLSModel);
383 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
384 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000385
Kostya Serebryany73762942014-12-16 21:24:15 +0000386 // We insert an empty inline asm after cov callbacks to avoid callback merge.
387 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
388 StringRef(""), StringRef(""),
389 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000390
James Y Knightf47d6b32019-01-31 20:35:56 +0000391 SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
392 SanCovTracePCGuard =
393 M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000394
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000395 for (auto &F : M)
396 runOnFunction(F);
397
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000398 Function *Ctor = nullptr;
Justin Bogner41e632b2017-02-01 02:38:39 +0000399
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000400 if (FunctionGuardArray)
401 Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
402 SanCovGuardsSectionName);
403 if (Function8bitCounterArray)
404 Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
405 SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000406 if (Ctor && Options.PCTable) {
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000407 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
James Y Knightf47d6b32019-01-31 20:35:56 +0000408 FunctionCallee InitFunction = declareSanitizerInitFunction(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000409 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000410 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
Jonathan Metzman5eb8cba2018-10-16 23:43:57 +0000411 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000412 }
Kostya Serebryany4192b962017-09-09 05:30:13 +0000413 // We don't reference these arrays directly in any of our runtime functions,
414 // so we need to prevent them from being dead stripped.
415 if (TargetTriple.isOSBinFormatMachO())
416 appendToUsed(M, GlobalsToAppendToUsed);
Matt Morehouse0ea9a902018-06-15 20:12:58 +0000417 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000418 return true;
419}
420
Mike Aizatsky9987f432016-03-23 23:15:03 +0000421// True if block has successors and it dominates all of them.
422static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
423 if (succ_begin(BB) == succ_end(BB))
424 return false;
425
426 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
427 if (!DT->dominates(BB, SUCC))
428 return false;
429 }
430
431 return true;
432}
433
George Karpenkov018472c2017-05-24 00:29:12 +0000434// True if block has predecessors and it postdominates all of them.
435static bool isFullPostDominator(const BasicBlock *BB,
436 const PostDominatorTree *PDT) {
437 if (pred_begin(BB) == pred_end(BB))
438 return false;
439
440 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
441 if (!PDT->dominates(BB, PRED))
442 return false;
443 }
444
445 return true;
446}
447
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000448static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
449 const DominatorTree *DT,
George Karpenkov018472c2017-05-24 00:29:12 +0000450 const PostDominatorTree *PDT,
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000451 const SanitizerCoverageOptions &Options) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000452 // Don't insert coverage for unreachable blocks: we will never call
453 // __sanitizer_cov() for them, so counting them in
454 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
455 // percentage. Also, unreachable instructions frequently have no debug
456 // locations.
457 if (isa<UnreachableInst>(BB->getTerminator()))
458 return false;
459
Reid Kleckner392f0622017-03-23 23:30:41 +0000460 // Don't insert coverage into blocks without a valid insertion point
461 // (catchswitch blocks).
462 if (BB->getFirstInsertionPt() == BB->end())
463 return false;
464
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000465 if (Options.NoPrune || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000466 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000467
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000468 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
469 &F.getEntryBlock() != BB)
470 return false;
471
George Karpenkova1c53272017-05-25 01:41:46 +0000472 // Do not instrument full dominators, or full post-dominators with multiple
473 // predecessors.
474 return !isFullDominator(BB, DT)
475 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
Mike Aizatsky5971f182016-02-26 01:17:22 +0000476}
477
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000478bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000479 if (F.empty())
480 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000481 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000482 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000483 if (F.getName().startswith("__sanitizer_"))
484 return false; // Don't instrument __sanitizer_* callbacks.
Kostya Serebryanybfc83fa2017-07-31 20:00:22 +0000485 // Don't touch available_externally functions, their actual body is elewhere.
486 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
487 return false;
Reid Klecknerec803542016-11-11 19:18:45 +0000488 // Don't instrument MSVC CRT configuration helpers. They may run before normal
489 // initialization.
490 if (F.getName() == "__local_stdio_printf_options" ||
491 F.getName() == "__local_stdio_scanf_options")
492 return false;
Kostya Serebryanya2759322018-05-11 01:09:39 +0000493 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
494 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000495 // Don't instrument functions using SEH for now. Splitting basic blocks like
496 // we do for coverage breaks WinEHPrepare.
497 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
498 if (F.hasPersonalityFn() &&
499 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
500 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000501 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000502 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000503 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000504 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000505 SmallVector<Instruction *, 8> CmpTraceTargets;
506 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000507 SmallVector<BinaryOperator *, 8> DivTraceTargets;
508 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000509
Mike Aizatsky602f7922016-03-21 23:08:16 +0000510 const DominatorTree *DT =
511 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
George Karpenkov018472c2017-05-24 00:29:12 +0000512 const PostDominatorTree *PDT =
513 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
Matt Morehouse034126e2017-08-30 22:49:31 +0000514 bool IsLeafFunc = true;
Mike Aizatsky602f7922016-03-21 23:08:16 +0000515
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000516 for (auto &BB : F) {
George Karpenkov018472c2017-05-24 00:29:12 +0000517 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000518 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000519 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000520 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000521 CallSite CS(&Inst);
522 if (CS && !CS.getCalledFunction())
523 IndirCalls.push_back(&Inst);
524 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000525 if (Options.TraceCmp) {
526 if (isa<ICmpInst>(&Inst))
527 CmpTraceTargets.push_back(&Inst);
528 if (isa<SwitchInst>(&Inst))
529 SwitchTraceTargets.push_back(&Inst);
530 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000531 if (Options.TraceDiv)
532 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
533 if (BO->getOpcode() == Instruction::SDiv ||
534 BO->getOpcode() == Instruction::UDiv)
535 DivTraceTargets.push_back(BO);
536 if (Options.TraceGep)
537 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
538 GepTraceTargets.push_back(GEP);
Matt Morehouse034126e2017-08-30 22:49:31 +0000539 if (Options.StackDepth)
540 if (isa<InvokeInst>(Inst) ||
541 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
542 IsLeafFunc = false;
543 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000544 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000545
Matt Morehouse034126e2017-08-30 22:49:31 +0000546 InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000547 InjectCoverageForIndirectCalls(F, IndirCalls);
548 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000549 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000550 InjectTraceForDiv(F, DivTraceTargets);
551 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000552 return true;
553}
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000554
555GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
556 size_t NumElements, Function &F, Type *Ty, const char *Section) {
557 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
558 auto Array = new GlobalVariable(
559 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
560 Constant::getNullValue(ArrayTy), "__sancov_gen_");
Kostya Serebryanybc504552018-10-12 23:21:48 +0000561
Matt Morehouse19ff35c2019-01-15 21:21:01 +0000562 if (TargetTriple.supportsCOMDAT() && !F.isInterposable())
Reid Klecknerb41b3722018-11-08 00:57:33 +0000563 if (auto Comdat =
564 GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId))
Kostya Serebryanybc504552018-10-12 23:21:48 +0000565 Array->setComdat(Comdat);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000566 Array->setSection(getSectionName(Section));
Kostya Serebryanybb6f0792017-07-31 19:49:45 +0000567 Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
568 : Ty->getPrimitiveSizeInBits() / 8);
Max Moroz4d010ca2018-10-12 13:59:31 +0000569 GlobalsToAppendToUsed.push_back(Array);
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000570 GlobalsToAppendToCompilerUsed.push_back(Array);
571 MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
572 Array->addMetadata(LLVMContext::MD_associated, *MD);
573
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000574 return Array;
575}
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000576
Justin Bogner873a0742017-08-28 23:46:11 +0000577GlobalVariable *
578SanitizerCoverageModule::CreatePCArray(Function &F,
579 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000580 size_t N = AllBlocks.size();
581 assert(N);
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000582 SmallVector<Constant *, 32> PCs;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000583 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000584 for (size_t i = 0; i < N; i++) {
585 if (&F.getEntryBlock() == AllBlocks[i]) {
586 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
587 PCs.push_back((Constant *)IRB.CreateIntToPtr(
588 ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
589 } else {
590 PCs.push_back((Constant *)IRB.CreatePointerCast(
591 BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
592 PCs.push_back((Constant *)IRB.CreateIntToPtr(
593 ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
594 }
595 }
Justin Bogner873a0742017-08-28 23:46:11 +0000596 auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
597 SanCovPCsSectionName);
598 PCArray->setInitializer(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000599 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
Justin Bogner873a0742017-08-28 23:46:11 +0000600 PCArray->setConstant(true);
Justin Bognerad96ff12017-08-25 01:24:54 +0000601
Justin Bogner873a0742017-08-28 23:46:11 +0000602 return PCArray;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000603}
604
605void SanitizerCoverageModule::CreateFunctionLocalArrays(
606 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
Max Moroz4d010ca2018-10-12 13:59:31 +0000607 if (Options.TracePCGuard)
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000608 FunctionGuardArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000609 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
Max Moroz4d010ca2018-10-12 13:59:31 +0000610
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000611 if (Options.Inline8bitCounters)
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000612 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000613 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
Max Moroz4d010ca2018-10-12 13:59:31 +0000614
Matt Morehouse3bea25e2018-09-13 21:45:55 +0000615 if (Options.PCTable)
Justin Bogner873a0742017-08-28 23:46:11 +0000616 FunctionPCsArray = CreatePCArray(F, AllBlocks);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000617}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000618
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000619bool SanitizerCoverageModule::InjectCoverage(Function &F,
Matt Morehouse034126e2017-08-30 22:49:31 +0000620 ArrayRef<BasicBlock *> AllBlocks,
621 bool IsLeafFunc) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000622 if (AllBlocks.empty()) return false;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000623 CreateFunctionLocalArrays(F, AllBlocks);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000624 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
Matt Morehouse034126e2017-08-30 22:49:31 +0000625 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000626 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000627}
628
629// On every indirect call we call a run-time function
630// __sanitizer_cov_indir_call* with two parameters:
631// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000632// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000633// The cache is used to speed up recording the caller-callee pairs.
634// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000635// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000636void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
637 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000638 if (IndirCalls.empty())
639 return;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000640 assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000641 for (auto I : IndirCalls) {
642 IRBuilder<> IRB(I);
643 CallSite CS(I);
644 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000645 if (isa<InlineAsm>(Callee))
646 continue;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000647 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000648 }
649}
650
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000651// For every switch statement we insert a call:
652// __sanitizer_cov_trace_switch(CondValue,
653// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
654
655void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000656 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000657 for (auto I : SwitchTraceTargets) {
658 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
659 IRBuilder<> IRB(I);
660 SmallVector<Constant *, 16> Initializers;
661 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000662 if (Cond->getType()->getScalarSizeInBits() >
663 Int64Ty->getScalarSizeInBits())
664 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000665 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
666 Initializers.push_back(
667 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
668 if (Cond->getType()->getScalarSizeInBits() <
669 Int64Ty->getScalarSizeInBits())
670 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000671 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000672 Constant *C = It.getCaseValue();
673 if (C->getType()->getScalarSizeInBits() <
674 Int64Ty->getScalarSizeInBits())
675 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
676 Initializers.push_back(C);
677 }
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000678 llvm::sort(Initializers.begin() + 2, Initializers.end(),
679 [](const Constant *A, const Constant *B) {
680 return cast<ConstantInt>(A)->getLimitedValue() <
681 cast<ConstantInt>(B)->getLimitedValue();
682 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000683 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
684 GlobalVariable *GV = new GlobalVariable(
685 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
686 ConstantArray::get(ArrayOfInt64Ty, Initializers),
687 "__sancov_gen_cov_switch_values");
688 IRB.CreateCall(SanCovTraceSwitchFunction,
689 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
690 }
691 }
692}
693
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000694void SanitizerCoverageModule::InjectTraceForDiv(
695 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
696 for (auto BO : DivTraceTargets) {
697 IRBuilder<> IRB(BO);
698 Value *A1 = BO->getOperand(1);
699 if (isa<ConstantInt>(A1)) continue;
700 if (!A1->getType()->isIntegerTy())
701 continue;
702 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
703 int CallbackIdx = TypeSize == 32 ? 0 :
704 TypeSize == 64 ? 1 : -1;
705 if (CallbackIdx < 0) continue;
706 auto Ty = Type::getIntNTy(*C, TypeSize);
707 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
708 {IRB.CreateIntCast(A1, Ty, true)});
709 }
710}
711
712void SanitizerCoverageModule::InjectTraceForGep(
713 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
714 for (auto GEP : GepTraceTargets) {
715 IRBuilder<> IRB(GEP);
716 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000717 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000718 IRB.CreateCall(SanCovTraceGepFunction,
719 {IRB.CreateIntCast(*I, IntptrTy, true)});
720 }
721}
722
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000723void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000724 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000725 for (auto I : CmpTraceTargets) {
726 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
727 IRBuilder<> IRB(ICMP);
728 Value *A0 = ICMP->getOperand(0);
729 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000730 if (!A0->getType()->isIntegerTy())
731 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000732 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000733 int CallbackIdx = TypeSize == 8 ? 0 :
734 TypeSize == 16 ? 1 :
735 TypeSize == 32 ? 2 :
736 TypeSize == 64 ? 3 : -1;
737 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000738 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Alexander Potapenko52410812017-08-10 15:00:13 +0000739 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
740 bool FirstIsConst = isa<ConstantInt>(A0);
741 bool SecondIsConst = isa<ConstantInt>(A1);
742 // If both are const, then we don't need such a comparison.
743 if (FirstIsConst && SecondIsConst) continue;
744 // If only one is const, then make it the first callback argument.
745 if (FirstIsConst || SecondIsConst) {
746 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
Justin Bognerbe757de2017-08-28 23:38:12 +0000747 if (SecondIsConst)
Alexander Potapenko52410812017-08-10 15:00:13 +0000748 std::swap(A0, A1);
749 }
750
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000751 auto Ty = Type::getIntNTy(*C, TypeSize);
Justin Bognerbe757de2017-08-28 23:38:12 +0000752 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
Alexander Potapenko52410812017-08-10 15:00:13 +0000753 IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000754 }
755 }
756}
757
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000758void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Matt Morehouse034126e2017-08-30 22:49:31 +0000759 size_t Idx,
760 bool IsLeafFunc) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000761 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000762 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000763 DebugLoc EntryLoc;
764 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000765 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000766 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000767 // Keep static allocas and llvm.localescape calls in the entry block. Even
768 // if we aren't splitting the block, it's nice for allocas to be before
769 // calls.
770 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000771 } else {
772 EntryLoc = IP->getDebugLoc();
773 }
774
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000775 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000776 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000777 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000778 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
779 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000780 }
781 if (Options.TracePCGuard) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000782 auto GuardPtr = IRB.CreateIntToPtr(
783 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
784 ConstantInt::get(IntptrTy, Idx * 4)),
785 Int32PtrTy);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000786 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
787 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000788 }
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000789 if (Options.Inline8bitCounters) {
790 auto CounterPtr = IRB.CreateGEP(
791 Function8bitCounterArray,
792 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
793 auto Load = IRB.CreateLoad(CounterPtr);
794 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
795 auto Store = IRB.CreateStore(Inc, CounterPtr);
796 SetNoSanitizeMetadata(Load);
797 SetNoSanitizeMetadata(Store);
798 }
Matt Morehouse034126e2017-08-30 22:49:31 +0000799 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000800 // Check stack depth. If it's the deepest so far, record it.
801 Function *GetFrameAddr =
802 Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
803 auto FrameAddrPtr =
804 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
805 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000806 auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000807 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
808 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
809 IRBuilder<> ThenIRB(ThenTerm);
Matt Morehouse034126e2017-08-30 22:49:31 +0000810 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
811 SetNoSanitizeMetadata(LowestStack);
812 SetNoSanitizeMetadata(Store);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000813 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000814}
815
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000816std::string
817SanitizerCoverageModule::getSectionName(const std::string &Section) const {
Jonathan Metzmane159a0d2019-01-14 21:02:02 +0000818 if (TargetTriple.isOSBinFormatCOFF()) {
Matt Morehouse7e042bb2018-08-30 15:54:44 +0000819 if (Section == SanCovCountersSectionName)
820 return ".SCOV$CM";
821 if (Section == SanCovPCsSectionName)
822 return ".SCOVP$M";
823 return ".SCOV$GM"; // For SanCovGuardsSectionName.
824 }
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000825 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000826 return "__DATA,__" + Section;
827 return "__" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000828}
829
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000830std::string
831SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000832 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000833 return "\1section$start$__DATA$__" + Section;
834 return "__start___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000835}
836
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000837std::string
838SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000839 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000840 return "\1section$end$__DATA$__" + Section;
841 return "__stop___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000842}
843
844
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000845char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000846INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000847 "SanitizerCoverage: TODO."
848 "ModulePass",
849 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000850INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
George Karpenkov018472c2017-05-24 00:29:12 +0000851INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Mike Aizatsky90562842016-02-27 05:50:40 +0000852INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000853 "SanitizerCoverage: TODO."
854 "ModulePass",
855 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000856ModulePass *llvm::createSanitizerCoverageModulePass(
857 const SanitizerCoverageOptions &Options) {
858 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000859}