xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision 9385aaa848516abe9c7beb4555c42db080c36249)
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/DataLayout.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/MDBuilder.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Instrumentation.h"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/ModuleUtils.h"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "sancov"
41 
42 static const char *const SanCovTracePCIndirName =
43     "__sanitizer_cov_trace_pc_indir";
44 static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
45 static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
46 static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
47 static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
48 static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
49 static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
50 static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
51 static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
52 static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
53 static const char *const SanCovModuleCtorName = "sancov.module_ctor";
54 static const uint64_t SanCtorAndDtorPriority = 2;
55 
56 static const char *const SanCovTracePCGuardName =
57     "__sanitizer_cov_trace_pc_guard";
58 static const char *const SanCovTracePCGuardInitName =
59     "__sanitizer_cov_trace_pc_guard_init";
60 static const char *const SanCov8bitCountersInitName =
61     "__sanitizer_cov_8bit_counters_init";
62 
63 static const char *const SanCovGuardsSectionName = "sancov_guards";
64 static const char *const SanCovCountersSectionName = "sancov_cntrs";
65 
66 static cl::opt<int> ClCoverageLevel(
67     "sanitizer-coverage-level",
68     cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
69              "3: all blocks and critical edges"),
70     cl::Hidden, cl::init(0));
71 
72 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
73                                cl::desc("Experimental pc tracing"), cl::Hidden,
74                                cl::init(false));
75 
76 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
77                                     cl::desc("pc tracing with a guard"),
78                                     cl::Hidden, cl::init(false));
79 
80 static cl::opt<bool> ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
81                                     cl::desc("increments 8-bit counter for every edge"),
82                                     cl::Hidden, cl::init(false));
83 
84 static cl::opt<bool>
85     ClCMPTracing("sanitizer-coverage-trace-compares",
86                  cl::desc("Tracing of CMP and similar instructions"),
87                  cl::Hidden, cl::init(false));
88 
89 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
90                                   cl::desc("Tracing of DIV instructions"),
91                                   cl::Hidden, cl::init(false));
92 
93 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
94                                   cl::desc("Tracing of GEP instructions"),
95                                   cl::Hidden, cl::init(false));
96 
97 static cl::opt<bool>
98     ClPruneBlocks("sanitizer-coverage-prune-blocks",
99                   cl::desc("Reduce the number of instrumented blocks"),
100                   cl::Hidden, cl::init(true));
101 
102 namespace {
103 
104 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
105   SanitizerCoverageOptions Res;
106   switch (LegacyCoverageLevel) {
107   case 0:
108     Res.CoverageType = SanitizerCoverageOptions::SCK_None;
109     break;
110   case 1:
111     Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
112     break;
113   case 2:
114     Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
115     break;
116   case 3:
117     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
118     break;
119   case 4:
120     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
121     Res.IndirectCalls = true;
122     break;
123   }
124   return Res;
125 }
126 
127 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
128   // Sets CoverageType and IndirectCalls.
129   SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
130   Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
131   Options.IndirectCalls |= CLOpts.IndirectCalls;
132   Options.TraceCmp |= ClCMPTracing;
133   Options.TraceDiv |= ClDIVTracing;
134   Options.TraceGep |= ClGEPTracing;
135   Options.TracePC |= ClTracePC;
136   Options.TracePCGuard |= ClTracePCGuard;
137   Options.Inline8bitCounters |= ClInline8bitCounters;
138   if (!Options.TracePCGuard && !Options.TracePC && !Options.Inline8bitCounters)
139     Options.TracePCGuard = true; // TracePCGuard is default.
140   Options.NoPrune |= !ClPruneBlocks;
141   return Options;
142 }
143 
144 class SanitizerCoverageModule : public ModulePass {
145 public:
146   SanitizerCoverageModule(
147       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
148       : ModulePass(ID), Options(OverrideFromCL(Options)) {
149     initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
150   }
151   bool runOnModule(Module &M) override;
152   bool runOnFunction(Function &F);
153   static char ID; // Pass identification, replacement for typeid
154   StringRef getPassName() const override { return "SanitizerCoverageModule"; }
155 
156   void getAnalysisUsage(AnalysisUsage &AU) const override {
157     AU.addRequired<DominatorTreeWrapperPass>();
158     AU.addRequired<PostDominatorTreeWrapperPass>();
159   }
160 
161 private:
162   void InjectCoverageForIndirectCalls(Function &F,
163                                       ArrayRef<Instruction *> IndirCalls);
164   void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
165   void InjectTraceForDiv(Function &F,
166                          ArrayRef<BinaryOperator *> DivTraceTargets);
167   void InjectTraceForGep(Function &F,
168                          ArrayRef<GetElementPtrInst *> GepTraceTargets);
169   void InjectTraceForSwitch(Function &F,
170                             ArrayRef<Instruction *> SwitchTraceTargets);
171   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
172   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
173                                                     Function &F, Type *Ty,
174                                                     const char *Section);
175   void CreateFunctionLocalArrays(size_t NumGuards, Function &F);
176   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
177   void CreateInitCallForSection(Module &M, const char *InitFunctionName,
178                                 Type *Ty, const std::string &Section);
179 
180   void SetNoSanitizeMetadata(Instruction *I) {
181     I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
182                    MDNode::get(*C, None));
183   }
184 
185   std::string getSectionName(const std::string &Section) const;
186   std::string getSectionStart(const std::string &Section) const;
187   std::string getSectionEnd(const std::string &Section) const;
188   Function *SanCovTracePCIndir;
189   Function *SanCovTracePC, *SanCovTracePCGuard;
190   Function *SanCovTraceCmpFunction[4];
191   Function *SanCovTraceDivFunction[2];
192   Function *SanCovTraceGepFunction;
193   Function *SanCovTraceSwitchFunction;
194   InlineAsm *EmptyAsm;
195   Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
196       *Int8Ty, *Int8PtrTy;
197   Module *CurModule;
198   Triple TargetTriple;
199   LLVMContext *C;
200   const DataLayout *DL;
201 
202   GlobalVariable *FunctionGuardArray;  // for trace-pc-guard.
203   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
204 
205   SanitizerCoverageOptions Options;
206 };
207 
208 } // namespace
209 
210 void SanitizerCoverageModule::CreateInitCallForSection(
211     Module &M, const char *InitFunctionName, Type *Ty,
212     const std::string &Section) {
213   IRBuilder<> IRB(M.getContext());
214   Function *CtorFunc;
215   GlobalVariable *SecStart =
216       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
217                          getSectionStart(Section));
218   SecStart->setVisibility(GlobalValue::HiddenVisibility);
219   GlobalVariable *SecEnd =
220       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
221                          nullptr, getSectionEnd(Section));
222   SecEnd->setVisibility(GlobalValue::HiddenVisibility);
223 
224   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
225       M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
226       {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
227 
228   if (TargetTriple.supportsCOMDAT()) {
229     // Use comdat to dedup CtorFunc.
230     CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
231     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
232   } else {
233     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
234   }
235 }
236 
237 bool SanitizerCoverageModule::runOnModule(Module &M) {
238   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
239     return false;
240   C = &(M.getContext());
241   DL = &M.getDataLayout();
242   CurModule = &M;
243   TargetTriple = Triple(M.getTargetTriple());
244   FunctionGuardArray = nullptr;
245   Function8bitCounterArray = nullptr;
246   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
247   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
248   Type *VoidTy = Type::getVoidTy(*C);
249   IRBuilder<> IRB(*C);
250   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
251   Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
252   Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
253   Int64Ty = IRB.getInt64Ty();
254   Int32Ty = IRB.getInt32Ty();
255   Int8Ty = IRB.getInt8Ty();
256 
257   SanCovTracePCIndir = checkSanitizerInterfaceFunction(
258       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
259   SanCovTraceCmpFunction[0] =
260       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
261           SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
262   SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
263       M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
264                             IRB.getInt16Ty()));
265   SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
266       M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
267                             IRB.getInt32Ty()));
268   SanCovTraceCmpFunction[3] =
269       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
270           SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
271 
272   SanCovTraceDivFunction[0] =
273       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
274           SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
275   SanCovTraceDivFunction[1] =
276       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
277           SanCovTraceDiv8, VoidTy, Int64Ty));
278   SanCovTraceGepFunction =
279       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
280           SanCovTraceGep, VoidTy, IntptrTy));
281   SanCovTraceSwitchFunction =
282       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
283           SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
284   // Make sure smaller parameters are zero-extended to i64 as required by the
285   // x86_64 ABI.
286   if (TargetTriple.getArch() == Triple::x86_64) {
287     for (int i = 0; i < 3; i++) {
288       SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
289       SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
290     }
291     SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
292   }
293 
294 
295   // We insert an empty inline asm after cov callbacks to avoid callback merge.
296   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
297                             StringRef(""), StringRef(""),
298                             /*hasSideEffects=*/true);
299 
300   SanCovTracePC = checkSanitizerInterfaceFunction(
301       M.getOrInsertFunction(SanCovTracePCName, VoidTy));
302   SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
303       SanCovTracePCGuardName, VoidTy, Int32PtrTy));
304 
305   for (auto &F : M)
306     runOnFunction(F);
307 
308   if (FunctionGuardArray)
309     CreateInitCallForSection(M, SanCovTracePCGuardInitName, Int32PtrTy,
310                              SanCovGuardsSectionName);
311   if (Function8bitCounterArray)
312     CreateInitCallForSection(M, SanCov8bitCountersInitName, Int8PtrTy,
313                              SanCovCountersSectionName);
314 
315   return true;
316 }
317 
318 // True if block has successors and it dominates all of them.
319 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
320   if (succ_begin(BB) == succ_end(BB))
321     return false;
322 
323   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
324     if (!DT->dominates(BB, SUCC))
325       return false;
326   }
327 
328   return true;
329 }
330 
331 // True if block has predecessors and it postdominates all of them.
332 static bool isFullPostDominator(const BasicBlock *BB,
333                                 const PostDominatorTree *PDT) {
334   if (pred_begin(BB) == pred_end(BB))
335     return false;
336 
337   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
338     if (!PDT->dominates(BB, PRED))
339       return false;
340   }
341 
342   return true;
343 }
344 
345 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
346                                   const DominatorTree *DT,
347                                   const PostDominatorTree *PDT,
348                                   const SanitizerCoverageOptions &Options) {
349   // Don't insert coverage for unreachable blocks: we will never call
350   // __sanitizer_cov() for them, so counting them in
351   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
352   // percentage. Also, unreachable instructions frequently have no debug
353   // locations.
354   if (isa<UnreachableInst>(BB->getTerminator()))
355     return false;
356 
357   // Don't insert coverage into blocks without a valid insertion point
358   // (catchswitch blocks).
359   if (BB->getFirstInsertionPt() == BB->end())
360     return false;
361 
362   if (Options.NoPrune || &F.getEntryBlock() == BB)
363     return true;
364 
365   // Do not instrument full dominators, or full post-dominators with multiple
366   // predecessors.
367   return !isFullDominator(BB, DT)
368     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
369 }
370 
371 bool SanitizerCoverageModule::runOnFunction(Function &F) {
372   if (F.empty())
373     return false;
374   if (F.getName().find(".module_ctor") != std::string::npos)
375     return false; // Should not instrument sanitizer init functions.
376   if (F.getName().startswith("__sanitizer_"))
377     return false;  // Don't instrument __sanitizer_* callbacks.
378   // Don't instrument MSVC CRT configuration helpers. They may run before normal
379   // initialization.
380   if (F.getName() == "__local_stdio_printf_options" ||
381       F.getName() == "__local_stdio_scanf_options")
382     return false;
383   // Don't instrument functions using SEH for now. Splitting basic blocks like
384   // we do for coverage breaks WinEHPrepare.
385   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
386   if (F.hasPersonalityFn() &&
387       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
388     return false;
389   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
390     SplitAllCriticalEdges(F);
391   SmallVector<Instruction *, 8> IndirCalls;
392   SmallVector<BasicBlock *, 16> BlocksToInstrument;
393   SmallVector<Instruction *, 8> CmpTraceTargets;
394   SmallVector<Instruction *, 8> SwitchTraceTargets;
395   SmallVector<BinaryOperator *, 8> DivTraceTargets;
396   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
397 
398   const DominatorTree *DT =
399       &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
400   const PostDominatorTree *PDT =
401       &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
402 
403   for (auto &BB : F) {
404     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
405       BlocksToInstrument.push_back(&BB);
406     for (auto &Inst : BB) {
407       if (Options.IndirectCalls) {
408         CallSite CS(&Inst);
409         if (CS && !CS.getCalledFunction())
410           IndirCalls.push_back(&Inst);
411       }
412       if (Options.TraceCmp) {
413         if (isa<ICmpInst>(&Inst))
414           CmpTraceTargets.push_back(&Inst);
415         if (isa<SwitchInst>(&Inst))
416           SwitchTraceTargets.push_back(&Inst);
417       }
418       if (Options.TraceDiv)
419         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
420           if (BO->getOpcode() == Instruction::SDiv ||
421               BO->getOpcode() == Instruction::UDiv)
422             DivTraceTargets.push_back(BO);
423       if (Options.TraceGep)
424         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
425           GepTraceTargets.push_back(GEP);
426    }
427   }
428 
429   InjectCoverage(F, BlocksToInstrument);
430   InjectCoverageForIndirectCalls(F, IndirCalls);
431   InjectTraceForCmp(F, CmpTraceTargets);
432   InjectTraceForSwitch(F, SwitchTraceTargets);
433   InjectTraceForDiv(F, DivTraceTargets);
434   InjectTraceForGep(F, GepTraceTargets);
435   return true;
436 }
437 
438 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
439     size_t NumElements, Function &F, Type *Ty, const char *Section) {
440   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
441   auto Array = new GlobalVariable(
442       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
443       Constant::getNullValue(ArrayTy), "__sancov_gen_");
444   if (auto Comdat = F.getComdat())
445     Array->setComdat(Comdat);
446   Array->setSection(getSectionName(Section));
447   return Array;
448 }
449 void SanitizerCoverageModule::CreateFunctionLocalArrays(size_t NumGuards,
450                                                        Function &F) {
451   if (Options.TracePCGuard)
452     FunctionGuardArray = CreateFunctionLocalArrayInSection(
453         NumGuards, F, Int32Ty, SanCovGuardsSectionName);
454   if (Options.Inline8bitCounters)
455     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
456         NumGuards, F, Int8Ty, SanCovCountersSectionName);
457 }
458 
459 bool SanitizerCoverageModule::InjectCoverage(Function &F,
460                                              ArrayRef<BasicBlock *> AllBlocks) {
461   if (AllBlocks.empty()) return false;
462   switch (Options.CoverageType) {
463   case SanitizerCoverageOptions::SCK_None:
464     return false;
465   case SanitizerCoverageOptions::SCK_Function:
466     CreateFunctionLocalArrays(1, F);
467     InjectCoverageAtBlock(F, F.getEntryBlock(), 0);
468     return true;
469   default: {
470     CreateFunctionLocalArrays(AllBlocks.size(), F);
471     for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
472       InjectCoverageAtBlock(F, *AllBlocks[i], i);
473     return true;
474   }
475   }
476 }
477 
478 // On every indirect call we call a run-time function
479 // __sanitizer_cov_indir_call* with two parameters:
480 //   - callee address,
481 //   - global cache array that contains CacheSize pointers (zero-initialized).
482 //     The cache is used to speed up recording the caller-callee pairs.
483 // The address of the caller is passed implicitly via caller PC.
484 // CacheSize is encoded in the name of the run-time function.
485 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
486     Function &F, ArrayRef<Instruction *> IndirCalls) {
487   if (IndirCalls.empty())
488     return;
489   assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
490   for (auto I : IndirCalls) {
491     IRBuilder<> IRB(I);
492     CallSite CS(I);
493     Value *Callee = CS.getCalledValue();
494     if (isa<InlineAsm>(Callee))
495       continue;
496     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
497   }
498 }
499 
500 // For every switch statement we insert a call:
501 // __sanitizer_cov_trace_switch(CondValue,
502 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
503 
504 void SanitizerCoverageModule::InjectTraceForSwitch(
505     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
506   for (auto I : SwitchTraceTargets) {
507     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
508       IRBuilder<> IRB(I);
509       SmallVector<Constant *, 16> Initializers;
510       Value *Cond = SI->getCondition();
511       if (Cond->getType()->getScalarSizeInBits() >
512           Int64Ty->getScalarSizeInBits())
513         continue;
514       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
515       Initializers.push_back(
516           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
517       if (Cond->getType()->getScalarSizeInBits() <
518           Int64Ty->getScalarSizeInBits())
519         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
520       for (auto It : SI->cases()) {
521         Constant *C = It.getCaseValue();
522         if (C->getType()->getScalarSizeInBits() <
523             Int64Ty->getScalarSizeInBits())
524           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
525         Initializers.push_back(C);
526       }
527       std::sort(Initializers.begin() + 2, Initializers.end(),
528                 [](const Constant *A, const Constant *B) {
529                   return cast<ConstantInt>(A)->getLimitedValue() <
530                          cast<ConstantInt>(B)->getLimitedValue();
531                 });
532       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
533       GlobalVariable *GV = new GlobalVariable(
534           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
535           ConstantArray::get(ArrayOfInt64Ty, Initializers),
536           "__sancov_gen_cov_switch_values");
537       IRB.CreateCall(SanCovTraceSwitchFunction,
538                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
539     }
540   }
541 }
542 
543 void SanitizerCoverageModule::InjectTraceForDiv(
544     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
545   for (auto BO : DivTraceTargets) {
546     IRBuilder<> IRB(BO);
547     Value *A1 = BO->getOperand(1);
548     if (isa<ConstantInt>(A1)) continue;
549     if (!A1->getType()->isIntegerTy())
550       continue;
551     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
552     int CallbackIdx = TypeSize == 32 ? 0 :
553         TypeSize == 64 ? 1 : -1;
554     if (CallbackIdx < 0) continue;
555     auto Ty = Type::getIntNTy(*C, TypeSize);
556     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
557                    {IRB.CreateIntCast(A1, Ty, true)});
558   }
559 }
560 
561 void SanitizerCoverageModule::InjectTraceForGep(
562     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
563   for (auto GEP : GepTraceTargets) {
564     IRBuilder<> IRB(GEP);
565     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
566       if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
567         IRB.CreateCall(SanCovTraceGepFunction,
568                        {IRB.CreateIntCast(*I, IntptrTy, true)});
569   }
570 }
571 
572 void SanitizerCoverageModule::InjectTraceForCmp(
573     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
574   for (auto I : CmpTraceTargets) {
575     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
576       IRBuilder<> IRB(ICMP);
577       Value *A0 = ICMP->getOperand(0);
578       Value *A1 = ICMP->getOperand(1);
579       if (!A0->getType()->isIntegerTy())
580         continue;
581       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
582       int CallbackIdx = TypeSize == 8 ? 0 :
583                         TypeSize == 16 ? 1 :
584                         TypeSize == 32 ? 2 :
585                         TypeSize == 64 ? 3 : -1;
586       if (CallbackIdx < 0) continue;
587       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
588       auto Ty = Type::getIntNTy(*C, TypeSize);
589       IRB.CreateCall(
590           SanCovTraceCmpFunction[CallbackIdx],
591           {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
592     }
593   }
594 }
595 
596 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
597                                                     size_t Idx) {
598   BasicBlock::iterator IP = BB.getFirstInsertionPt();
599   bool IsEntryBB = &BB == &F.getEntryBlock();
600   DebugLoc EntryLoc;
601   if (IsEntryBB) {
602     if (auto SP = F.getSubprogram())
603       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
604     // Keep static allocas and llvm.localescape calls in the entry block.  Even
605     // if we aren't splitting the block, it's nice for allocas to be before
606     // calls.
607     IP = PrepareToSplitEntryBlock(BB, IP);
608   } else {
609     EntryLoc = IP->getDebugLoc();
610   }
611 
612   IRBuilder<> IRB(&*IP);
613   IRB.SetCurrentDebugLocation(EntryLoc);
614   if (Options.TracePC) {
615     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
616     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
617   }
618   if (Options.TracePCGuard) {
619     auto GuardPtr = IRB.CreateIntToPtr(
620         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
621                       ConstantInt::get(IntptrTy, Idx * 4)),
622         Int32PtrTy);
623     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
624     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
625   }
626   if (Options.Inline8bitCounters) {
627     auto CounterPtr = IRB.CreateGEP(
628         Function8bitCounterArray,
629         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
630     auto Load = IRB.CreateLoad(CounterPtr);
631     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
632     auto Store = IRB.CreateStore(Inc, CounterPtr);
633     SetNoSanitizeMetadata(Load);
634     SetNoSanitizeMetadata(Store);
635   }
636 }
637 
638 std::string
639 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
640   if (TargetTriple.getObjectFormat() == Triple::COFF)
641     return ".SCOV$M";
642   if (TargetTriple.isOSBinFormatMachO())
643     return "__DATA,__" + Section;
644   return "__" + Section;
645 }
646 
647 std::string
648 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
649   if (TargetTriple.isOSBinFormatMachO())
650     return "\1section$start$__DATA$__" + Section;
651   return "__start___" + Section;
652 }
653 
654 std::string
655 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
656   if (TargetTriple.isOSBinFormatMachO())
657     return "\1section$end$__DATA$__" + Section;
658   return "__stop___" + Section;
659 }
660 
661 
662 char SanitizerCoverageModule::ID = 0;
663 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
664                       "SanitizerCoverage: TODO."
665                       "ModulePass",
666                       false, false)
667 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
668 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
669 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
670                     "SanitizerCoverage: TODO."
671                     "ModulePass",
672                     false, false)
673 ModulePass *llvm::createSanitizerCoverageModulePass(
674     const SanitizerCoverageOptions &Options) {
675   return new SanitizerCoverageModule(Options);
676 }
677