xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision 7ce60324321a34c49aaf4f540038c6184253502c)
1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Coverage instrumentation done on LLVM IR level, works with Sanitizers.
11 //
12 //===----------------------------------------------------------------------===//
13 
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/CallSite.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/MDBuilder.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Transforms/Instrumentation.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Transforms/Utils/ModuleUtils.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "sancov"
44 
45 static const char *const SanCovTracePCIndirName =
46     "__sanitizer_cov_trace_pc_indir";
47 static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
48 static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
49 static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
50 static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
51 static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
52 static const char *const SanCovTraceConstCmp1 =
53     "__sanitizer_cov_trace_const_cmp1";
54 static const char *const SanCovTraceConstCmp2 =
55     "__sanitizer_cov_trace_const_cmp2";
56 static const char *const SanCovTraceConstCmp4 =
57     "__sanitizer_cov_trace_const_cmp4";
58 static const char *const SanCovTraceConstCmp8 =
59     "__sanitizer_cov_trace_const_cmp8";
60 static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
61 static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
62 static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
63 static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
64 static const char *const SanCovModuleCtorName = "sancov.module_ctor";
65 static const uint64_t SanCtorAndDtorPriority = 2;
66 
67 static const char *const SanCovTracePCGuardName =
68     "__sanitizer_cov_trace_pc_guard";
69 static const char *const SanCovTracePCGuardInitName =
70     "__sanitizer_cov_trace_pc_guard_init";
71 static const char *const SanCov8bitCountersInitName =
72     "__sanitizer_cov_8bit_counters_init";
73 static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
74 
75 static const char *const SanCovGuardsSectionName = "sancov_guards";
76 static const char *const SanCovCountersSectionName = "sancov_cntrs";
77 static const char *const SanCovPCsSectionName = "sancov_pcs";
78 
79 static const char *const SanCovLowestStackName = "__sancov_lowest_stack";
80 
81 static cl::opt<int> ClCoverageLevel(
82     "sanitizer-coverage-level",
83     cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
84              "3: all blocks and critical edges"),
85     cl::Hidden, cl::init(0));
86 
87 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
88                                cl::desc("Experimental pc tracing"), cl::Hidden,
89                                cl::init(false));
90 
91 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
92                                     cl::desc("pc tracing with a guard"),
93                                     cl::Hidden, cl::init(false));
94 
95 // 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.
100 static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
101                                      cl::desc("create a static PC table"),
102                                      cl::Hidden, cl::init(false));
103 
104 static 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));
108 
109 static cl::opt<bool>
110     ClCMPTracing("sanitizer-coverage-trace-compares",
111                  cl::desc("Tracing of CMP and similar instructions"),
112                  cl::Hidden, cl::init(false));
113 
114 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
115                                   cl::desc("Tracing of DIV instructions"),
116                                   cl::Hidden, cl::init(false));
117 
118 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
119                                   cl::desc("Tracing of GEP instructions"),
120                                   cl::Hidden, cl::init(false));
121 
122 static cl::opt<bool>
123     ClPruneBlocks("sanitizer-coverage-prune-blocks",
124                   cl::desc("Reduce the number of instrumented blocks"),
125                   cl::Hidden, cl::init(true));
126 
127 static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
128                                   cl::desc("max stack depth tracing"),
129                                   cl::Hidden, cl::init(false));
130 
131 namespace {
132 
133 SanitizerCoverageOptions 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 
156 SanitizerCoverageOptions 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;
161   Options.TraceCmp |= ClCMPTracing;
162   Options.TraceDiv |= ClDIVTracing;
163   Options.TraceGep |= ClGEPTracing;
164   Options.TracePC |= ClTracePC;
165   Options.TracePCGuard |= ClTracePCGuard;
166   Options.Inline8bitCounters |= ClInline8bitCounters;
167   Options.PCTable |= ClCreatePCTable;
168   Options.NoPrune |= !ClPruneBlocks;
169   Options.StackDepth |= ClStackDepth;
170   if (!Options.TracePCGuard && !Options.TracePC &&
171       !Options.Inline8bitCounters && !Options.StackDepth)
172     Options.TracePCGuard = true; // TracePCGuard is default.
173   return Options;
174 }
175 
176 class SanitizerCoverageModule : public ModulePass {
177 public:
178   SanitizerCoverageModule(
179       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
180       : ModulePass(ID), Options(OverrideFromCL(Options)) {
181     initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
182   }
183   bool runOnModule(Module &M) override;
184   bool runOnFunction(Function &F);
185   static char ID; // Pass identification, replacement for typeid
186   StringRef getPassName() const override { return "SanitizerCoverageModule"; }
187 
188   void getAnalysisUsage(AnalysisUsage &AU) const override {
189     AU.addRequired<DominatorTreeWrapperPass>();
190     AU.addRequired<PostDominatorTreeWrapperPass>();
191   }
192 
193 private:
194   void InjectCoverageForIndirectCalls(Function &F,
195                                       ArrayRef<Instruction *> IndirCalls);
196   void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
197   void InjectTraceForDiv(Function &F,
198                          ArrayRef<BinaryOperator *> DivTraceTargets);
199   void InjectTraceForGep(Function &F,
200                          ArrayRef<GetElementPtrInst *> GepTraceTargets);
201   void InjectTraceForSwitch(Function &F,
202                             ArrayRef<Instruction *> SwitchTraceTargets);
203   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
204                       bool IsLeafFunc = true);
205   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
206                                                     Function &F, Type *Ty,
207                                                     const char *Section);
208   GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
209   void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
210   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
211                              bool IsLeafFunc = true);
212   Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
213                                        Type *Ty, const char *Section);
214   std::pair<GlobalVariable *, GlobalVariable *>
215   CreateSecStartEnd(Module &M, const char *Section, Type *Ty);
216 
217   void SetNoSanitizeMetadata(Instruction *I) {
218     I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
219                    MDNode::get(*C, None));
220   }
221 
222   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;
225   Function *SanCovTracePCIndir;
226   Function *SanCovTracePC, *SanCovTracePCGuard;
227   Function *SanCovTraceCmpFunction[4];
228   Function *SanCovTraceConstCmpFunction[4];
229   Function *SanCovTraceDivFunction[2];
230   Function *SanCovTraceGepFunction;
231   Function *SanCovTraceSwitchFunction;
232   GlobalVariable *SanCovLowestStack;
233   InlineAsm *EmptyAsm;
234   Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
235       *Int16Ty, *Int8Ty, *Int8PtrTy;
236   Module *CurModule;
237   Triple TargetTriple;
238   LLVMContext *C;
239   const DataLayout *DL;
240 
241   GlobalVariable *FunctionGuardArray;  // for trace-pc-guard.
242   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
243   GlobalVariable *FunctionPCsArray;  // for pc-table.
244   SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
245   SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
246 
247   SanitizerCoverageOptions Options;
248 };
249 
250 } // namespace
251 
252 std::pair<GlobalVariable *, GlobalVariable *>
253 SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
254                                            Type *Ty) {
255   GlobalVariable *SecStart =
256       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
257                          getSectionStart(Section));
258   SecStart->setVisibility(GlobalValue::HiddenVisibility);
259   GlobalVariable *SecEnd =
260       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
261                          nullptr, getSectionEnd(Section));
262   SecEnd->setVisibility(GlobalValue::HiddenVisibility);
263 
264   return std::make_pair(SecStart, SecEnd);
265 }
266 
267 
268 Function *SanitizerCoverageModule::CreateInitCallsForSections(
269     Module &M, const char *InitFunctionName, Type *Ty,
270     const char *Section) {
271   IRBuilder<> IRB(M.getContext());
272   auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
273   auto SecStart = SecStartEnd.first;
274   auto SecEnd = SecStartEnd.second;
275   Function *CtorFunc;
276   Value *SecStartPtr = nullptr;
277   // Account for the fact that on windows-msvc __start_* symbols actually
278   // point to a uint64_t before the start of the array.
279   if (TargetTriple.getObjectFormat() == Triple::COFF) {
280     auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
281     auto GEP = IRB.CreateGEP(SecStartI8Ptr,
282                              ConstantInt::get(IntptrTy, sizeof(uint64_t)));
283     SecStartPtr = IRB.CreatePointerCast(GEP, Ty);
284   } else {
285     SecStartPtr = IRB.CreatePointerCast(SecStart, Ty);
286   }
287   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
288       M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
289       {SecStartPtr, IRB.CreatePointerCast(SecEnd, Ty)});
290 
291   if (TargetTriple.supportsCOMDAT()) {
292     // Use comdat to dedup CtorFunc.
293     CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
294     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
295   } else {
296     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
297   }
298   return CtorFunc;
299 }
300 
301 bool SanitizerCoverageModule::runOnModule(Module &M) {
302   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
303     return false;
304   C = &(M.getContext());
305   DL = &M.getDataLayout();
306   CurModule = &M;
307   TargetTriple = Triple(M.getTargetTriple());
308   FunctionGuardArray = nullptr;
309   Function8bitCounterArray = nullptr;
310   FunctionPCsArray = nullptr;
311   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
312   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
313   Type *VoidTy = Type::getVoidTy(*C);
314   IRBuilder<> IRB(*C);
315   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
316   Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
317   Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
318   Int64Ty = IRB.getInt64Ty();
319   Int32Ty = IRB.getInt32Ty();
320   Int16Ty = IRB.getInt16Ty();
321   Int8Ty = IRB.getInt8Ty();
322 
323   SanCovTracePCIndir = checkSanitizerInterfaceFunction(
324       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
325   SanCovTraceCmpFunction[0] =
326       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
327           SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
328   SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
329       M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
330                             IRB.getInt16Ty()));
331   SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
332       M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
333                             IRB.getInt32Ty()));
334   SanCovTraceCmpFunction[3] =
335       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
336           SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
337 
338   SanCovTraceConstCmpFunction[0] =
339       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
340           SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
341   SanCovTraceConstCmpFunction[1] =
342       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
343           SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
344   SanCovTraceConstCmpFunction[2] =
345       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
346           SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
347   SanCovTraceConstCmpFunction[3] =
348       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
349           SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
350 
351   SanCovTraceDivFunction[0] =
352       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
353           SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
354   SanCovTraceDivFunction[1] =
355       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
356           SanCovTraceDiv8, VoidTy, Int64Ty));
357   SanCovTraceGepFunction =
358       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
359           SanCovTraceGep, VoidTy, IntptrTy));
360   SanCovTraceSwitchFunction =
361       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
362           SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
363 
364   Constant *SanCovLowestStackConstant =
365       M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
366   SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
367   SanCovLowestStack->setThreadLocalMode(
368       GlobalValue::ThreadLocalMode::InitialExecTLSModel);
369   if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
370     SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
371 
372   // Make sure smaller parameters are zero-extended to i64 as required by the
373   // x86_64 ABI.
374   if (TargetTriple.getArch() == Triple::x86_64) {
375     for (int i = 0; i < 3; i++) {
376       SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
377       SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
378       SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
379       SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
380     }
381     SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
382   }
383 
384 
385   // We insert an empty inline asm after cov callbacks to avoid callback merge.
386   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
387                             StringRef(""), StringRef(""),
388                             /*hasSideEffects=*/true);
389 
390   SanCovTracePC = checkSanitizerInterfaceFunction(
391       M.getOrInsertFunction(SanCovTracePCName, VoidTy));
392   SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
393       SanCovTracePCGuardName, VoidTy, Int32PtrTy));
394 
395   for (auto &F : M)
396     runOnFunction(F);
397 
398   Function *Ctor = nullptr;
399 
400   if (FunctionGuardArray)
401     Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
402                                       SanCovGuardsSectionName);
403   if (Function8bitCounterArray)
404     Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
405                                       SanCovCountersSectionName);
406   if (Ctor && Options.PCTable) {
407     auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
408     Function *InitFunction = declareSanitizerInitFunction(
409         M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
410     IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
411     Value *SecStartPtr = nullptr;
412     // Account for the fact that on windows-msvc __start_pc_table actually
413     // points to a uint64_t before the start of the PC table.
414     if (TargetTriple.getObjectFormat() == Triple::COFF) {
415       auto SecStartI8Ptr = IRB.CreatePointerCast(SecStartEnd.first, Int8PtrTy);
416       auto GEP = IRB.CreateGEP(SecStartI8Ptr,
417                                ConstantInt::get(IntptrTy, sizeof(uint64_t)));
418       SecStartPtr = IRB.CreatePointerCast(GEP, IntptrPtrTy);
419     } else {
420       SecStartPtr = IRB.CreatePointerCast(SecStartEnd.first, IntptrPtrTy);
421     }
422     IRBCtor.CreateCall(
423         InitFunction,
424         {SecStartPtr, IRB.CreatePointerCast(SecStartEnd.second, IntptrPtrTy)});
425   }
426   // We don't reference these arrays directly in any of our runtime functions,
427   // so we need to prevent them from being dead stripped.
428   if (TargetTriple.isOSBinFormatMachO())
429     appendToUsed(M, GlobalsToAppendToUsed);
430   appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
431   return true;
432 }
433 
434 // True if block has successors and it dominates all of them.
435 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
436   if (succ_begin(BB) == succ_end(BB))
437     return false;
438 
439   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
440     if (!DT->dominates(BB, SUCC))
441       return false;
442   }
443 
444   return true;
445 }
446 
447 // True if block has predecessors and it postdominates all of them.
448 static bool isFullPostDominator(const BasicBlock *BB,
449                                 const PostDominatorTree *PDT) {
450   if (pred_begin(BB) == pred_end(BB))
451     return false;
452 
453   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
454     if (!PDT->dominates(BB, PRED))
455       return false;
456   }
457 
458   return true;
459 }
460 
461 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
462                                   const DominatorTree *DT,
463                                   const PostDominatorTree *PDT,
464                                   const SanitizerCoverageOptions &Options) {
465   // Don't insert coverage for unreachable blocks: we will never call
466   // __sanitizer_cov() for them, so counting them in
467   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
468   // percentage. Also, unreachable instructions frequently have no debug
469   // locations.
470   if (isa<UnreachableInst>(BB->getTerminator()))
471     return false;
472 
473   // Don't insert coverage into blocks without a valid insertion point
474   // (catchswitch blocks).
475   if (BB->getFirstInsertionPt() == BB->end())
476     return false;
477 
478   if (Options.NoPrune || &F.getEntryBlock() == BB)
479     return true;
480 
481   if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
482       &F.getEntryBlock() != BB)
483     return false;
484 
485   // Do not instrument full dominators, or full post-dominators with multiple
486   // predecessors.
487   return !isFullDominator(BB, DT)
488     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
489 }
490 
491 bool SanitizerCoverageModule::runOnFunction(Function &F) {
492   if (F.empty())
493     return false;
494   if (F.getName().find(".module_ctor") != std::string::npos)
495     return false; // Should not instrument sanitizer init functions.
496   if (F.getName().startswith("__sanitizer_"))
497     return false;  // Don't instrument __sanitizer_* callbacks.
498   // Don't touch available_externally functions, their actual body is elewhere.
499   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
500     return false;
501   // Don't instrument MSVC CRT configuration helpers. They may run before normal
502   // initialization.
503   if (F.getName() == "__local_stdio_printf_options" ||
504       F.getName() == "__local_stdio_scanf_options")
505     return false;
506   if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
507     return false;
508   // Don't instrument functions using SEH for now. Splitting basic blocks like
509   // we do for coverage breaks WinEHPrepare.
510   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
511   if (F.hasPersonalityFn() &&
512       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
513     return false;
514   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
515     SplitAllCriticalEdges(F);
516   SmallVector<Instruction *, 8> IndirCalls;
517   SmallVector<BasicBlock *, 16> BlocksToInstrument;
518   SmallVector<Instruction *, 8> CmpTraceTargets;
519   SmallVector<Instruction *, 8> SwitchTraceTargets;
520   SmallVector<BinaryOperator *, 8> DivTraceTargets;
521   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
522 
523   const DominatorTree *DT =
524       &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
525   const PostDominatorTree *PDT =
526       &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
527   bool IsLeafFunc = true;
528 
529   for (auto &BB : F) {
530     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
531       BlocksToInstrument.push_back(&BB);
532     for (auto &Inst : BB) {
533       if (Options.IndirectCalls) {
534         CallSite CS(&Inst);
535         if (CS && !CS.getCalledFunction())
536           IndirCalls.push_back(&Inst);
537       }
538       if (Options.TraceCmp) {
539         if (isa<ICmpInst>(&Inst))
540           CmpTraceTargets.push_back(&Inst);
541         if (isa<SwitchInst>(&Inst))
542           SwitchTraceTargets.push_back(&Inst);
543       }
544       if (Options.TraceDiv)
545         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
546           if (BO->getOpcode() == Instruction::SDiv ||
547               BO->getOpcode() == Instruction::UDiv)
548             DivTraceTargets.push_back(BO);
549       if (Options.TraceGep)
550         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
551           GepTraceTargets.push_back(GEP);
552       if (Options.StackDepth)
553         if (isa<InvokeInst>(Inst) ||
554             (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
555           IsLeafFunc = false;
556     }
557   }
558 
559   InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
560   InjectCoverageForIndirectCalls(F, IndirCalls);
561   InjectTraceForCmp(F, CmpTraceTargets);
562   InjectTraceForSwitch(F, SwitchTraceTargets);
563   InjectTraceForDiv(F, DivTraceTargets);
564   InjectTraceForGep(F, GepTraceTargets);
565   return true;
566 }
567 
568 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
569     size_t NumElements, Function &F, Type *Ty, const char *Section) {
570   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
571   auto Array = new GlobalVariable(
572       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
573       Constant::getNullValue(ArrayTy), "__sancov_gen_");
574   if (auto Comdat = F.getComdat()) {
575     Array->setComdat(Comdat);
576   } else if (TargetTriple.isOSBinFormatELF()) {
577     // TODO: Refactor into a helper function and use it in ASan.
578     assert(F.hasName());
579     std::string Name = F.getName();
580     if (F.hasLocalLinkage()) {
581       std::string ModuleId = getUniqueModuleId(CurModule);
582       Name += ModuleId.empty() ? CurModule->getModuleIdentifier() : ModuleId;
583     }
584     Comdat = CurModule->getOrInsertComdat(Name);
585     // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
586     // linkage to internal linkage so that a symbol table entry is emitted. This
587     // is necessary in order to create the comdat group.
588     if (TargetTriple.isOSBinFormatCOFF()) {
589       Comdat->setSelectionKind(Comdat::NoDuplicates);
590       if (F.hasPrivateLinkage())
591         F.setLinkage(GlobalValue::InternalLinkage);
592     }
593     F.setComdat(Comdat);
594     Array->setComdat(Comdat);
595   }
596   Array->setSection(getSectionName(Section));
597   Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
598                                         : Ty->getPrimitiveSizeInBits() / 8);
599   GlobalsToAppendToCompilerUsed.push_back(Array);
600   MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
601   Array->addMetadata(LLVMContext::MD_associated, *MD);
602   return Array;
603 }
604 
605 GlobalVariable *
606 SanitizerCoverageModule::CreatePCArray(Function &F,
607                                        ArrayRef<BasicBlock *> AllBlocks) {
608   size_t N = AllBlocks.size();
609   assert(N);
610   SmallVector<Constant *, 32> PCs;
611   IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
612   for (size_t i = 0; i < N; i++) {
613     if (&F.getEntryBlock() == AllBlocks[i]) {
614       PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
615       PCs.push_back((Constant *)IRB.CreateIntToPtr(
616           ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
617     } else {
618       PCs.push_back((Constant *)IRB.CreatePointerCast(
619           BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
620       PCs.push_back((Constant *)IRB.CreateIntToPtr(
621           ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
622     }
623   }
624   auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
625                                                     SanCovPCsSectionName);
626   PCArray->setInitializer(
627       ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
628   PCArray->setConstant(true);
629 
630   return PCArray;
631 }
632 
633 void SanitizerCoverageModule::CreateFunctionLocalArrays(
634     Function &F, ArrayRef<BasicBlock *> AllBlocks) {
635   if (Options.TracePCGuard) {
636     FunctionGuardArray = CreateFunctionLocalArrayInSection(
637         AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
638     GlobalsToAppendToUsed.push_back(FunctionGuardArray);
639   }
640   if (Options.Inline8bitCounters)
641     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
642         AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
643   if (Options.PCTable)
644     FunctionPCsArray = CreatePCArray(F, AllBlocks);
645 }
646 
647 bool SanitizerCoverageModule::InjectCoverage(Function &F,
648                                              ArrayRef<BasicBlock *> AllBlocks,
649                                              bool IsLeafFunc) {
650   if (AllBlocks.empty()) return false;
651   CreateFunctionLocalArrays(F, AllBlocks);
652   for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
653     InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
654   return true;
655 }
656 
657 // On every indirect call we call a run-time function
658 // __sanitizer_cov_indir_call* with two parameters:
659 //   - callee address,
660 //   - global cache array that contains CacheSize pointers (zero-initialized).
661 //     The cache is used to speed up recording the caller-callee pairs.
662 // The address of the caller is passed implicitly via caller PC.
663 // CacheSize is encoded in the name of the run-time function.
664 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
665     Function &F, ArrayRef<Instruction *> IndirCalls) {
666   if (IndirCalls.empty())
667     return;
668   assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
669   for (auto I : IndirCalls) {
670     IRBuilder<> IRB(I);
671     CallSite CS(I);
672     Value *Callee = CS.getCalledValue();
673     if (isa<InlineAsm>(Callee))
674       continue;
675     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
676   }
677 }
678 
679 // For every switch statement we insert a call:
680 // __sanitizer_cov_trace_switch(CondValue,
681 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
682 
683 void SanitizerCoverageModule::InjectTraceForSwitch(
684     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
685   for (auto I : SwitchTraceTargets) {
686     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
687       IRBuilder<> IRB(I);
688       SmallVector<Constant *, 16> Initializers;
689       Value *Cond = SI->getCondition();
690       if (Cond->getType()->getScalarSizeInBits() >
691           Int64Ty->getScalarSizeInBits())
692         continue;
693       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
694       Initializers.push_back(
695           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
696       if (Cond->getType()->getScalarSizeInBits() <
697           Int64Ty->getScalarSizeInBits())
698         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
699       for (auto It : SI->cases()) {
700         Constant *C = It.getCaseValue();
701         if (C->getType()->getScalarSizeInBits() <
702             Int64Ty->getScalarSizeInBits())
703           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
704         Initializers.push_back(C);
705       }
706       llvm::sort(Initializers.begin() + 2, Initializers.end(),
707                  [](const Constant *A, const Constant *B) {
708                    return cast<ConstantInt>(A)->getLimitedValue() <
709                           cast<ConstantInt>(B)->getLimitedValue();
710                  });
711       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
712       GlobalVariable *GV = new GlobalVariable(
713           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
714           ConstantArray::get(ArrayOfInt64Ty, Initializers),
715           "__sancov_gen_cov_switch_values");
716       IRB.CreateCall(SanCovTraceSwitchFunction,
717                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
718     }
719   }
720 }
721 
722 void SanitizerCoverageModule::InjectTraceForDiv(
723     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
724   for (auto BO : DivTraceTargets) {
725     IRBuilder<> IRB(BO);
726     Value *A1 = BO->getOperand(1);
727     if (isa<ConstantInt>(A1)) continue;
728     if (!A1->getType()->isIntegerTy())
729       continue;
730     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
731     int CallbackIdx = TypeSize == 32 ? 0 :
732         TypeSize == 64 ? 1 : -1;
733     if (CallbackIdx < 0) continue;
734     auto Ty = Type::getIntNTy(*C, TypeSize);
735     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
736                    {IRB.CreateIntCast(A1, Ty, true)});
737   }
738 }
739 
740 void SanitizerCoverageModule::InjectTraceForGep(
741     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
742   for (auto GEP : GepTraceTargets) {
743     IRBuilder<> IRB(GEP);
744     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
745       if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
746         IRB.CreateCall(SanCovTraceGepFunction,
747                        {IRB.CreateIntCast(*I, IntptrTy, true)});
748   }
749 }
750 
751 void SanitizerCoverageModule::InjectTraceForCmp(
752     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
753   for (auto I : CmpTraceTargets) {
754     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
755       IRBuilder<> IRB(ICMP);
756       Value *A0 = ICMP->getOperand(0);
757       Value *A1 = ICMP->getOperand(1);
758       if (!A0->getType()->isIntegerTy())
759         continue;
760       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
761       int CallbackIdx = TypeSize == 8 ? 0 :
762                         TypeSize == 16 ? 1 :
763                         TypeSize == 32 ? 2 :
764                         TypeSize == 64 ? 3 : -1;
765       if (CallbackIdx < 0) continue;
766       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
767       auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
768       bool FirstIsConst = isa<ConstantInt>(A0);
769       bool SecondIsConst = isa<ConstantInt>(A1);
770       // If both are const, then we don't need such a comparison.
771       if (FirstIsConst && SecondIsConst) continue;
772       // If only one is const, then make it the first callback argument.
773       if (FirstIsConst || SecondIsConst) {
774         CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
775         if (SecondIsConst)
776           std::swap(A0, A1);
777       }
778 
779       auto Ty = Type::getIntNTy(*C, TypeSize);
780       IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
781               IRB.CreateIntCast(A1, Ty, true)});
782     }
783   }
784 }
785 
786 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
787                                                     size_t Idx,
788                                                     bool IsLeafFunc) {
789   BasicBlock::iterator IP = BB.getFirstInsertionPt();
790   bool IsEntryBB = &BB == &F.getEntryBlock();
791   DebugLoc EntryLoc;
792   if (IsEntryBB) {
793     if (auto SP = F.getSubprogram())
794       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
795     // Keep static allocas and llvm.localescape calls in the entry block.  Even
796     // if we aren't splitting the block, it's nice for allocas to be before
797     // calls.
798     IP = PrepareToSplitEntryBlock(BB, IP);
799   } else {
800     EntryLoc = IP->getDebugLoc();
801   }
802 
803   IRBuilder<> IRB(&*IP);
804   IRB.SetCurrentDebugLocation(EntryLoc);
805   if (Options.TracePC) {
806     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
807     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
808   }
809   if (Options.TracePCGuard) {
810     auto GuardPtr = IRB.CreateIntToPtr(
811         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
812                       ConstantInt::get(IntptrTy, Idx * 4)),
813         Int32PtrTy);
814     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
815     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
816   }
817   if (Options.Inline8bitCounters) {
818     auto CounterPtr = IRB.CreateGEP(
819         Function8bitCounterArray,
820         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
821     auto Load = IRB.CreateLoad(CounterPtr);
822     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
823     auto Store = IRB.CreateStore(Inc, CounterPtr);
824     SetNoSanitizeMetadata(Load);
825     SetNoSanitizeMetadata(Store);
826   }
827   if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
828     // Check stack depth.  If it's the deepest so far, record it.
829     Function *GetFrameAddr =
830         Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
831     auto FrameAddrPtr =
832         IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
833     auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
834     auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
835     auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
836     auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
837     IRBuilder<> ThenIRB(ThenTerm);
838     auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
839     SetNoSanitizeMetadata(LowestStack);
840     SetNoSanitizeMetadata(Store);
841   }
842 }
843 
844 std::string
845 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
846   if (TargetTriple.getObjectFormat() == Triple::COFF) {
847     if (Section == SanCovCountersSectionName)
848       return ".SCOV$CM";
849     if (Section == SanCovPCsSectionName)
850       return ".SCOVP$M";
851     return ".SCOV$GM"; // For SanCovGuardsSectionName.
852   }
853   if (TargetTriple.isOSBinFormatMachO())
854     return "__DATA,__" + Section;
855   return "__" + Section;
856 }
857 
858 std::string
859 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
860   if (TargetTriple.isOSBinFormatMachO())
861     return "\1section$start$__DATA$__" + Section;
862   return "__start___" + Section;
863 }
864 
865 std::string
866 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
867   if (TargetTriple.isOSBinFormatMachO())
868     return "\1section$end$__DATA$__" + Section;
869   return "__stop___" + Section;
870 }
871 
872 
873 char SanitizerCoverageModule::ID = 0;
874 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
875                       "SanitizerCoverage: TODO."
876                       "ModulePass",
877                       false, false)
878 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
879 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
880 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
881                     "SanitizerCoverage: TODO."
882                     "ModulePass",
883                     false, false)
884 ModulePass *llvm::createSanitizerCoverageModulePass(
885     const SanitizerCoverageOptions &Options) {
886   return new SanitizerCoverageModule(Options);
887 }
888