xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision c6fff3b6f5b937b97a427e5e52ece058ce71b55b)
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   auto SecStartPtr = IRB.CreatePointerCast(SecStart, Ty);
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     SecStartPtr = IRB.CreateAdd(SecStartPtr,
281                                 ConstantInt::get(IntptrTy, sizeof(uint64_t)));
282   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
283       M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
284       {SecStartPtr, IRB.CreatePointerCast(SecEnd, Ty)});
285 
286   if (TargetTriple.supportsCOMDAT()) {
287     // Use comdat to dedup CtorFunc.
288     CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
289     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
290   } else {
291     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
292   }
293   return CtorFunc;
294 }
295 
296 bool SanitizerCoverageModule::runOnModule(Module &M) {
297   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
298     return false;
299   C = &(M.getContext());
300   DL = &M.getDataLayout();
301   CurModule = &M;
302   TargetTriple = Triple(M.getTargetTriple());
303   FunctionGuardArray = nullptr;
304   Function8bitCounterArray = nullptr;
305   FunctionPCsArray = nullptr;
306   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
307   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
308   Type *VoidTy = Type::getVoidTy(*C);
309   IRBuilder<> IRB(*C);
310   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
311   Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
312   Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
313   Int64Ty = IRB.getInt64Ty();
314   Int32Ty = IRB.getInt32Ty();
315   Int16Ty = IRB.getInt16Ty();
316   Int8Ty = IRB.getInt8Ty();
317 
318   SanCovTracePCIndir = checkSanitizerInterfaceFunction(
319       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
320   SanCovTraceCmpFunction[0] =
321       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
322           SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
323   SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
324       M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
325                             IRB.getInt16Ty()));
326   SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
327       M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
328                             IRB.getInt32Ty()));
329   SanCovTraceCmpFunction[3] =
330       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
331           SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
332 
333   SanCovTraceConstCmpFunction[0] =
334       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
335           SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
336   SanCovTraceConstCmpFunction[1] =
337       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
338           SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
339   SanCovTraceConstCmpFunction[2] =
340       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
341           SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
342   SanCovTraceConstCmpFunction[3] =
343       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
344           SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
345 
346   SanCovTraceDivFunction[0] =
347       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
348           SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
349   SanCovTraceDivFunction[1] =
350       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
351           SanCovTraceDiv8, VoidTy, Int64Ty));
352   SanCovTraceGepFunction =
353       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
354           SanCovTraceGep, VoidTy, IntptrTy));
355   SanCovTraceSwitchFunction =
356       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
357           SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
358 
359   Constant *SanCovLowestStackConstant =
360       M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
361   SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
362   SanCovLowestStack->setThreadLocalMode(
363       GlobalValue::ThreadLocalMode::InitialExecTLSModel);
364   if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
365     SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
366 
367   // Make sure smaller parameters are zero-extended to i64 as required by the
368   // x86_64 ABI.
369   if (TargetTriple.getArch() == Triple::x86_64) {
370     for (int i = 0; i < 3; i++) {
371       SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
372       SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
373       SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
374       SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
375     }
376     SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
377   }
378 
379 
380   // We insert an empty inline asm after cov callbacks to avoid callback merge.
381   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
382                             StringRef(""), StringRef(""),
383                             /*hasSideEffects=*/true);
384 
385   SanCovTracePC = checkSanitizerInterfaceFunction(
386       M.getOrInsertFunction(SanCovTracePCName, VoidTy));
387   SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
388       SanCovTracePCGuardName, VoidTy, Int32PtrTy));
389 
390   for (auto &F : M)
391     runOnFunction(F);
392 
393   Function *Ctor = nullptr;
394 
395   if (FunctionGuardArray)
396     Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
397                                       SanCovGuardsSectionName);
398   if (Function8bitCounterArray)
399     Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
400                                       SanCovCountersSectionName);
401   if (Ctor && Options.PCTable) {
402     auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
403     Function *InitFunction = declareSanitizerInitFunction(
404         M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
405     IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
406     auto SecStartPtr = IRB.CreatePointerCast(SecStartEnd.first, IntptrPtrTy);
407     // Account for the fact that on windows-msvc __start_pc_table actually
408     // points to a uint64_t before the start of the PC table.
409     if (TargetTriple.getObjectFormat() == Triple::COFF)
410       SecStartPtr = IRB.CreateAdd(SecStartPtr,
411                                   ConstantInt::get(IntptrTy, sizeof(uint64_t)));
412     IRBCtor.CreateCall(
413         InitFunction,
414         {SecStartPtr, IRB.CreatePointerCast(SecStartEnd.second, IntptrPtrTy)});
415   }
416   // We don't reference these arrays directly in any of our runtime functions,
417   // so we need to prevent them from being dead stripped.
418   if (TargetTriple.isOSBinFormatMachO())
419     appendToUsed(M, GlobalsToAppendToUsed);
420   appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
421   return true;
422 }
423 
424 // True if block has successors and it dominates all of them.
425 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
426   if (succ_begin(BB) == succ_end(BB))
427     return false;
428 
429   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
430     if (!DT->dominates(BB, SUCC))
431       return false;
432   }
433 
434   return true;
435 }
436 
437 // True if block has predecessors and it postdominates all of them.
438 static bool isFullPostDominator(const BasicBlock *BB,
439                                 const PostDominatorTree *PDT) {
440   if (pred_begin(BB) == pred_end(BB))
441     return false;
442 
443   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
444     if (!PDT->dominates(BB, PRED))
445       return false;
446   }
447 
448   return true;
449 }
450 
451 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
452                                   const DominatorTree *DT,
453                                   const PostDominatorTree *PDT,
454                                   const SanitizerCoverageOptions &Options) {
455   // Don't insert coverage for unreachable blocks: we will never call
456   // __sanitizer_cov() for them, so counting them in
457   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
458   // percentage. Also, unreachable instructions frequently have no debug
459   // locations.
460   if (isa<UnreachableInst>(BB->getTerminator()))
461     return false;
462 
463   // Don't insert coverage into blocks without a valid insertion point
464   // (catchswitch blocks).
465   if (BB->getFirstInsertionPt() == BB->end())
466     return false;
467 
468   if (Options.NoPrune || &F.getEntryBlock() == BB)
469     return true;
470 
471   if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
472       &F.getEntryBlock() != BB)
473     return false;
474 
475   // Do not instrument full dominators, or full post-dominators with multiple
476   // predecessors.
477   return !isFullDominator(BB, DT)
478     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
479 }
480 
481 bool SanitizerCoverageModule::runOnFunction(Function &F) {
482   if (F.empty())
483     return false;
484   if (F.getName().find(".module_ctor") != std::string::npos)
485     return false; // Should not instrument sanitizer init functions.
486   if (F.getName().startswith("__sanitizer_"))
487     return false;  // Don't instrument __sanitizer_* callbacks.
488   // Don't touch available_externally functions, their actual body is elewhere.
489   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
490     return false;
491   // Don't instrument MSVC CRT configuration helpers. They may run before normal
492   // initialization.
493   if (F.getName() == "__local_stdio_printf_options" ||
494       F.getName() == "__local_stdio_scanf_options")
495     return false;
496   if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
497     return false;
498   // Don't instrument functions using SEH for now. Splitting basic blocks like
499   // we do for coverage breaks WinEHPrepare.
500   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
501   if (F.hasPersonalityFn() &&
502       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
503     return false;
504   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
505     SplitAllCriticalEdges(F);
506   SmallVector<Instruction *, 8> IndirCalls;
507   SmallVector<BasicBlock *, 16> BlocksToInstrument;
508   SmallVector<Instruction *, 8> CmpTraceTargets;
509   SmallVector<Instruction *, 8> SwitchTraceTargets;
510   SmallVector<BinaryOperator *, 8> DivTraceTargets;
511   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
512 
513   const DominatorTree *DT =
514       &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
515   const PostDominatorTree *PDT =
516       &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
517   bool IsLeafFunc = true;
518 
519   for (auto &BB : F) {
520     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
521       BlocksToInstrument.push_back(&BB);
522     for (auto &Inst : BB) {
523       if (Options.IndirectCalls) {
524         CallSite CS(&Inst);
525         if (CS && !CS.getCalledFunction())
526           IndirCalls.push_back(&Inst);
527       }
528       if (Options.TraceCmp) {
529         if (isa<ICmpInst>(&Inst))
530           CmpTraceTargets.push_back(&Inst);
531         if (isa<SwitchInst>(&Inst))
532           SwitchTraceTargets.push_back(&Inst);
533       }
534       if (Options.TraceDiv)
535         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
536           if (BO->getOpcode() == Instruction::SDiv ||
537               BO->getOpcode() == Instruction::UDiv)
538             DivTraceTargets.push_back(BO);
539       if (Options.TraceGep)
540         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
541           GepTraceTargets.push_back(GEP);
542       if (Options.StackDepth)
543         if (isa<InvokeInst>(Inst) ||
544             (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
545           IsLeafFunc = false;
546     }
547   }
548 
549   InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
550   InjectCoverageForIndirectCalls(F, IndirCalls);
551   InjectTraceForCmp(F, CmpTraceTargets);
552   InjectTraceForSwitch(F, SwitchTraceTargets);
553   InjectTraceForDiv(F, DivTraceTargets);
554   InjectTraceForGep(F, GepTraceTargets);
555   return true;
556 }
557 
558 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
559     size_t NumElements, Function &F, Type *Ty, const char *Section) {
560   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
561   auto Array = new GlobalVariable(
562       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
563       Constant::getNullValue(ArrayTy), "__sancov_gen_");
564   if (auto Comdat = F.getComdat())
565     Array->setComdat(Comdat);
566   Array->setSection(getSectionName(Section));
567   Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
568                                         : Ty->getPrimitiveSizeInBits() / 8);
569   return Array;
570 }
571 
572 GlobalVariable *
573 SanitizerCoverageModule::CreatePCArray(Function &F,
574                                        ArrayRef<BasicBlock *> AllBlocks) {
575   size_t N = AllBlocks.size();
576   assert(N);
577   SmallVector<Constant *, 32> PCs;
578   IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
579   for (size_t i = 0; i < N; i++) {
580     if (&F.getEntryBlock() == AllBlocks[i]) {
581       PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
582       PCs.push_back((Constant *)IRB.CreateIntToPtr(
583           ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
584     } else {
585       PCs.push_back((Constant *)IRB.CreatePointerCast(
586           BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
587       PCs.push_back((Constant *)IRB.CreateIntToPtr(
588           ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
589     }
590   }
591   auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
592                                                     SanCovPCsSectionName);
593   PCArray->setInitializer(
594       ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
595   PCArray->setConstant(true);
596 
597   return PCArray;
598 }
599 
600 void SanitizerCoverageModule::CreateFunctionLocalArrays(
601     Function &F, ArrayRef<BasicBlock *> AllBlocks) {
602   if (Options.TracePCGuard) {
603     FunctionGuardArray = CreateFunctionLocalArrayInSection(
604         AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
605     GlobalsToAppendToUsed.push_back(FunctionGuardArray);
606     GlobalsToAppendToCompilerUsed.push_back(FunctionGuardArray);
607     MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
608     FunctionGuardArray->addMetadata(LLVMContext::MD_associated, *MD);
609   }
610   if (Options.Inline8bitCounters) {
611     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
612         AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
613     GlobalsToAppendToCompilerUsed.push_back(Function8bitCounterArray);
614     MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
615     Function8bitCounterArray->addMetadata(LLVMContext::MD_associated, *MD);
616   }
617   if (Options.PCTable) {
618     FunctionPCsArray = CreatePCArray(F, AllBlocks);
619     GlobalsToAppendToCompilerUsed.push_back(FunctionPCsArray);
620     MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
621     FunctionPCsArray->addMetadata(LLVMContext::MD_associated, *MD);
622   }
623 }
624 
625 bool SanitizerCoverageModule::InjectCoverage(Function &F,
626                                              ArrayRef<BasicBlock *> AllBlocks,
627                                              bool IsLeafFunc) {
628   if (AllBlocks.empty()) return false;
629   CreateFunctionLocalArrays(F, AllBlocks);
630   for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
631     InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
632   return true;
633 }
634 
635 // On every indirect call we call a run-time function
636 // __sanitizer_cov_indir_call* with two parameters:
637 //   - callee address,
638 //   - global cache array that contains CacheSize pointers (zero-initialized).
639 //     The cache is used to speed up recording the caller-callee pairs.
640 // The address of the caller is passed implicitly via caller PC.
641 // CacheSize is encoded in the name of the run-time function.
642 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
643     Function &F, ArrayRef<Instruction *> IndirCalls) {
644   if (IndirCalls.empty())
645     return;
646   assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
647   for (auto I : IndirCalls) {
648     IRBuilder<> IRB(I);
649     CallSite CS(I);
650     Value *Callee = CS.getCalledValue();
651     if (isa<InlineAsm>(Callee))
652       continue;
653     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
654   }
655 }
656 
657 // For every switch statement we insert a call:
658 // __sanitizer_cov_trace_switch(CondValue,
659 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
660 
661 void SanitizerCoverageModule::InjectTraceForSwitch(
662     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
663   for (auto I : SwitchTraceTargets) {
664     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
665       IRBuilder<> IRB(I);
666       SmallVector<Constant *, 16> Initializers;
667       Value *Cond = SI->getCondition();
668       if (Cond->getType()->getScalarSizeInBits() >
669           Int64Ty->getScalarSizeInBits())
670         continue;
671       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
672       Initializers.push_back(
673           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
674       if (Cond->getType()->getScalarSizeInBits() <
675           Int64Ty->getScalarSizeInBits())
676         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
677       for (auto It : SI->cases()) {
678         Constant *C = It.getCaseValue();
679         if (C->getType()->getScalarSizeInBits() <
680             Int64Ty->getScalarSizeInBits())
681           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
682         Initializers.push_back(C);
683       }
684       llvm::sort(Initializers.begin() + 2, Initializers.end(),
685                  [](const Constant *A, const Constant *B) {
686                    return cast<ConstantInt>(A)->getLimitedValue() <
687                           cast<ConstantInt>(B)->getLimitedValue();
688                  });
689       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
690       GlobalVariable *GV = new GlobalVariable(
691           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
692           ConstantArray::get(ArrayOfInt64Ty, Initializers),
693           "__sancov_gen_cov_switch_values");
694       IRB.CreateCall(SanCovTraceSwitchFunction,
695                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
696     }
697   }
698 }
699 
700 void SanitizerCoverageModule::InjectTraceForDiv(
701     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
702   for (auto BO : DivTraceTargets) {
703     IRBuilder<> IRB(BO);
704     Value *A1 = BO->getOperand(1);
705     if (isa<ConstantInt>(A1)) continue;
706     if (!A1->getType()->isIntegerTy())
707       continue;
708     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
709     int CallbackIdx = TypeSize == 32 ? 0 :
710         TypeSize == 64 ? 1 : -1;
711     if (CallbackIdx < 0) continue;
712     auto Ty = Type::getIntNTy(*C, TypeSize);
713     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
714                    {IRB.CreateIntCast(A1, Ty, true)});
715   }
716 }
717 
718 void SanitizerCoverageModule::InjectTraceForGep(
719     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
720   for (auto GEP : GepTraceTargets) {
721     IRBuilder<> IRB(GEP);
722     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
723       if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
724         IRB.CreateCall(SanCovTraceGepFunction,
725                        {IRB.CreateIntCast(*I, IntptrTy, true)});
726   }
727 }
728 
729 void SanitizerCoverageModule::InjectTraceForCmp(
730     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
731   for (auto I : CmpTraceTargets) {
732     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
733       IRBuilder<> IRB(ICMP);
734       Value *A0 = ICMP->getOperand(0);
735       Value *A1 = ICMP->getOperand(1);
736       if (!A0->getType()->isIntegerTy())
737         continue;
738       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
739       int CallbackIdx = TypeSize == 8 ? 0 :
740                         TypeSize == 16 ? 1 :
741                         TypeSize == 32 ? 2 :
742                         TypeSize == 64 ? 3 : -1;
743       if (CallbackIdx < 0) continue;
744       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
745       auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
746       bool FirstIsConst = isa<ConstantInt>(A0);
747       bool SecondIsConst = isa<ConstantInt>(A1);
748       // If both are const, then we don't need such a comparison.
749       if (FirstIsConst && SecondIsConst) continue;
750       // If only one is const, then make it the first callback argument.
751       if (FirstIsConst || SecondIsConst) {
752         CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
753         if (SecondIsConst)
754           std::swap(A0, A1);
755       }
756 
757       auto Ty = Type::getIntNTy(*C, TypeSize);
758       IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
759               IRB.CreateIntCast(A1, Ty, true)});
760     }
761   }
762 }
763 
764 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
765                                                     size_t Idx,
766                                                     bool IsLeafFunc) {
767   BasicBlock::iterator IP = BB.getFirstInsertionPt();
768   bool IsEntryBB = &BB == &F.getEntryBlock();
769   DebugLoc EntryLoc;
770   if (IsEntryBB) {
771     if (auto SP = F.getSubprogram())
772       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
773     // Keep static allocas and llvm.localescape calls in the entry block.  Even
774     // if we aren't splitting the block, it's nice for allocas to be before
775     // calls.
776     IP = PrepareToSplitEntryBlock(BB, IP);
777   } else {
778     EntryLoc = IP->getDebugLoc();
779   }
780 
781   IRBuilder<> IRB(&*IP);
782   IRB.SetCurrentDebugLocation(EntryLoc);
783   if (Options.TracePC) {
784     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
785     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
786   }
787   if (Options.TracePCGuard) {
788     auto GuardPtr = IRB.CreateIntToPtr(
789         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
790                       ConstantInt::get(IntptrTy, Idx * 4)),
791         Int32PtrTy);
792     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
793     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
794   }
795   if (Options.Inline8bitCounters) {
796     auto CounterPtr = IRB.CreateGEP(
797         Function8bitCounterArray,
798         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
799     auto Load = IRB.CreateLoad(CounterPtr);
800     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
801     auto Store = IRB.CreateStore(Inc, CounterPtr);
802     SetNoSanitizeMetadata(Load);
803     SetNoSanitizeMetadata(Store);
804   }
805   if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
806     // Check stack depth.  If it's the deepest so far, record it.
807     Function *GetFrameAddr =
808         Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
809     auto FrameAddrPtr =
810         IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
811     auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
812     auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
813     auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
814     auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
815     IRBuilder<> ThenIRB(ThenTerm);
816     auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
817     SetNoSanitizeMetadata(LowestStack);
818     SetNoSanitizeMetadata(Store);
819   }
820 }
821 
822 std::string
823 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
824   if (TargetTriple.getObjectFormat() == Triple::COFF) {
825     if (Section == SanCovCountersSectionName)
826       return ".SCOV$CM";
827     if (Section == SanCovPCsSectionName)
828       return ".SCOVP$M";
829     return ".SCOV$GM"; // For SanCovGuardsSectionName.
830   }
831   if (TargetTriple.isOSBinFormatMachO())
832     return "__DATA,__" + Section;
833   return "__" + Section;
834 }
835 
836 std::string
837 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
838   if (TargetTriple.isOSBinFormatMachO())
839     return "\1section$start$__DATA$__" + Section;
840   return "__start___" + Section;
841 }
842 
843 std::string
844 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
845   if (TargetTriple.isOSBinFormatMachO())
846     return "\1section$end$__DATA$__" + Section;
847   return "__stop___" + Section;
848 }
849 
850 
851 char SanitizerCoverageModule::ID = 0;
852 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
853                       "SanitizerCoverage: TODO."
854                       "ModulePass",
855                       false, false)
856 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
857 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
858 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
859                     "SanitizerCoverage: TODO."
860                     "ModulePass",
861                     false, false)
862 ModulePass *llvm::createSanitizerCoverageModulePass(
863     const SanitizerCoverageOptions &Options) {
864   return new SanitizerCoverageModule(Options);
865 }
866