1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Coverage instrumentation done on LLVM IR level, works with Sanitizers.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/Analysis/EHPersonalities.h"
17 #include "llvm/Analysis/PostDominators.h"
18 #include "llvm/IR/CFG.h"
19 #include "llvm/IR/Constant.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/InlineAsm.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/MDBuilder.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/InitializePasses.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/SpecialCaseList.h"
38 #include "llvm/Support/VirtualFileSystem.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Instrumentation.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/Transforms/Utils/ModuleUtils.h"
43
44 using namespace llvm;
45
46 #define DEBUG_TYPE "sancov"
47
48 const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
49 const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
50 const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
51 const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
52 const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
53 const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8";
54 const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1";
55 const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2";
56 const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4";
57 const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8";
58 const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4";
59 const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8";
60 const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep";
61 const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch";
62 const char SanCovModuleCtorTracePcGuardName[] =
63 "sancov.module_ctor_trace_pc_guard";
64 const char SanCovModuleCtor8bitCountersName[] =
65 "sancov.module_ctor_8bit_counters";
66 const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag";
67 static const uint64_t SanCtorAndDtorPriority = 2;
68
69 const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard";
70 const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init";
71 const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
72 const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
73 const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
74
75 const char SanCovGuardsSectionName[] = "sancov_guards";
76 const char SanCovCountersSectionName[] = "sancov_cntrs";
77 const char SanCovBoolFlagSectionName[] = "sancov_bools";
78 const char SanCovPCsSectionName[] = "sancov_pcs";
79
80 const char SanCovLowestStackName[] = "__sancov_lowest_stack";
81
82 static cl::opt<int> ClCoverageLevel(
83 "sanitizer-coverage-level",
84 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
85 "3: all blocks and critical edges"),
86 cl::Hidden, cl::init(0));
87
88 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
89 cl::desc("Experimental pc tracing"), cl::Hidden,
90 cl::init(false));
91
92 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
93 cl::desc("pc tracing with a guard"),
94 cl::Hidden, cl::init(false));
95
96 // 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, inline-8bit-counters, and
101 // inline-bool-flag.
102 static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
103 cl::desc("create a static PC table"),
104 cl::Hidden, cl::init(false));
105
106 static cl::opt<bool>
107 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
108 cl::desc("increments 8-bit counter for every edge"),
109 cl::Hidden, cl::init(false));
110
111 static cl::opt<bool>
112 ClInlineBoolFlag("sanitizer-coverage-inline-bool-flag",
113 cl::desc("sets a boolean flag for every edge"), cl::Hidden,
114 cl::init(false));
115
116 static cl::opt<bool>
117 ClCMPTracing("sanitizer-coverage-trace-compares",
118 cl::desc("Tracing of CMP and similar instructions"),
119 cl::Hidden, cl::init(false));
120
121 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
122 cl::desc("Tracing of DIV instructions"),
123 cl::Hidden, cl::init(false));
124
125 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
126 cl::desc("Tracing of GEP instructions"),
127 cl::Hidden, cl::init(false));
128
129 static cl::opt<bool>
130 ClPruneBlocks("sanitizer-coverage-prune-blocks",
131 cl::desc("Reduce the number of instrumented blocks"),
132 cl::Hidden, cl::init(true));
133
134 static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
135 cl::desc("max stack depth tracing"),
136 cl::Hidden, cl::init(false));
137
138 namespace {
139
getOptions(int LegacyCoverageLevel)140 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
141 SanitizerCoverageOptions Res;
142 switch (LegacyCoverageLevel) {
143 case 0:
144 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
145 break;
146 case 1:
147 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
148 break;
149 case 2:
150 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
151 break;
152 case 3:
153 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
154 break;
155 case 4:
156 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
157 Res.IndirectCalls = true;
158 break;
159 }
160 return Res;
161 }
162
OverrideFromCL(SanitizerCoverageOptions Options)163 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
164 // Sets CoverageType and IndirectCalls.
165 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
166 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
167 Options.IndirectCalls |= CLOpts.IndirectCalls;
168 Options.TraceCmp |= ClCMPTracing;
169 Options.TraceDiv |= ClDIVTracing;
170 Options.TraceGep |= ClGEPTracing;
171 Options.TracePC |= ClTracePC;
172 Options.TracePCGuard |= ClTracePCGuard;
173 Options.Inline8bitCounters |= ClInline8bitCounters;
174 Options.InlineBoolFlag |= ClInlineBoolFlag;
175 Options.PCTable |= ClCreatePCTable;
176 Options.NoPrune |= !ClPruneBlocks;
177 Options.StackDepth |= ClStackDepth;
178 if (!Options.TracePCGuard && !Options.TracePC &&
179 !Options.Inline8bitCounters && !Options.StackDepth &&
180 !Options.InlineBoolFlag)
181 Options.TracePCGuard = true; // TracePCGuard is default.
182 return Options;
183 }
184
185 using DomTreeCallback = function_ref<const DominatorTree *(Function &F)>;
186 using PostDomTreeCallback =
187 function_ref<const PostDominatorTree *(Function &F)>;
188
189 class ModuleSanitizerCoverage {
190 public:
ModuleSanitizerCoverage(const SanitizerCoverageOptions & Options=SanitizerCoverageOptions (),const SpecialCaseList * Allowlist=nullptr,const SpecialCaseList * Blocklist=nullptr)191 ModuleSanitizerCoverage(
192 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions(),
193 const SpecialCaseList *Allowlist = nullptr,
194 const SpecialCaseList *Blocklist = nullptr)
195 : Options(OverrideFromCL(Options)), Allowlist(Allowlist),
196 Blocklist(Blocklist) {}
197 bool instrumentModule(Module &M, DomTreeCallback DTCallback,
198 PostDomTreeCallback PDTCallback);
199
200 private:
201 void instrumentFunction(Function &F, DomTreeCallback DTCallback,
202 PostDomTreeCallback PDTCallback);
203 void InjectCoverageForIndirectCalls(Function &F,
204 ArrayRef<Instruction *> IndirCalls);
205 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
206 void InjectTraceForDiv(Function &F,
207 ArrayRef<BinaryOperator *> DivTraceTargets);
208 void InjectTraceForGep(Function &F,
209 ArrayRef<GetElementPtrInst *> GepTraceTargets);
210 void InjectTraceForSwitch(Function &F,
211 ArrayRef<Instruction *> SwitchTraceTargets);
212 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
213 bool IsLeafFunc = true);
214 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
215 Function &F, Type *Ty,
216 const char *Section);
217 GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
218 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
219 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
220 bool IsLeafFunc = true);
221 Function *CreateInitCallsForSections(Module &M, const char *CtorName,
222 const char *InitFunctionName, Type *Ty,
223 const char *Section);
224 std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
225 Type *Ty);
226
SetNoSanitizeMetadata(Instruction * I)227 void SetNoSanitizeMetadata(Instruction *I) {
228 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
229 MDNode::get(*C, None));
230 }
231
232 std::string getSectionName(const std::string &Section) const;
233 std::string getSectionStart(const std::string &Section) const;
234 std::string getSectionEnd(const std::string &Section) const;
235 FunctionCallee SanCovTracePCIndir;
236 FunctionCallee SanCovTracePC, SanCovTracePCGuard;
237 FunctionCallee SanCovTraceCmpFunction[4];
238 FunctionCallee SanCovTraceConstCmpFunction[4];
239 FunctionCallee SanCovTraceDivFunction[2];
240 FunctionCallee SanCovTraceGepFunction;
241 FunctionCallee SanCovTraceSwitchFunction;
242 GlobalVariable *SanCovLowestStack;
243 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
244 *Int16Ty, *Int8Ty, *Int8PtrTy, *Int1Ty, *Int1PtrTy;
245 Module *CurModule;
246 std::string CurModuleUniqueId;
247 Triple TargetTriple;
248 LLVMContext *C;
249 const DataLayout *DL;
250
251 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
252 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
253 GlobalVariable *FunctionBoolArray; // for inline-bool-flag.
254 GlobalVariable *FunctionPCsArray; // for pc-table.
255 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
256 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
257
258 SanitizerCoverageOptions Options;
259
260 const SpecialCaseList *Allowlist;
261 const SpecialCaseList *Blocklist;
262 };
263
264 class ModuleSanitizerCoverageLegacyPass : public ModulePass {
265 public:
ModuleSanitizerCoverageLegacyPass(const SanitizerCoverageOptions & Options=SanitizerCoverageOptions (),const std::vector<std::string> & AllowlistFiles=std::vector<std::string> (),const std::vector<std::string> & BlocklistFiles=std::vector<std::string> ())266 ModuleSanitizerCoverageLegacyPass(
267 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions(),
268 const std::vector<std::string> &AllowlistFiles =
269 std::vector<std::string>(),
270 const std::vector<std::string> &BlocklistFiles =
271 std::vector<std::string>())
272 : ModulePass(ID), Options(Options) {
273 if (AllowlistFiles.size() > 0)
274 Allowlist = SpecialCaseList::createOrDie(AllowlistFiles,
275 *vfs::getRealFileSystem());
276 if (BlocklistFiles.size() > 0)
277 Blocklist = SpecialCaseList::createOrDie(BlocklistFiles,
278 *vfs::getRealFileSystem());
279 initializeModuleSanitizerCoverageLegacyPassPass(
280 *PassRegistry::getPassRegistry());
281 }
runOnModule(Module & M)282 bool runOnModule(Module &M) override {
283 ModuleSanitizerCoverage ModuleSancov(Options, Allowlist.get(),
284 Blocklist.get());
285 auto DTCallback = [this](Function &F) -> const DominatorTree * {
286 return &this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
287 };
288 auto PDTCallback = [this](Function &F) -> const PostDominatorTree * {
289 return &this->getAnalysis<PostDominatorTreeWrapperPass>(F)
290 .getPostDomTree();
291 };
292 return ModuleSancov.instrumentModule(M, DTCallback, PDTCallback);
293 }
294
295 static char ID; // Pass identification, replacement for typeid
getPassName() const296 StringRef getPassName() const override { return "ModuleSanitizerCoverage"; }
297
getAnalysisUsage(AnalysisUsage & AU) const298 void getAnalysisUsage(AnalysisUsage &AU) const override {
299 AU.addRequired<DominatorTreeWrapperPass>();
300 AU.addRequired<PostDominatorTreeWrapperPass>();
301 }
302
303 private:
304 SanitizerCoverageOptions Options;
305
306 std::unique_ptr<SpecialCaseList> Allowlist;
307 std::unique_ptr<SpecialCaseList> Blocklist;
308 };
309
310 } // namespace
311
run(Module & M,ModuleAnalysisManager & MAM)312 PreservedAnalyses ModuleSanitizerCoveragePass::run(Module &M,
313 ModuleAnalysisManager &MAM) {
314 ModuleSanitizerCoverage ModuleSancov(Options, Allowlist.get(),
315 Blocklist.get());
316 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
317 auto DTCallback = [&FAM](Function &F) -> const DominatorTree * {
318 return &FAM.getResult<DominatorTreeAnalysis>(F);
319 };
320 auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree * {
321 return &FAM.getResult<PostDominatorTreeAnalysis>(F);
322 };
323 if (ModuleSancov.instrumentModule(M, DTCallback, PDTCallback))
324 return PreservedAnalyses::none();
325 return PreservedAnalyses::all();
326 }
327
328 std::pair<Value *, Value *>
CreateSecStartEnd(Module & M,const char * Section,Type * Ty)329 ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
330 Type *Ty) {
331 // Use ExternalWeak so that if all sections are discarded due to section
332 // garbage collection, the linker will not report undefined symbol errors.
333 // Windows defines the start/stop symbols in compiler-rt so no need for
334 // ExternalWeak.
335 GlobalValue::LinkageTypes Linkage = TargetTriple.isOSBinFormatCOFF()
336 ? GlobalVariable::ExternalLinkage
337 : GlobalVariable::ExternalWeakLinkage;
338 GlobalVariable *SecStart =
339 new GlobalVariable(M, Ty->getPointerElementType(), false, Linkage,
340 nullptr, getSectionStart(Section));
341 SecStart->setVisibility(GlobalValue::HiddenVisibility);
342 GlobalVariable *SecEnd =
343 new GlobalVariable(M, Ty->getPointerElementType(), false, Linkage,
344 nullptr, getSectionEnd(Section));
345 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
346 IRBuilder<> IRB(M.getContext());
347 if (!TargetTriple.isOSBinFormatCOFF())
348 return std::make_pair(SecStart, SecEnd);
349
350 // Account for the fact that on windows-msvc __start_* symbols actually
351 // point to a uint64_t before the start of the array.
352 auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
353 auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr,
354 ConstantInt::get(IntptrTy, sizeof(uint64_t)));
355 return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEnd);
356 }
357
CreateInitCallsForSections(Module & M,const char * CtorName,const char * InitFunctionName,Type * Ty,const char * Section)358 Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
359 Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
360 const char *Section) {
361 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
362 auto SecStart = SecStartEnd.first;
363 auto SecEnd = SecStartEnd.second;
364 Function *CtorFunc;
365 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
366 M, CtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd});
367 assert(CtorFunc->getName() == CtorName);
368
369 if (TargetTriple.supportsCOMDAT()) {
370 // Use comdat to dedup CtorFunc.
371 CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
372 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
373 } else {
374 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
375 }
376
377 if (TargetTriple.isOSBinFormatCOFF()) {
378 // In COFF files, if the contructors are set as COMDAT (they are because
379 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
380 // functions and data) is used, the constructors get stripped. To prevent
381 // this, give the constructors weak ODR linkage and ensure the linker knows
382 // to include the sancov constructor. This way the linker can deduplicate
383 // the constructors but always leave one copy.
384 CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
385 appendToUsed(M, CtorFunc);
386 }
387 return CtorFunc;
388 }
389
instrumentModule(Module & M,DomTreeCallback DTCallback,PostDomTreeCallback PDTCallback)390 bool ModuleSanitizerCoverage::instrumentModule(
391 Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
392 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
393 return false;
394 if (Allowlist &&
395 !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
396 return false;
397 if (Blocklist &&
398 Blocklist->inSection("coverage", "src", M.getSourceFileName()))
399 return false;
400 C = &(M.getContext());
401 DL = &M.getDataLayout();
402 CurModule = &M;
403 CurModuleUniqueId = getUniqueModuleId(CurModule);
404 TargetTriple = Triple(M.getTargetTriple());
405 FunctionGuardArray = nullptr;
406 Function8bitCounterArray = nullptr;
407 FunctionBoolArray = nullptr;
408 FunctionPCsArray = nullptr;
409 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
410 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
411 Type *VoidTy = Type::getVoidTy(*C);
412 IRBuilder<> IRB(*C);
413 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
414 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
415 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
416 Int1PtrTy = PointerType::getUnqual(IRB.getInt1Ty());
417 Int64Ty = IRB.getInt64Ty();
418 Int32Ty = IRB.getInt32Ty();
419 Int16Ty = IRB.getInt16Ty();
420 Int8Ty = IRB.getInt8Ty();
421 Int1Ty = IRB.getInt1Ty();
422
423 SanCovTracePCIndir =
424 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
425 // Make sure smaller parameters are zero-extended to i64 if required by the
426 // target ABI.
427 AttributeList SanCovTraceCmpZeroExtAL;
428 SanCovTraceCmpZeroExtAL =
429 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
430 SanCovTraceCmpZeroExtAL =
431 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
432
433 SanCovTraceCmpFunction[0] =
434 M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
435 IRB.getInt8Ty(), IRB.getInt8Ty());
436 SanCovTraceCmpFunction[1] =
437 M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
438 IRB.getInt16Ty(), IRB.getInt16Ty());
439 SanCovTraceCmpFunction[2] =
440 M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
441 IRB.getInt32Ty(), IRB.getInt32Ty());
442 SanCovTraceCmpFunction[3] =
443 M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
444
445 SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
446 SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
447 SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
448 SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
449 SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
450 SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
451 SanCovTraceConstCmpFunction[3] =
452 M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
453
454 {
455 AttributeList AL;
456 AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
457 SanCovTraceDivFunction[0] =
458 M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
459 }
460 SanCovTraceDivFunction[1] =
461 M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
462 SanCovTraceGepFunction =
463 M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
464 SanCovTraceSwitchFunction =
465 M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
466
467 Constant *SanCovLowestStackConstant =
468 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
469 SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
470 if (!SanCovLowestStack) {
471 C->emitError(StringRef("'") + SanCovLowestStackName +
472 "' should not be declared by the user");
473 return true;
474 }
475 SanCovLowestStack->setThreadLocalMode(
476 GlobalValue::ThreadLocalMode::InitialExecTLSModel);
477 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
478 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
479
480 SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
481 SanCovTracePCGuard =
482 M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
483
484 for (auto &F : M)
485 instrumentFunction(F, DTCallback, PDTCallback);
486
487 Function *Ctor = nullptr;
488
489 if (FunctionGuardArray)
490 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
491 SanCovTracePCGuardInitName, Int32PtrTy,
492 SanCovGuardsSectionName);
493 if (Function8bitCounterArray)
494 Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
495 SanCov8bitCountersInitName, Int8PtrTy,
496 SanCovCountersSectionName);
497 if (FunctionBoolArray) {
498 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
499 SanCovBoolFlagInitName, Int1PtrTy,
500 SanCovBoolFlagSectionName);
501 }
502 if (Ctor && Options.PCTable) {
503 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
504 FunctionCallee InitFunction = declareSanitizerInitFunction(
505 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
506 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
507 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
508 }
509 appendToUsed(M, GlobalsToAppendToUsed);
510 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
511 return true;
512 }
513
514 // True if block has successors and it dominates all of them.
isFullDominator(const BasicBlock * BB,const DominatorTree * DT)515 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
516 if (succ_empty(BB))
517 return false;
518
519 return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) {
520 return DT->dominates(BB, SUCC);
521 });
522 }
523
524 // True if block has predecessors and it postdominates all of them.
isFullPostDominator(const BasicBlock * BB,const PostDominatorTree * PDT)525 static bool isFullPostDominator(const BasicBlock *BB,
526 const PostDominatorTree *PDT) {
527 if (pred_empty(BB))
528 return false;
529
530 return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) {
531 return PDT->dominates(BB, PRED);
532 });
533 }
534
shouldInstrumentBlock(const Function & F,const BasicBlock * BB,const DominatorTree * DT,const PostDominatorTree * PDT,const SanitizerCoverageOptions & Options)535 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
536 const DominatorTree *DT,
537 const PostDominatorTree *PDT,
538 const SanitizerCoverageOptions &Options) {
539 // Don't insert coverage for blocks containing nothing but unreachable: we
540 // will never call __sanitizer_cov() for them, so counting them in
541 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
542 // percentage. Also, unreachable instructions frequently have no debug
543 // locations.
544 if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime()))
545 return false;
546
547 // Don't insert coverage into blocks without a valid insertion point
548 // (catchswitch blocks).
549 if (BB->getFirstInsertionPt() == BB->end())
550 return false;
551
552 if (Options.NoPrune || &F.getEntryBlock() == BB)
553 return true;
554
555 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
556 &F.getEntryBlock() != BB)
557 return false;
558
559 // Do not instrument full dominators, or full post-dominators with multiple
560 // predecessors.
561 return !isFullDominator(BB, DT)
562 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
563 }
564
565
566 // Returns true iff From->To is a backedge.
567 // A twist here is that we treat From->To as a backedge if
568 // * To dominates From or
569 // * To->UniqueSuccessor dominates From
IsBackEdge(BasicBlock * From,BasicBlock * To,const DominatorTree * DT)570 static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
571 const DominatorTree *DT) {
572 if (DT->dominates(To, From))
573 return true;
574 if (auto Next = To->getUniqueSuccessor())
575 if (DT->dominates(Next, From))
576 return true;
577 return false;
578 }
579
580 // Prunes uninteresting Cmp instrumentation:
581 // * CMP instructions that feed into loop backedge branch.
582 //
583 // Note that Cmp pruning is controlled by the same flag as the
584 // BB pruning.
IsInterestingCmp(ICmpInst * CMP,const DominatorTree * DT,const SanitizerCoverageOptions & Options)585 static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT,
586 const SanitizerCoverageOptions &Options) {
587 if (!Options.NoPrune)
588 if (CMP->hasOneUse())
589 if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
590 for (BasicBlock *B : BR->successors())
591 if (IsBackEdge(BR->getParent(), B, DT))
592 return false;
593 return true;
594 }
595
instrumentFunction(Function & F,DomTreeCallback DTCallback,PostDomTreeCallback PDTCallback)596 void ModuleSanitizerCoverage::instrumentFunction(
597 Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
598 if (F.empty())
599 return;
600 if (F.getName().find(".module_ctor") != std::string::npos)
601 return; // Should not instrument sanitizer init functions.
602 if (F.getName().startswith("__sanitizer_"))
603 return; // Don't instrument __sanitizer_* callbacks.
604 // Don't touch available_externally functions, their actual body is elewhere.
605 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
606 return;
607 // Don't instrument MSVC CRT configuration helpers. They may run before normal
608 // initialization.
609 if (F.getName() == "__local_stdio_printf_options" ||
610 F.getName() == "__local_stdio_scanf_options")
611 return;
612 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
613 return;
614 // Don't instrument functions using SEH for now. Splitting basic blocks like
615 // we do for coverage breaks WinEHPrepare.
616 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
617 if (F.hasPersonalityFn() &&
618 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
619 return;
620 if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
621 return;
622 if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
623 return;
624 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
625 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
626 SmallVector<Instruction *, 8> IndirCalls;
627 SmallVector<BasicBlock *, 16> BlocksToInstrument;
628 SmallVector<Instruction *, 8> CmpTraceTargets;
629 SmallVector<Instruction *, 8> SwitchTraceTargets;
630 SmallVector<BinaryOperator *, 8> DivTraceTargets;
631 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
632
633 const DominatorTree *DT = DTCallback(F);
634 const PostDominatorTree *PDT = PDTCallback(F);
635 bool IsLeafFunc = true;
636
637 for (auto &BB : F) {
638 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
639 BlocksToInstrument.push_back(&BB);
640 for (auto &Inst : BB) {
641 if (Options.IndirectCalls) {
642 CallBase *CB = dyn_cast<CallBase>(&Inst);
643 if (CB && !CB->getCalledFunction())
644 IndirCalls.push_back(&Inst);
645 }
646 if (Options.TraceCmp) {
647 if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
648 if (IsInterestingCmp(CMP, DT, Options))
649 CmpTraceTargets.push_back(&Inst);
650 if (isa<SwitchInst>(&Inst))
651 SwitchTraceTargets.push_back(&Inst);
652 }
653 if (Options.TraceDiv)
654 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
655 if (BO->getOpcode() == Instruction::SDiv ||
656 BO->getOpcode() == Instruction::UDiv)
657 DivTraceTargets.push_back(BO);
658 if (Options.TraceGep)
659 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
660 GepTraceTargets.push_back(GEP);
661 if (Options.StackDepth)
662 if (isa<InvokeInst>(Inst) ||
663 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
664 IsLeafFunc = false;
665 }
666 }
667
668 InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
669 InjectCoverageForIndirectCalls(F, IndirCalls);
670 InjectTraceForCmp(F, CmpTraceTargets);
671 InjectTraceForSwitch(F, SwitchTraceTargets);
672 InjectTraceForDiv(F, DivTraceTargets);
673 InjectTraceForGep(F, GepTraceTargets);
674 }
675
CreateFunctionLocalArrayInSection(size_t NumElements,Function & F,Type * Ty,const char * Section)676 GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
677 size_t NumElements, Function &F, Type *Ty, const char *Section) {
678 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
679 auto Array = new GlobalVariable(
680 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
681 Constant::getNullValue(ArrayTy), "__sancov_gen_");
682
683 if (TargetTriple.supportsCOMDAT() &&
684 (TargetTriple.isOSBinFormatELF() || !F.isInterposable()))
685 if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
686 Array->setComdat(Comdat);
687 Array->setSection(getSectionName(Section));
688 Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedSize()));
689
690 // sancov_pcs parallels the other metadata section(s). Optimizers (e.g.
691 // GlobalOpt/ConstantMerge) may not discard sancov_pcs and the other
692 // section(s) as a unit, so we conservatively retain all unconditionally in
693 // the compiler.
694 //
695 // With comdat (COFF/ELF), the linker can guarantee the associated sections
696 // will be retained or discarded as a unit, so llvm.compiler.used is
697 // sufficient. Otherwise, conservatively make all of them retained by the
698 // linker.
699 if (Array->hasComdat())
700 GlobalsToAppendToCompilerUsed.push_back(Array);
701 else
702 GlobalsToAppendToUsed.push_back(Array);
703
704 return Array;
705 }
706
707 GlobalVariable *
CreatePCArray(Function & F,ArrayRef<BasicBlock * > AllBlocks)708 ModuleSanitizerCoverage::CreatePCArray(Function &F,
709 ArrayRef<BasicBlock *> AllBlocks) {
710 size_t N = AllBlocks.size();
711 assert(N);
712 SmallVector<Constant *, 32> PCs;
713 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
714 for (size_t i = 0; i < N; i++) {
715 if (&F.getEntryBlock() == AllBlocks[i]) {
716 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
717 PCs.push_back((Constant *)IRB.CreateIntToPtr(
718 ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
719 } else {
720 PCs.push_back((Constant *)IRB.CreatePointerCast(
721 BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
722 PCs.push_back((Constant *)IRB.CreateIntToPtr(
723 ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
724 }
725 }
726 auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
727 SanCovPCsSectionName);
728 PCArray->setInitializer(
729 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
730 PCArray->setConstant(true);
731
732 return PCArray;
733 }
734
CreateFunctionLocalArrays(Function & F,ArrayRef<BasicBlock * > AllBlocks)735 void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
736 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
737 if (Options.TracePCGuard)
738 FunctionGuardArray = CreateFunctionLocalArrayInSection(
739 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
740
741 if (Options.Inline8bitCounters)
742 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
743 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
744 if (Options.InlineBoolFlag)
745 FunctionBoolArray = CreateFunctionLocalArrayInSection(
746 AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
747
748 if (Options.PCTable)
749 FunctionPCsArray = CreatePCArray(F, AllBlocks);
750 }
751
InjectCoverage(Function & F,ArrayRef<BasicBlock * > AllBlocks,bool IsLeafFunc)752 bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
753 ArrayRef<BasicBlock *> AllBlocks,
754 bool IsLeafFunc) {
755 if (AllBlocks.empty()) return false;
756 CreateFunctionLocalArrays(F, AllBlocks);
757 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
758 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
759 return true;
760 }
761
762 // On every indirect call we call a run-time function
763 // __sanitizer_cov_indir_call* with two parameters:
764 // - callee address,
765 // - global cache array that contains CacheSize pointers (zero-initialized).
766 // The cache is used to speed up recording the caller-callee pairs.
767 // The address of the caller is passed implicitly via caller PC.
768 // CacheSize is encoded in the name of the run-time function.
InjectCoverageForIndirectCalls(Function & F,ArrayRef<Instruction * > IndirCalls)769 void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
770 Function &F, ArrayRef<Instruction *> IndirCalls) {
771 if (IndirCalls.empty())
772 return;
773 assert(Options.TracePC || Options.TracePCGuard ||
774 Options.Inline8bitCounters || Options.InlineBoolFlag);
775 for (auto I : IndirCalls) {
776 IRBuilder<> IRB(I);
777 CallBase &CB = cast<CallBase>(*I);
778 Value *Callee = CB.getCalledOperand();
779 if (isa<InlineAsm>(Callee))
780 continue;
781 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
782 }
783 }
784
785 // For every switch statement we insert a call:
786 // __sanitizer_cov_trace_switch(CondValue,
787 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
788
InjectTraceForSwitch(Function &,ArrayRef<Instruction * > SwitchTraceTargets)789 void ModuleSanitizerCoverage::InjectTraceForSwitch(
790 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
791 for (auto I : SwitchTraceTargets) {
792 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
793 IRBuilder<> IRB(I);
794 SmallVector<Constant *, 16> Initializers;
795 Value *Cond = SI->getCondition();
796 if (Cond->getType()->getScalarSizeInBits() >
797 Int64Ty->getScalarSizeInBits())
798 continue;
799 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
800 Initializers.push_back(
801 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
802 if (Cond->getType()->getScalarSizeInBits() <
803 Int64Ty->getScalarSizeInBits())
804 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
805 for (auto It : SI->cases()) {
806 Constant *C = It.getCaseValue();
807 if (C->getType()->getScalarSizeInBits() <
808 Int64Ty->getScalarSizeInBits())
809 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
810 Initializers.push_back(C);
811 }
812 llvm::sort(drop_begin(Initializers, 2),
813 [](const Constant *A, const Constant *B) {
814 return cast<ConstantInt>(A)->getLimitedValue() <
815 cast<ConstantInt>(B)->getLimitedValue();
816 });
817 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
818 GlobalVariable *GV = new GlobalVariable(
819 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
820 ConstantArray::get(ArrayOfInt64Ty, Initializers),
821 "__sancov_gen_cov_switch_values");
822 IRB.CreateCall(SanCovTraceSwitchFunction,
823 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
824 }
825 }
826 }
827
InjectTraceForDiv(Function &,ArrayRef<BinaryOperator * > DivTraceTargets)828 void ModuleSanitizerCoverage::InjectTraceForDiv(
829 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
830 for (auto BO : DivTraceTargets) {
831 IRBuilder<> IRB(BO);
832 Value *A1 = BO->getOperand(1);
833 if (isa<ConstantInt>(A1)) continue;
834 if (!A1->getType()->isIntegerTy())
835 continue;
836 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
837 int CallbackIdx = TypeSize == 32 ? 0 :
838 TypeSize == 64 ? 1 : -1;
839 if (CallbackIdx < 0) continue;
840 auto Ty = Type::getIntNTy(*C, TypeSize);
841 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
842 {IRB.CreateIntCast(A1, Ty, true)});
843 }
844 }
845
InjectTraceForGep(Function &,ArrayRef<GetElementPtrInst * > GepTraceTargets)846 void ModuleSanitizerCoverage::InjectTraceForGep(
847 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
848 for (auto GEP : GepTraceTargets) {
849 IRBuilder<> IRB(GEP);
850 for (Use &Idx : GEP->indices())
851 if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
852 IRB.CreateCall(SanCovTraceGepFunction,
853 {IRB.CreateIntCast(Idx, IntptrTy, true)});
854 }
855 }
856
InjectTraceForCmp(Function &,ArrayRef<Instruction * > CmpTraceTargets)857 void ModuleSanitizerCoverage::InjectTraceForCmp(
858 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
859 for (auto I : CmpTraceTargets) {
860 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
861 IRBuilder<> IRB(ICMP);
862 Value *A0 = ICMP->getOperand(0);
863 Value *A1 = ICMP->getOperand(1);
864 if (!A0->getType()->isIntegerTy())
865 continue;
866 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
867 int CallbackIdx = TypeSize == 8 ? 0 :
868 TypeSize == 16 ? 1 :
869 TypeSize == 32 ? 2 :
870 TypeSize == 64 ? 3 : -1;
871 if (CallbackIdx < 0) continue;
872 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
873 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
874 bool FirstIsConst = isa<ConstantInt>(A0);
875 bool SecondIsConst = isa<ConstantInt>(A1);
876 // If both are const, then we don't need such a comparison.
877 if (FirstIsConst && SecondIsConst) continue;
878 // If only one is const, then make it the first callback argument.
879 if (FirstIsConst || SecondIsConst) {
880 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
881 if (SecondIsConst)
882 std::swap(A0, A1);
883 }
884
885 auto Ty = Type::getIntNTy(*C, TypeSize);
886 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
887 IRB.CreateIntCast(A1, Ty, true)});
888 }
889 }
890 }
891
InjectCoverageAtBlock(Function & F,BasicBlock & BB,size_t Idx,bool IsLeafFunc)892 void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
893 size_t Idx,
894 bool IsLeafFunc) {
895 BasicBlock::iterator IP = BB.getFirstInsertionPt();
896 bool IsEntryBB = &BB == &F.getEntryBlock();
897 DebugLoc EntryLoc;
898 if (IsEntryBB) {
899 if (auto SP = F.getSubprogram())
900 EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
901 // Keep static allocas and llvm.localescape calls in the entry block. Even
902 // if we aren't splitting the block, it's nice for allocas to be before
903 // calls.
904 IP = PrepareToSplitEntryBlock(BB, IP);
905 } else {
906 EntryLoc = IP->getDebugLoc();
907 if (!EntryLoc)
908 if (auto *SP = F.getSubprogram())
909 EntryLoc = DILocation::get(SP->getContext(), 0, 0, SP);
910 }
911
912 IRBuilder<> IRB(&*IP);
913 IRB.SetCurrentDebugLocation(EntryLoc);
914 if (Options.TracePC) {
915 IRB.CreateCall(SanCovTracePC)
916 ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
917 }
918 if (Options.TracePCGuard) {
919 auto GuardPtr = IRB.CreateIntToPtr(
920 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
921 ConstantInt::get(IntptrTy, Idx * 4)),
922 Int32PtrTy);
923 IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
924 }
925 if (Options.Inline8bitCounters) {
926 auto CounterPtr = IRB.CreateGEP(
927 Function8bitCounterArray->getValueType(), Function8bitCounterArray,
928 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
929 auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
930 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
931 auto Store = IRB.CreateStore(Inc, CounterPtr);
932 SetNoSanitizeMetadata(Load);
933 SetNoSanitizeMetadata(Store);
934 }
935 if (Options.InlineBoolFlag) {
936 auto FlagPtr = IRB.CreateGEP(
937 FunctionBoolArray->getValueType(), FunctionBoolArray,
938 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
939 auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
940 auto ThenTerm =
941 SplitBlockAndInsertIfThen(IRB.CreateIsNull(Load), &*IP, false);
942 IRBuilder<> ThenIRB(ThenTerm);
943 auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
944 SetNoSanitizeMetadata(Load);
945 SetNoSanitizeMetadata(Store);
946 }
947 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
948 // Check stack depth. If it's the deepest so far, record it.
949 Module *M = F.getParent();
950 Function *GetFrameAddr = Intrinsic::getDeclaration(
951 M, Intrinsic::frameaddress,
952 IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
953 auto FrameAddrPtr =
954 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
955 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
956 auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
957 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
958 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
959 IRBuilder<> ThenIRB(ThenTerm);
960 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
961 SetNoSanitizeMetadata(LowestStack);
962 SetNoSanitizeMetadata(Store);
963 }
964 }
965
966 std::string
getSectionName(const std::string & Section) const967 ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
968 if (TargetTriple.isOSBinFormatCOFF()) {
969 if (Section == SanCovCountersSectionName)
970 return ".SCOV$CM";
971 if (Section == SanCovBoolFlagSectionName)
972 return ".SCOV$BM";
973 if (Section == SanCovPCsSectionName)
974 return ".SCOVP$M";
975 return ".SCOV$GM"; // For SanCovGuardsSectionName.
976 }
977 if (TargetTriple.isOSBinFormatMachO())
978 return "__DATA,__" + Section;
979 return "__" + Section;
980 }
981
982 std::string
getSectionStart(const std::string & Section) const983 ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
984 if (TargetTriple.isOSBinFormatMachO())
985 return "\1section$start$__DATA$__" + Section;
986 return "__start___" + Section;
987 }
988
989 std::string
getSectionEnd(const std::string & Section) const990 ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
991 if (TargetTriple.isOSBinFormatMachO())
992 return "\1section$end$__DATA$__" + Section;
993 return "__stop___" + Section;
994 }
995
996 char ModuleSanitizerCoverageLegacyPass::ID = 0;
997 INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov",
998 "Pass for instrumenting coverage on functions", false,
999 false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)1000 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1001 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
1002 INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov",
1003 "Pass for instrumenting coverage on functions", false,
1004 false)
1005 ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass(
1006 const SanitizerCoverageOptions &Options,
1007 const std::vector<std::string> &AllowlistFiles,
1008 const std::vector<std::string> &BlocklistFiles) {
1009 return new ModuleSanitizerCoverageLegacyPass(Options, AllowlistFiles,
1010 BlocklistFiles);
1011 }
1012