1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Coverage instrumentation done on LLVM IR level, works with Sanitizers.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Analysis/EHPersonalities.h"
18 #include "llvm/Analysis/PostDominators.h"
19 #include "llvm/IR/CFG.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/Mangler.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/PassManager.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/SpecialCaseList.h"
40 #include "llvm/Support/VirtualFileSystem.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/Instrumentation.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/ModuleUtils.h"
45 #include "llvm/Passes/PassPlugin.h"
46 #include "llvm/Passes/PassBuilder.h"
47 #include "llvm/IR/PassManager.h"
48 
49 #include "config.h"
50 #include "debug.h"
51 #include "afl-llvm-common.h"
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "sancov"
56 
57 const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
58 const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
59 const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
60 const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
61 const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
62 const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8";
63 const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1";
64 const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2";
65 const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4";
66 const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8";
67 const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4";
68 const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8";
69 const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep";
70 const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch";
71 const char SanCovModuleCtorTracePcGuardName[] =
72     "sancov.module_ctor_trace_pc_guard";
73 const char SanCovModuleCtor8bitCountersName[] =
74     "sancov.module_ctor_8bit_counters";
75 const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag";
76 static const uint64_t SanCtorAndDtorPriority = 2;
77 
78 const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard";
79 const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init";
80 const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
81 const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
82 const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
83 
84 const char SanCovGuardsSectionName[] = "sancov_guards";
85 const char SanCovCountersSectionName[] = "sancov_cntrs";
86 const char SanCovBoolFlagSectionName[] = "sancov_bools";
87 const char SanCovPCsSectionName[] = "sancov_pcs";
88 
89 const char SanCovLowestStackName[] = "__sancov_lowest_stack";
90 
91 static const char *skip_nozero;
92 static const char *use_threadsafe_counters;
93 
94 namespace {
95 
OverrideFromCL(SanitizerCoverageOptions Options)96 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
97 
98   // Sets CoverageType and IndirectCalls.
99   // SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
100   Options.CoverageType =
101       SanitizerCoverageOptions::SCK_Edge;  // std::max(Options.CoverageType,
102                                            // CLOpts.CoverageType);
103   Options.IndirectCalls = false;           // CLOpts.IndirectCalls;
104   Options.TraceCmp = false;                //|= ClCMPTracing;
105   Options.TraceDiv = false;                //|= ClDIVTracing;
106   Options.TraceGep = false;                //|= ClGEPTracing;
107   Options.TracePC = false;                 //|= ClTracePC;
108   Options.TracePCGuard = true;             // |= ClTracePCGuard;
109   Options.Inline8bitCounters = 0;          //|= ClInline8bitCounters;
110   // Options.InlineBoolFlag = 0; //|= ClInlineBoolFlag;
111   Options.PCTable = false;     //|= ClCreatePCTable;
112   Options.NoPrune = false;     //|= !ClPruneBlocks;
113   Options.StackDepth = false;  //|= ClStackDepth;
114   if (!Options.TracePCGuard && !Options.TracePC &&
115       !Options.Inline8bitCounters && !Options.StackDepth /*&&
116       !Options.InlineBoolFlag*/)
117     Options.TracePCGuard = true;  // TracePCGuard is default.
118 
119   return Options;
120 
121 }
122 
123 using DomTreeCallback = function_ref<const DominatorTree *(Function &F)>;
124 using PostDomTreeCallback =
125     function_ref<const PostDominatorTree *(Function &F)>;
126 
127 class ModuleSanitizerCoverageAFL
128     : public PassInfoMixin<ModuleSanitizerCoverageAFL> {
129 
130  public:
ModuleSanitizerCoverageAFL(const SanitizerCoverageOptions & Options=SanitizerCoverageOptions ())131   ModuleSanitizerCoverageAFL(
132       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
133       : Options(OverrideFromCL(Options)) {
134 
135   }
136 
137   PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM);
138 
139   bool instrumentModule(Module &M, DomTreeCallback DTCallback,
140                         PostDomTreeCallback PDTCallback);
141 
142  private:
143   void instrumentFunction(Function &F, DomTreeCallback DTCallback,
144                           PostDomTreeCallback PDTCallback);
145   void InjectCoverageForIndirectCalls(Function &              F,
146                                       ArrayRef<Instruction *> IndirCalls);
147   void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
148   void InjectTraceForDiv(Function &                 F,
149                          ArrayRef<BinaryOperator *> DivTraceTargets);
150   void InjectTraceForGep(Function &                    F,
151                          ArrayRef<GetElementPtrInst *> GepTraceTargets);
152   void InjectTraceForSwitch(Function &              F,
153                             ArrayRef<Instruction *> SwitchTraceTargets);
154   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
155                       bool IsLeafFunc = true);
156   GlobalVariable *CreateFunctionLocalArrayInSection(size_t    NumElements,
157                                                     Function &F, Type *Ty,
158                                                     const char *Section);
159   GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
160   void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks,
161                                  uint32_t special);
162   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
163                              bool IsLeafFunc = true);
164   Function *CreateInitCallsForSections(Module &M, const char *CtorName,
165                                        const char *InitFunctionName, Type *Ty,
166                                        const char *Section);
167   std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
168                                                 Type *Ty);
169 
SetNoSanitizeMetadata(Instruction * I)170   void SetNoSanitizeMetadata(Instruction *I) {
171 
172     I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
173                    MDNode::get(*C, None));
174 
175   }
176 
177   std::string     getSectionName(const std::string &Section) const;
178   std::string     getSectionStart(const std::string &Section) const;
179   std::string     getSectionEnd(const std::string &Section) const;
180   FunctionCallee  SanCovTracePCIndir;
181   FunctionCallee  SanCovTracePC, SanCovTracePCGuard;
182   FunctionCallee  SanCovTraceCmpFunction[4];
183   FunctionCallee  SanCovTraceConstCmpFunction[4];
184   FunctionCallee  SanCovTraceDivFunction[2];
185   FunctionCallee  SanCovTraceGepFunction;
186   FunctionCallee  SanCovTraceSwitchFunction;
187   GlobalVariable *SanCovLowestStack;
188   Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
189       *Int16Ty, *Int8Ty, *Int8PtrTy, *Int1Ty, *Int1PtrTy;
190   Module *          CurModule;
191   std::string       CurModuleUniqueId;
192   Triple            TargetTriple;
193   LLVMContext *     C;
194   const DataLayout *DL;
195 
196   GlobalVariable *FunctionGuardArray;        // for trace-pc-guard.
197   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
198   GlobalVariable *FunctionBoolArray;         // for inline-bool-flag.
199   GlobalVariable *FunctionPCsArray;          // for pc-table.
200   SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
201   SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
202 
203   SanitizerCoverageOptions Options;
204 
205   uint32_t        instr = 0, selects = 0, unhandled = 0;
206   GlobalVariable *AFLMapPtr = NULL;
207   ConstantInt *   One = NULL;
208   ConstantInt *   Zero = NULL;
209 
210 };
211 
212 class ModuleSanitizerCoverageLegacyPass : public ModulePass {
213 
214  public:
ModuleSanitizerCoverageLegacyPass(const SanitizerCoverageOptions & Options=SanitizerCoverageOptions ())215   ModuleSanitizerCoverageLegacyPass(
216       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
217       : ModulePass(ID), Options(Options) {
218 
219     initializeModuleSanitizerCoverageLegacyPassPass(
220         *PassRegistry::getPassRegistry());
221 
222   }
223 
runOnModule(Module & M)224   bool runOnModule(Module &M) override {
225 
226     ModuleSanitizerCoverageAFL ModuleSancov(Options);
227     auto DTCallback = [this](Function &F) -> const DominatorTree * {
228 
229       return &this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
230 
231     };
232 
233     auto PDTCallback = [this](Function &F) -> const PostDominatorTree * {
234 
235       return &this->getAnalysis<PostDominatorTreeWrapperPass>(F)
236                   .getPostDomTree();
237 
238     };
239 
240     return ModuleSancov.instrumentModule(M, DTCallback, PDTCallback);
241 
242   }
243 
244   /*static*/ char ID;  // Pass identification, replacement for typeid
getPassName() const245   StringRef       getPassName() const override {
246 
247     return "ModuleSanitizerCoverage";
248 
249   }
250 
getAnalysisUsage(AnalysisUsage & AU) const251   void getAnalysisUsage(AnalysisUsage &AU) const override {
252 
253     AU.addRequired<DominatorTreeWrapperPass>();
254     AU.addRequired<PostDominatorTreeWrapperPass>();
255 
256   }
257 
258  private:
259   SanitizerCoverageOptions Options;
260 
261 };
262 
263 }  // namespace
264 
265 #if 1
266 
267 extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK
llvmGetPassPluginInfo()268 llvmGetPassPluginInfo() {
269 
270   return {LLVM_PLUGIN_API_VERSION, "SanitizerCoveragePCGUARD", "v0.1",
271           /* lambda to insert our pass into the pass pipeline. */
272           [](PassBuilder &PB) {
273 
274   #if LLVM_VERSION_MAJOR <= 13
275             using OptimizationLevel = typename PassBuilder::OptimizationLevel;
276   #endif
277             PB.registerOptimizerLastEPCallback(
278                 [](ModulePassManager &MPM, OptimizationLevel OL) {
279 
280                   MPM.addPass(ModuleSanitizerCoverageAFL());
281 
282                 });
283 
284           }};
285 
286 }
287 
288 #endif
289 
run(Module & M,ModuleAnalysisManager & MAM)290 PreservedAnalyses ModuleSanitizerCoverageAFL::run(Module &               M,
291                                                   ModuleAnalysisManager &MAM) {
292 
293   ModuleSanitizerCoverageAFL ModuleSancov(Options);
294   auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
295   auto  DTCallback = [&FAM](Function &F) -> const DominatorTree * {
296 
297     return &FAM.getResult<DominatorTreeAnalysis>(F);
298 
299   };
300 
301   auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree * {
302 
303     return &FAM.getResult<PostDominatorTreeAnalysis>(F);
304 
305   };
306 
307   if (ModuleSancov.instrumentModule(M, DTCallback, PDTCallback))
308     return PreservedAnalyses::none();
309   return PreservedAnalyses::all();
310 
311 }
312 
CreateSecStartEnd(Module & M,const char * Section,Type * Ty)313 std::pair<Value *, Value *> ModuleSanitizerCoverageAFL::CreateSecStartEnd(
314     Module &M, const char *Section, Type *Ty) {
315 
316   GlobalVariable *SecStart =
317       new GlobalVariable(M,
318 #if LLVM_VERSION_MAJOR >= 15
319                          Ty,
320 #else
321                          Ty->getPointerElementType(),
322 #endif
323                          false, GlobalVariable::ExternalWeakLinkage, nullptr,
324                          getSectionStart(Section));
325   SecStart->setVisibility(GlobalValue::HiddenVisibility);
326   GlobalVariable *SecEnd =
327       new GlobalVariable(M,
328 #if LLVM_VERSION_MAJOR >= 15
329                          Ty,
330 #else
331                          Ty->getPointerElementType(),
332 #endif
333                          false, GlobalVariable::ExternalWeakLinkage, nullptr,
334                          getSectionEnd(Section));
335   SecEnd->setVisibility(GlobalValue::HiddenVisibility);
336   IRBuilder<> IRB(M.getContext());
337   if (!TargetTriple.isOSBinFormatCOFF())
338     return std::make_pair(SecStart, SecEnd);
339 
340   // Account for the fact that on windows-msvc __start_* symbols actually
341   // point to a uint64_t before the start of the array.
342   auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
343   auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr,
344                            ConstantInt::get(IntptrTy, sizeof(uint64_t)));
345   return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEnd);
346 
347 }
348 
CreateInitCallsForSections(Module & M,const char * CtorName,const char * InitFunctionName,Type * Ty,const char * Section)349 Function *ModuleSanitizerCoverageAFL::CreateInitCallsForSections(
350     Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
351     const char *Section) {
352 
353   auto      SecStartEnd = CreateSecStartEnd(M, Section, Ty);
354   auto      SecStart = SecStartEnd.first;
355   auto      SecEnd = SecStartEnd.second;
356   Function *CtorFunc;
357   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
358       M, CtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd});
359   assert(CtorFunc->getName() == CtorName);
360 
361   if (TargetTriple.supportsCOMDAT()) {
362 
363     // Use comdat to dedup CtorFunc.
364     CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
365     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
366 
367   } else {
368 
369     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
370 
371   }
372 
373   if (TargetTriple.isOSBinFormatCOFF()) {
374 
375     // In COFF files, if the contructors are set as COMDAT (they are because
376     // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
377     // functions and data) is used, the constructors get stripped. To prevent
378     // this, give the constructors weak ODR linkage and ensure the linker knows
379     // to include the sancov constructor. This way the linker can deduplicate
380     // the constructors but always leave one copy.
381     CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
382     appendToUsed(M, CtorFunc);
383 
384   }
385 
386   return CtorFunc;
387 
388 }
389 
instrumentModule(Module & M,DomTreeCallback DTCallback,PostDomTreeCallback PDTCallback)390 bool ModuleSanitizerCoverageAFL::instrumentModule(
391     Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
392 
393   setvbuf(stdout, NULL, _IONBF, 0);
394   if (getenv("AFL_DEBUG")) debug = 1;
395 
396   if ((isatty(2) && !getenv("AFL_QUIET")) || debug) {
397 
398     SAYF(cCYA "SanitizerCoveragePCGUARD" VERSION cRST "\n");
399 
400   } else
401 
402     be_quiet = 1;
403 
404   skip_nozero = getenv("AFL_LLVM_SKIP_NEVERZERO");
405   use_threadsafe_counters = getenv("AFL_LLVM_THREADSAFE_INST");
406 
407   initInstrumentList();
408   scanForDangerousFunctions(&M);
409 
410   if (debug) {
411 
412     fprintf(stderr,
413             "SANCOV: covtype:%u indirect:%d stack:%d noprune:%d "
414             "createtable:%d tracepcguard:%d tracepc:%d\n",
415             Options.CoverageType, Options.IndirectCalls == true ? 1 : 0,
416             Options.StackDepth == true ? 1 : 0, Options.NoPrune == true ? 1 : 0,
417             // Options.InlineBoolFlag == true ? 1 : 0,
418             Options.PCTable == true ? 1 : 0,
419             Options.TracePCGuard == true ? 1 : 0,
420             Options.TracePC == true ? 1 : 0);
421 
422   }
423 
424   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None) return false;
425   C = &(M.getContext());
426   DL = &M.getDataLayout();
427   CurModule = &M;
428   CurModuleUniqueId = getUniqueModuleId(CurModule);
429   TargetTriple = Triple(M.getTargetTriple());
430   FunctionGuardArray = nullptr;
431   Function8bitCounterArray = nullptr;
432   FunctionBoolArray = nullptr;
433   FunctionPCsArray = nullptr;
434   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
435   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
436   Type *      VoidTy = Type::getVoidTy(*C);
437   IRBuilder<> IRB(*C);
438   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
439   Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
440   Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
441   Int1PtrTy = PointerType::getUnqual(IRB.getInt1Ty());
442   Int64Ty = IRB.getInt64Ty();
443   Int32Ty = IRB.getInt32Ty();
444   Int16Ty = IRB.getInt16Ty();
445   Int8Ty = IRB.getInt8Ty();
446   Int1Ty = IRB.getInt1Ty();
447   LLVMContext &Ctx = M.getContext();
448 
449   AFLMapPtr =
450       new GlobalVariable(M, PointerType::get(Int8Ty, 0), false,
451                          GlobalValue::ExternalLinkage, 0, "__afl_area_ptr");
452   One = ConstantInt::get(IntegerType::getInt8Ty(Ctx), 1);
453   Zero = ConstantInt::get(IntegerType::getInt8Ty(Ctx), 0);
454 
455   SanCovTracePCIndir =
456       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
457   // Make sure smaller parameters are zero-extended to i64 if required by the
458   // target ABI.
459   AttributeList SanCovTraceCmpZeroExtAL;
460   SanCovTraceCmpZeroExtAL =
461       SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
462   SanCovTraceCmpZeroExtAL =
463       SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
464 
465   SanCovTraceCmpFunction[0] =
466       M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
467                             IRB.getInt8Ty(), IRB.getInt8Ty());
468   SanCovTraceCmpFunction[1] =
469       M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
470                             IRB.getInt16Ty(), IRB.getInt16Ty());
471   SanCovTraceCmpFunction[2] =
472       M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
473                             IRB.getInt32Ty(), IRB.getInt32Ty());
474   SanCovTraceCmpFunction[3] =
475       M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
476 
477   SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
478       SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
479   SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
480       SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
481   SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
482       SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
483   SanCovTraceConstCmpFunction[3] =
484       M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
485 
486   {
487 
488     AttributeList AL;
489     AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
490     SanCovTraceDivFunction[0] =
491         M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
492 
493   }
494 
495   SanCovTraceDivFunction[1] =
496       M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
497   SanCovTraceGepFunction =
498       M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
499   SanCovTraceSwitchFunction =
500       M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
501 
502   Constant *SanCovLowestStackConstant =
503       M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
504   SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
505   if (!SanCovLowestStack) {
506 
507     C->emitError(StringRef("'") + SanCovLowestStackName +
508                  "' should not be declared by the user");
509     return true;
510 
511   }
512 
513   SanCovLowestStack->setThreadLocalMode(
514       GlobalValue::ThreadLocalMode::InitialExecTLSModel);
515   if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
516     SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
517 
518   SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
519   SanCovTracePCGuard =
520       M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
521 
522   for (auto &F : M)
523     instrumentFunction(F, DTCallback, PDTCallback);
524 
525   Function *Ctor = nullptr;
526 
527   if (FunctionGuardArray)
528     Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
529                                       SanCovTracePCGuardInitName, Int32PtrTy,
530                                       SanCovGuardsSectionName);
531   if (Function8bitCounterArray)
532     Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
533                                       SanCov8bitCountersInitName, Int8PtrTy,
534                                       SanCovCountersSectionName);
535   if (FunctionBoolArray) {
536 
537     Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
538                                       SanCovBoolFlagInitName, Int1PtrTy,
539                                       SanCovBoolFlagSectionName);
540 
541   }
542 
543   if (Ctor && Options.PCTable) {
544 
545     auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
546     FunctionCallee InitFunction = declareSanitizerInitFunction(
547         M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
548     IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
549     IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
550 
551   }
552 
553   // We don't reference these arrays directly in any of our runtime functions,
554   // so we need to prevent them from being dead stripped.
555   if (TargetTriple.isOSBinFormatMachO()) appendToUsed(M, GlobalsToAppendToUsed);
556   appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
557 
558   if (!be_quiet) {
559 
560     if (!instr)
561       WARNF("No instrumentation targets found.");
562     else {
563 
564       char modeline[100];
565       snprintf(modeline, sizeof(modeline), "%s%s%s%s%s%s",
566                getenv("AFL_HARDEN") ? "hardened" : "non-hardened",
567                getenv("AFL_USE_ASAN") ? ", ASAN" : "",
568                getenv("AFL_USE_MSAN") ? ", MSAN" : "",
569                getenv("AFL_USE_TSAN") ? ", TSAN" : "",
570                getenv("AFL_USE_CFISAN") ? ", CFISAN" : "",
571                getenv("AFL_USE_UBSAN") ? ", UBSAN" : "");
572       OKF("Instrumented %u locations with no collisions (%s mode) of which are "
573           "%u handled and %u unhandled selects.",
574           instr, modeline, selects, unhandled);
575 
576     }
577 
578   }
579 
580   return true;
581 
582 }
583 
584 // True if block has successors and it dominates all of them.
isFullDominator(const BasicBlock * BB,const DominatorTree * DT)585 bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
586 
587   if (succ_begin(BB) == succ_end(BB)) return false;
588 
589   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
590 
591     if (!DT->dominates(BB, SUCC)) return false;
592 
593   }
594 
595   return true;
596 
597 }
598 
599 // True if block has predecessors and it postdominates all of them.
isFullPostDominator(const BasicBlock * BB,const PostDominatorTree * PDT)600 bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree *PDT) {
601 
602   if (pred_begin(BB) == pred_end(BB)) return false;
603 
604   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
605 
606     if (!PDT->dominates(BB, PRED)) return false;
607 
608   }
609 
610   return true;
611 
612 }
613 
shouldInstrumentBlock(const Function & F,const BasicBlock * BB,const DominatorTree * DT,const PostDominatorTree * PDT,const SanitizerCoverageOptions & Options)614 bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
615                            const DominatorTree *           DT,
616                            const PostDominatorTree *       PDT,
617                            const SanitizerCoverageOptions &Options) {
618 
619   // Don't insert coverage for blocks containing nothing but unreachable: we
620   // will never call __sanitizer_cov() for them, so counting them in
621   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
622   // percentage. Also, unreachable instructions frequently have no debug
623   // locations.
624   if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime())) return false;
625 
626   // Don't insert coverage into blocks without a valid insertion point
627   // (catchswitch blocks).
628   if (BB->getFirstInsertionPt() == BB->end()) return false;
629 
630   if (Options.NoPrune || &F.getEntryBlock() == BB) return true;
631 
632   if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
633       &F.getEntryBlock() != BB)
634     return false;
635 
636   // Do not instrument full dominators, or full post-dominators with multiple
637   // predecessors.
638   return !isFullDominator(BB, DT) &&
639          !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
640 
641 }
642 
643 // Returns true iff From->To is a backedge.
644 // A twist here is that we treat From->To as a backedge if
645 //   * To dominates From or
646 //   * To->UniqueSuccessor dominates From
IsBackEdge(BasicBlock * From,BasicBlock * To,const DominatorTree * DT)647 bool IsBackEdge(BasicBlock *From, BasicBlock *To, const DominatorTree *DT) {
648 
649   if (DT->dominates(To, From)) return true;
650   if (auto Next = To->getUniqueSuccessor())
651     if (DT->dominates(Next, From)) return true;
652   return false;
653 
654 }
655 
656 // Prunes uninteresting Cmp instrumentation:
657 //   * CMP instructions that feed into loop backedge branch.
658 //
659 // Note that Cmp pruning is controlled by the same flag as the
660 // BB pruning.
IsInterestingCmp(ICmpInst * CMP,const DominatorTree * DT,const SanitizerCoverageOptions & Options)661 bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT,
662                       const SanitizerCoverageOptions &Options) {
663 
664   if (!Options.NoPrune)
665     if (CMP->hasOneUse())
666       if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
667         for (BasicBlock *B : BR->successors())
668           if (IsBackEdge(BR->getParent(), B, DT)) return false;
669   return true;
670 
671 }
672 
instrumentFunction(Function & F,DomTreeCallback DTCallback,PostDomTreeCallback PDTCallback)673 void ModuleSanitizerCoverageAFL::instrumentFunction(
674     Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
675 
676   if (F.empty()) return;
677   if (!isInInstrumentList(&F, FMNAME)) return;
678 
679   if (F.getName().find(".module_ctor") != std::string::npos)
680     return;  // Should not instrument sanitizer init functions.
681   if (F.getName().startswith("__sanitizer_"))
682     return;  // Don't instrument __sanitizer_* callbacks.
683   // Don't touch available_externally functions, their actual body is elewhere.
684   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return;
685   // Don't instrument MSVC CRT configuration helpers. They may run before normal
686   // initialization.
687   if (F.getName() == "__local_stdio_printf_options" ||
688       F.getName() == "__local_stdio_scanf_options")
689     return;
690   if (isa<UnreachableInst>(F.getEntryBlock().getTerminator())) return;
691   // Don't instrument functions using SEH for now. Splitting basic blocks like
692   // we do for coverage breaks WinEHPrepare.
693   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
694   if (F.hasPersonalityFn() &&
695       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
696     return;
697   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
698     SplitAllCriticalEdges(
699         F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
700   SmallVector<Instruction *, 8>       IndirCalls;
701   SmallVector<BasicBlock *, 16>       BlocksToInstrument;
702   SmallVector<Instruction *, 8>       CmpTraceTargets;
703   SmallVector<Instruction *, 8>       SwitchTraceTargets;
704   SmallVector<BinaryOperator *, 8>    DivTraceTargets;
705   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
706 
707   const DominatorTree *    DT = DTCallback(F);
708   const PostDominatorTree *PDT = PDTCallback(F);
709   bool                     IsLeafFunc = true;
710 
711   for (auto &BB : F) {
712 
713     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
714       BlocksToInstrument.push_back(&BB);
715     for (auto &Inst : BB) {
716 
717       if (Options.IndirectCalls) {
718 
719         CallBase *CB = dyn_cast<CallBase>(&Inst);
720         if (CB && !CB->getCalledFunction()) IndirCalls.push_back(&Inst);
721 
722       }
723 
724       if (Options.TraceCmp) {
725 
726         if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
727           if (IsInterestingCmp(CMP, DT, Options))
728             CmpTraceTargets.push_back(&Inst);
729         if (isa<SwitchInst>(&Inst)) SwitchTraceTargets.push_back(&Inst);
730 
731       }
732 
733       if (Options.TraceDiv)
734         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
735           if (BO->getOpcode() == Instruction::SDiv ||
736               BO->getOpcode() == Instruction::UDiv)
737             DivTraceTargets.push_back(BO);
738       if (Options.TraceGep)
739         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
740           GepTraceTargets.push_back(GEP);
741       if (Options.StackDepth)
742         if (isa<InvokeInst>(Inst) ||
743             (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
744           IsLeafFunc = false;
745 
746     }
747 
748   }
749 
750   InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
751   InjectCoverageForIndirectCalls(F, IndirCalls);
752   InjectTraceForCmp(F, CmpTraceTargets);
753   InjectTraceForSwitch(F, SwitchTraceTargets);
754   InjectTraceForDiv(F, DivTraceTargets);
755   InjectTraceForGep(F, GepTraceTargets);
756 
757 }
758 
CreateFunctionLocalArrayInSection(size_t NumElements,Function & F,Type * Ty,const char * Section)759 GlobalVariable *ModuleSanitizerCoverageAFL::CreateFunctionLocalArrayInSection(
760     size_t NumElements, Function &F, Type *Ty, const char *Section) {
761 
762   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
763   auto       Array = new GlobalVariable(
764       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
765       Constant::getNullValue(ArrayTy), "__sancov_gen_");
766 
767 #if LLVM_VERSION_MAJOR >= 13
768   if (TargetTriple.supportsCOMDAT() &&
769       (TargetTriple.isOSBinFormatELF() || !F.isInterposable()))
770     if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
771       Array->setComdat(Comdat);
772 #else
773   if (TargetTriple.supportsCOMDAT() && !F.isInterposable())
774     if (auto Comdat =
775             GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId))
776       Array->setComdat(Comdat);
777 #endif
778 
779   Array->setSection(getSectionName(Section));
780 #if (LLVM_VERSION_MAJOR >= 11) || \
781     (LLVM_VERSION_MAJOR == 10 && LLVM_VERSION_MINOR >= 1)
782   Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedSize()));
783 #else
784   Array->setAlignment(Align(4));  // cheating
785 #endif
786   GlobalsToAppendToUsed.push_back(Array);
787   GlobalsToAppendToCompilerUsed.push_back(Array);
788   MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
789   Array->addMetadata(LLVMContext::MD_associated, *MD);
790 
791   return Array;
792 
793 }
794 
CreatePCArray(Function & F,ArrayRef<BasicBlock * > AllBlocks)795 GlobalVariable *ModuleSanitizerCoverageAFL::CreatePCArray(
796     Function &F, ArrayRef<BasicBlock *> AllBlocks) {
797 
798   size_t N = AllBlocks.size();
799   assert(N);
800   SmallVector<Constant *, 32> PCs;
801   IRBuilder<>                 IRB(&*F.getEntryBlock().getFirstInsertionPt());
802   for (size_t i = 0; i < N; i++) {
803 
804     if (&F.getEntryBlock() == AllBlocks[i]) {
805 
806       PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
807       PCs.push_back((Constant *)IRB.CreateIntToPtr(
808           ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
809 
810     } else {
811 
812       PCs.push_back((Constant *)IRB.CreatePointerCast(
813           BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
814       PCs.push_back((Constant *)IRB.CreateIntToPtr(
815           ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
816 
817     }
818 
819   }
820 
821   auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
822                                                     SanCovPCsSectionName);
823   PCArray->setInitializer(
824       ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
825   PCArray->setConstant(true);
826 
827   return PCArray;
828 
829 }
830 
CreateFunctionLocalArrays(Function & F,ArrayRef<BasicBlock * > AllBlocks,uint32_t special)831 void ModuleSanitizerCoverageAFL::CreateFunctionLocalArrays(
832     Function &F, ArrayRef<BasicBlock *> AllBlocks, uint32_t special) {
833 
834   if (Options.TracePCGuard)
835     FunctionGuardArray = CreateFunctionLocalArrayInSection(
836         AllBlocks.size() + special, F, Int32Ty, SanCovGuardsSectionName);
837 
838   if (Options.Inline8bitCounters)
839     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
840         AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
841   /*
842     if (Options.InlineBoolFlag)
843       FunctionBoolArray = CreateFunctionLocalArrayInSection(
844           AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
845   */
846   if (Options.PCTable) FunctionPCsArray = CreatePCArray(F, AllBlocks);
847 
848 }
849 
InjectCoverage(Function & F,ArrayRef<BasicBlock * > AllBlocks,bool IsLeafFunc)850 bool ModuleSanitizerCoverageAFL::InjectCoverage(
851     Function &F, ArrayRef<BasicBlock *> AllBlocks, bool IsLeafFunc) {
852 
853   uint32_t cnt_cov = 0, cnt_sel = 0, cnt_sel_inc = 0;
854 
855   for (auto &BB : F) {
856 
857     for (auto &IN : BB) {
858 
859       CallInst *callInst = nullptr;
860 
861       if ((callInst = dyn_cast<CallInst>(&IN))) {
862 
863         Function *Callee = callInst->getCalledFunction();
864         if (!Callee) continue;
865         if (callInst->getCallingConv() != llvm::CallingConv::C) continue;
866         StringRef FuncName = Callee->getName();
867         if (!FuncName.compare(StringRef("dlopen")) ||
868             !FuncName.compare(StringRef("_dlopen"))) {
869 
870           fprintf(stderr,
871                   "WARNING: dlopen() detected. To have coverage for a library "
872                   "that your target dlopen()'s this must either happen before "
873                   "__AFL_INIT() or you must use AFL_PRELOAD to preload all "
874                   "dlopen()'ed libraries!\n");
875           continue;
876 
877         }
878 
879         if (FuncName.compare(StringRef("__afl_coverage_interesting"))) continue;
880 
881         cnt_cov++;
882 
883       }
884 
885       SelectInst *selectInst = nullptr;
886 
887       if ((selectInst = dyn_cast<SelectInst>(&IN))) {
888 
889         Value *c = selectInst->getCondition();
890         auto   t = c->getType();
891         if (t->getTypeID() == llvm::Type::IntegerTyID) {
892 
893           cnt_sel++;
894           cnt_sel_inc += 2;
895 
896         }
897 
898 #if (LLVM_VERSION_MAJOR >= 12)
899         else if (t->getTypeID() == llvm::Type::FixedVectorTyID) {
900 
901           FixedVectorType *tt = dyn_cast<FixedVectorType>(t);
902           if (tt) {
903 
904             cnt_sel++;
905             cnt_sel_inc += tt->getElementCount().getKnownMinValue();
906 
907           }
908 
909         }
910 
911 #endif
912 
913       }
914 
915     }
916 
917   }
918 
919   /* Create PCGUARD array */
920   CreateFunctionLocalArrays(F, AllBlocks, cnt_cov + cnt_sel_inc);
921   selects += cnt_sel;
922 
923   uint32_t special = 0, local_selects = 0, skip_next = 0;
924 
925   for (auto &BB : F) {
926 
927     for (auto &IN : BB) {
928 
929       CallInst *callInst = nullptr;
930 
931       /*
932                                 std::string errMsg;
933                                 raw_string_ostream os(errMsg);
934                             IN.print(os);
935                             fprintf(stderr, "X: %s\n", os.str().c_str());
936       */
937       if ((callInst = dyn_cast<CallInst>(&IN))) {
938 
939         Function *Callee = callInst->getCalledFunction();
940         if (!Callee) continue;
941         if (callInst->getCallingConv() != llvm::CallingConv::C) continue;
942         StringRef FuncName = Callee->getName();
943         if (FuncName.compare(StringRef("__afl_coverage_interesting"))) continue;
944 
945         IRBuilder<> IRB(callInst);
946 
947         if (!FunctionGuardArray) {
948 
949           fprintf(stderr,
950                   "SANCOV: FunctionGuardArray is NULL, failed to emit "
951                   "instrumentation.");
952           continue;
953 
954         }
955 
956         Value *GuardPtr = IRB.CreateIntToPtr(
957             IRB.CreateAdd(
958                 IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
959                 ConstantInt::get(IntptrTy, (++special + AllBlocks.size()) * 4)),
960             Int32PtrTy);
961 
962         LoadInst *Idx = IRB.CreateLoad(IRB.getInt32Ty(), GuardPtr);
963         ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(Idx);
964 
965         callInst->setOperand(1, Idx);
966 
967       }
968 
969       SelectInst *selectInst = nullptr;
970 
971       if (!skip_next && (selectInst = dyn_cast<SelectInst>(&IN))) {
972 
973         uint32_t    vector_cnt = 0;
974         Value *     condition = selectInst->getCondition();
975         Value *     result;
976         auto        t = condition->getType();
977         IRBuilder<> IRB(selectInst->getNextNode());
978 
979         if (t->getTypeID() == llvm::Type::IntegerTyID) {
980 
981           if (!FunctionGuardArray) {
982 
983             fprintf(stderr,
984                     "SANCOV: FunctionGuardArray is NULL, failed to emit "
985                     "instrumentation.");
986             continue;
987 
988           }
989 
990           auto GuardPtr1 = IRB.CreateIntToPtr(
991               IRB.CreateAdd(
992                   IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
993                   ConstantInt::get(
994                       IntptrTy,
995                       (cnt_cov + ++local_selects + AllBlocks.size()) * 4)),
996               Int32PtrTy);
997 
998           auto GuardPtr2 = IRB.CreateIntToPtr(
999               IRB.CreateAdd(
1000                   IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
1001                   ConstantInt::get(
1002                       IntptrTy,
1003                       (cnt_cov + ++local_selects + AllBlocks.size()) * 4)),
1004               Int32PtrTy);
1005 
1006           result = IRB.CreateSelect(condition, GuardPtr1, GuardPtr2);
1007 
1008         } else
1009 
1010 #if LLVM_VERSION_MAJOR >= 14
1011             if (t->getTypeID() == llvm::Type::FixedVectorTyID) {
1012 
1013           FixedVectorType *tt = dyn_cast<FixedVectorType>(t);
1014           if (tt) {
1015 
1016             uint32_t elements = tt->getElementCount().getFixedValue();
1017             vector_cnt = elements;
1018             if (elements) {
1019 
1020               FixedVectorType *GuardPtr1 =
1021                   FixedVectorType::get(Int32PtrTy, elements);
1022               FixedVectorType *GuardPtr2 =
1023                   FixedVectorType::get(Int32PtrTy, elements);
1024               Value *x, *y;
1025 
1026               if (!FunctionGuardArray) {
1027 
1028                 fprintf(stderr,
1029                         "SANCOV: FunctionGuardArray is NULL, failed to emit "
1030                         "instrumentation.");
1031                 continue;
1032 
1033               }
1034 
1035               Value *val1 = IRB.CreateIntToPtr(
1036                   IRB.CreateAdd(
1037                       IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
1038                       ConstantInt::get(
1039                           IntptrTy,
1040                           (cnt_cov + ++local_selects + AllBlocks.size()) * 4)),
1041                   Int32PtrTy);
1042               x = IRB.CreateInsertElement(GuardPtr1, val1, (uint64_t)0);
1043 
1044               Value *val2 = IRB.CreateIntToPtr(
1045                   IRB.CreateAdd(
1046                       IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
1047                       ConstantInt::get(
1048                           IntptrTy,
1049                           (cnt_cov + ++local_selects + AllBlocks.size()) * 4)),
1050                   Int32PtrTy);
1051               y = IRB.CreateInsertElement(GuardPtr2, val2, (uint64_t)0);
1052 
1053               for (uint64_t i = 1; i < elements; i++) {
1054 
1055                 val1 = IRB.CreateIntToPtr(
1056                     IRB.CreateAdd(
1057                         IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
1058                         ConstantInt::get(IntptrTy, (cnt_cov + ++local_selects +
1059                                                     AllBlocks.size()) *
1060                                                        4)),
1061                     Int32PtrTy);
1062                 x = IRB.CreateInsertElement(x, val1, i);
1063 
1064                 val2 = IRB.CreateIntToPtr(
1065                     IRB.CreateAdd(
1066                         IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
1067                         ConstantInt::get(IntptrTy, (cnt_cov + ++local_selects +
1068                                                     AllBlocks.size()) *
1069                                                        4)),
1070                     Int32PtrTy);
1071                 y = IRB.CreateInsertElement(y, val2, i);
1072 
1073               }
1074 
1075               /*
1076                           std::string errMsg;
1077                           raw_string_ostream os(errMsg);
1078                       x->print(os);
1079                       fprintf(stderr, "X: %s\n", os.str().c_str());
1080               */
1081               result = IRB.CreateSelect(condition, x, y);
1082 
1083             }
1084 
1085           }
1086 
1087         } else
1088 
1089 #endif
1090         {
1091 
1092           unhandled++;
1093           continue;
1094 
1095         }
1096 
1097         uint32_t vector_cur = 0;
1098 
1099         /* Load SHM pointer */
1100 
1101         LoadInst *MapPtr =
1102             IRB.CreateLoad(PointerType::get(Int8Ty, 0), AFLMapPtr);
1103         ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(MapPtr);
1104 
1105         /*
1106             std::string errMsg;
1107             raw_string_ostream os(errMsg);
1108         result->print(os);
1109         fprintf(stderr, "X: %s\n", os.str().c_str());
1110         */
1111 
1112         while (1) {
1113 
1114           /* Get CurLoc */
1115           LoadInst *CurLoc = nullptr;
1116           Value *   MapPtrIdx = nullptr;
1117 
1118           /* Load counter for CurLoc */
1119           if (!vector_cnt) {
1120 
1121             CurLoc = IRB.CreateLoad(IRB.getInt32Ty(), result);
1122             ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(CurLoc);
1123             MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, CurLoc);
1124 
1125           } else {
1126 
1127             auto element = IRB.CreateExtractElement(result, vector_cur++);
1128             auto elementptr = IRB.CreateIntToPtr(element, Int32PtrTy);
1129             auto elementld = IRB.CreateLoad(IRB.getInt32Ty(), elementptr);
1130             ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(elementld);
1131             MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, elementld);
1132 
1133           }
1134 
1135           if (use_threadsafe_counters) {
1136 
1137             IRB.CreateAtomicRMW(llvm::AtomicRMWInst::BinOp::Add, MapPtrIdx, One,
1138 #if LLVM_VERSION_MAJOR >= 13
1139                                 llvm::MaybeAlign(1),
1140 #endif
1141                                 llvm::AtomicOrdering::Monotonic);
1142 
1143           } else {
1144 
1145             LoadInst *Counter = IRB.CreateLoad(IRB.getInt8Ty(), MapPtrIdx);
1146             ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(Counter);
1147 
1148             /* Update bitmap */
1149 
1150             Value *Incr = IRB.CreateAdd(Counter, One);
1151 
1152             if (skip_nozero == NULL) {
1153 
1154               auto cf = IRB.CreateICmpEQ(Incr, Zero);
1155               auto carry = IRB.CreateZExt(cf, Int8Ty);
1156               Incr = IRB.CreateAdd(Incr, carry);
1157 
1158             }
1159 
1160             StoreInst *StoreCtx = IRB.CreateStore(Incr, MapPtrIdx);
1161             ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(StoreCtx);
1162 
1163           }
1164 
1165           if (!vector_cnt) {
1166 
1167             vector_cnt = 2;
1168             break;
1169 
1170           } else if (vector_cnt == vector_cur) {
1171 
1172             break;
1173 
1174           }
1175 
1176         }
1177 
1178         skip_next = 1;
1179         instr += vector_cnt;
1180 
1181       } else {
1182 
1183         skip_next = 0;
1184 
1185       }
1186 
1187     }
1188 
1189   }
1190 
1191   if (AllBlocks.empty() && !special && !local_selects) return false;
1192 
1193   if (!AllBlocks.empty())
1194     for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
1195       InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
1196 
1197   return true;
1198 
1199 }
1200 
1201 // On every indirect call we call a run-time function
1202 // __sanitizer_cov_indir_call* with two parameters:
1203 //   - callee address,
1204 //   - global cache array that contains CacheSize pointers (zero-initialized).
1205 //     The cache is used to speed up recording the caller-callee pairs.
1206 // The address of the caller is passed implicitly via caller PC.
1207 // CacheSize is encoded in the name of the run-time function.
InjectCoverageForIndirectCalls(Function & F,ArrayRef<Instruction * > IndirCalls)1208 void ModuleSanitizerCoverageAFL::InjectCoverageForIndirectCalls(
1209     Function &F, ArrayRef<Instruction *> IndirCalls) {
1210 
1211   if (IndirCalls.empty()) return;
1212   for (auto I : IndirCalls) {
1213 
1214     IRBuilder<> IRB(I);
1215     CallBase &  CB = cast<CallBase>(*I);
1216     Value *     Callee = CB.getCalledOperand();
1217     if (isa<InlineAsm>(Callee)) continue;
1218     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
1219 
1220   }
1221 
1222 }
1223 
1224 // For every switch statement we insert a call:
1225 // __sanitizer_cov_trace_switch(CondValue,
1226 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
1227 
InjectTraceForSwitch(Function &,ArrayRef<Instruction * > SwitchTraceTargets)1228 void ModuleSanitizerCoverageAFL::InjectTraceForSwitch(
1229     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
1230 
1231   for (auto I : SwitchTraceTargets) {
1232 
1233     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1234 
1235       IRBuilder<>                 IRB(I);
1236       SmallVector<Constant *, 16> Initializers;
1237       Value *                     Cond = SI->getCondition();
1238       if (Cond->getType()->getScalarSizeInBits() >
1239           Int64Ty->getScalarSizeInBits())
1240         continue;
1241       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
1242       Initializers.push_back(
1243           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
1244       if (Cond->getType()->getScalarSizeInBits() <
1245           Int64Ty->getScalarSizeInBits())
1246         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
1247       for (auto It : SI->cases()) {
1248 
1249         Constant *C = It.getCaseValue();
1250         if (C->getType()->getScalarSizeInBits() <
1251             Int64Ty->getScalarSizeInBits())
1252           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
1253         Initializers.push_back(C);
1254 
1255       }
1256 
1257       llvm::sort(drop_begin(Initializers, 2),
1258                  [](const Constant *A, const Constant *B) {
1259 
1260                    return cast<ConstantInt>(A)->getLimitedValue() <
1261                           cast<ConstantInt>(B)->getLimitedValue();
1262 
1263                  });
1264 
1265       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
1266       GlobalVariable *GV = new GlobalVariable(
1267           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
1268           ConstantArray::get(ArrayOfInt64Ty, Initializers),
1269           "__sancov_gen_cov_switch_values");
1270       IRB.CreateCall(SanCovTraceSwitchFunction,
1271                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
1272 
1273     }
1274 
1275   }
1276 
1277 }
1278 
InjectTraceForDiv(Function &,ArrayRef<BinaryOperator * > DivTraceTargets)1279 void ModuleSanitizerCoverageAFL::InjectTraceForDiv(
1280     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
1281 
1282   for (auto BO : DivTraceTargets) {
1283 
1284     IRBuilder<> IRB(BO);
1285     Value *     A1 = BO->getOperand(1);
1286     if (isa<ConstantInt>(A1)) continue;
1287     if (!A1->getType()->isIntegerTy()) continue;
1288     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
1289     int      CallbackIdx = TypeSize == 32 ? 0 : TypeSize == 64 ? 1 : -1;
1290     if (CallbackIdx < 0) continue;
1291     auto Ty = Type::getIntNTy(*C, TypeSize);
1292     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
1293                    {IRB.CreateIntCast(A1, Ty, true)});
1294 
1295   }
1296 
1297 }
1298 
InjectTraceForGep(Function &,ArrayRef<GetElementPtrInst * > GepTraceTargets)1299 void ModuleSanitizerCoverageAFL::InjectTraceForGep(
1300     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
1301 
1302   for (auto GEP : GepTraceTargets) {
1303 
1304     IRBuilder<> IRB(GEP);
1305     for (Use &Idx : GEP->indices())
1306       if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
1307         IRB.CreateCall(SanCovTraceGepFunction,
1308                        {IRB.CreateIntCast(Idx, IntptrTy, true)});
1309 
1310   }
1311 
1312 }
1313 
InjectTraceForCmp(Function &,ArrayRef<Instruction * > CmpTraceTargets)1314 void ModuleSanitizerCoverageAFL::InjectTraceForCmp(
1315     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
1316 
1317   for (auto I : CmpTraceTargets) {
1318 
1319     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
1320 
1321       IRBuilder<> IRB(ICMP);
1322       Value *     A0 = ICMP->getOperand(0);
1323       Value *     A1 = ICMP->getOperand(1);
1324       if (!A0->getType()->isIntegerTy()) continue;
1325       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
1326       int      CallbackIdx = TypeSize == 8    ? 0
1327                              : TypeSize == 16 ? 1
1328                              : TypeSize == 32 ? 2
1329                              : TypeSize == 64 ? 3
1330                                               : -1;
1331       if (CallbackIdx < 0) continue;
1332       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
1333       auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
1334       bool FirstIsConst = isa<ConstantInt>(A0);
1335       bool SecondIsConst = isa<ConstantInt>(A1);
1336       // If both are const, then we don't need such a comparison.
1337       if (FirstIsConst && SecondIsConst) continue;
1338       // If only one is const, then make it the first callback argument.
1339       if (FirstIsConst || SecondIsConst) {
1340 
1341         CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
1342         if (SecondIsConst) std::swap(A0, A1);
1343 
1344       }
1345 
1346       auto Ty = Type::getIntNTy(*C, TypeSize);
1347       IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
1348                                     IRB.CreateIntCast(A1, Ty, true)});
1349 
1350     }
1351 
1352   }
1353 
1354 }
1355 
InjectCoverageAtBlock(Function & F,BasicBlock & BB,size_t Idx,bool IsLeafFunc)1356 void ModuleSanitizerCoverageAFL::InjectCoverageAtBlock(Function &  F,
1357                                                        BasicBlock &BB,
1358                                                        size_t      Idx,
1359                                                        bool        IsLeafFunc) {
1360 
1361   BasicBlock::iterator IP = BB.getFirstInsertionPt();
1362   bool                 IsEntryBB = &BB == &F.getEntryBlock();
1363 
1364   if (IsEntryBB) {
1365 
1366     // Keep allocas and llvm.localescape calls in the entry block.  Even
1367     // if we aren't splitting the block, it's nice for allocas to be before
1368     // calls.
1369     IP = PrepareToSplitEntryBlock(BB, IP);
1370 
1371   }
1372 
1373   IRBuilder<> IRB(&*IP);
1374 
1375   if (Options.TracePC) {
1376 
1377     IRB.CreateCall(SanCovTracePC);
1378     //        ->setCannotMerge();  // gets the PC using GET_CALLER_PC.
1379 
1380   }
1381 
1382   if (Options.TracePCGuard) {
1383 
1384     /* Get CurLoc */
1385 
1386     Value *GuardPtr = IRB.CreateIntToPtr(
1387         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
1388                       ConstantInt::get(IntptrTy, Idx * 4)),
1389         Int32PtrTy);
1390 
1391     LoadInst *CurLoc = IRB.CreateLoad(IRB.getInt32Ty(), GuardPtr);
1392     ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(CurLoc);
1393 
1394     /* Load SHM pointer */
1395 
1396     LoadInst *MapPtr = IRB.CreateLoad(PointerType::get(Int8Ty, 0), AFLMapPtr);
1397     ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(MapPtr);
1398 
1399     /* Load counter for CurLoc */
1400 
1401     Value *MapPtrIdx = IRB.CreateGEP(Int8Ty, MapPtr, CurLoc);
1402 
1403     if (use_threadsafe_counters) {
1404 
1405       IRB.CreateAtomicRMW(llvm::AtomicRMWInst::BinOp::Add, MapPtrIdx, One,
1406 #if LLVM_VERSION_MAJOR >= 13
1407                           llvm::MaybeAlign(1),
1408 #endif
1409                           llvm::AtomicOrdering::Monotonic);
1410 
1411     } else {
1412 
1413       LoadInst *Counter = IRB.CreateLoad(IRB.getInt8Ty(), MapPtrIdx);
1414       ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(Counter);
1415 
1416       /* Update bitmap */
1417 
1418       Value *Incr = IRB.CreateAdd(Counter, One);
1419 
1420       if (skip_nozero == NULL) {
1421 
1422         auto cf = IRB.CreateICmpEQ(Incr, Zero);
1423         auto carry = IRB.CreateZExt(cf, Int8Ty);
1424         Incr = IRB.CreateAdd(Incr, carry);
1425 
1426       }
1427 
1428       StoreInst *StoreCtx = IRB.CreateStore(Incr, MapPtrIdx);
1429       ModuleSanitizerCoverageAFL::SetNoSanitizeMetadata(StoreCtx);
1430 
1431     }
1432 
1433     // done :)
1434 
1435     //    IRB.CreateCall(SanCovTracePCGuard, Offset)->setCannotMerge();
1436     //    IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
1437     ++instr;
1438 
1439   }
1440 
1441   if (Options.Inline8bitCounters) {
1442 
1443     auto CounterPtr = IRB.CreateGEP(
1444         Function8bitCounterArray->getValueType(), Function8bitCounterArray,
1445         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1446     auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
1447     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
1448     auto Store = IRB.CreateStore(Inc, CounterPtr);
1449     SetNoSanitizeMetadata(Load);
1450     SetNoSanitizeMetadata(Store);
1451 
1452   }
1453 
1454   /*
1455     if (Options.InlineBoolFlag) {
1456 
1457       auto FlagPtr = IRB.CreateGEP(
1458           FunctionBoolArray->getValueType(), FunctionBoolArray,
1459           {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
1460       auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
1461       auto ThenTerm =
1462           SplitBlockAndInsertIfThen(IRB.CreateIsNull(Load), &*IP, false);
1463       IRBuilder<> ThenIRB(ThenTerm);
1464       auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
1465       SetNoSanitizeMetadata(Load);
1466       SetNoSanitizeMetadata(Store);
1467 
1468     }
1469 
1470   */
1471 
1472   if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
1473 
1474     // Check stack depth.  If it's the deepest so far, record it.
1475     Module *  M = F.getParent();
1476     Function *GetFrameAddr = Intrinsic::getDeclaration(
1477         M, Intrinsic::frameaddress,
1478         IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
1479     auto FrameAddrPtr =
1480         IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
1481     auto        FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
1482     auto        LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
1483     auto        IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
1484     auto        ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
1485     IRBuilder<> ThenIRB(ThenTerm);
1486     auto        Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
1487     SetNoSanitizeMetadata(LowestStack);
1488     SetNoSanitizeMetadata(Store);
1489 
1490   }
1491 
1492 }
1493 
getSectionName(const std::string & Section) const1494 std::string ModuleSanitizerCoverageAFL::getSectionName(
1495     const std::string &Section) const {
1496 
1497   if (TargetTriple.isOSBinFormatCOFF()) {
1498 
1499     if (Section == SanCovCountersSectionName) return ".SCOV$CM";
1500     if (Section == SanCovBoolFlagSectionName) return ".SCOV$BM";
1501     if (Section == SanCovPCsSectionName) return ".SCOVP$M";
1502     return ".SCOV$GM";  // For SanCovGuardsSectionName.
1503 
1504   }
1505 
1506   if (TargetTriple.isOSBinFormatMachO()) return "__DATA,__" + Section;
1507   return "__" + Section;
1508 
1509 }
1510 
getSectionStart(const std::string & Section) const1511 std::string ModuleSanitizerCoverageAFL::getSectionStart(
1512     const std::string &Section) const {
1513 
1514   if (TargetTriple.isOSBinFormatMachO())
1515     return "\1section$start$__DATA$__" + Section;
1516   return "__start___" + Section;
1517 
1518 }
1519 
getSectionEnd(const std::string & Section) const1520 std::string ModuleSanitizerCoverageAFL::getSectionEnd(
1521     const std::string &Section) const {
1522 
1523   if (TargetTriple.isOSBinFormatMachO())
1524     return "\1section$end$__DATA$__" + Section;
1525   return "__stop___" + Section;
1526 
1527 }
1528 
1529 #if 0
1530 
1531 char ModuleSanitizerCoverageLegacyPass::ID = 0;
1532 INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov",
1533                       "Pass for instrumenting coverage on functions", false,
1534                       false)
1535 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1536 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
1537 INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov",
1538                     "Pass for instrumenting coverage on functions", false,
1539                     false)
1540 ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass(
1541     const SanitizerCoverageOptions &Options,
1542     const std::vector<std::string> &AllowlistFiles,
1543     const std::vector<std::string> &BlocklistFiles) {
1544 
1545   return new ModuleSanitizerCoverageLegacyPass(Options, AllowlistFiles,
1546                                                BlocklistFiles);
1547 
1548 }
1549 
1550 #endif
1551 
1552