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