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 InlineAsm *EmptyAsm; 254 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy, 255 *Int16Ty, *Int8Ty, *Int8PtrTy, *Int1Ty, *Int1PtrTy; 256 Module *CurModule; 257 std::string CurModuleUniqueId; 258 Triple TargetTriple; 259 LLVMContext *C; 260 const DataLayout *DL; 261 262 GlobalVariable *FunctionGuardArray; // for trace-pc-guard. 263 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters. 264 GlobalVariable *FunctionBoolArray; // for inline-bool-flag. 265 GlobalVariable *FunctionPCsArray; // for pc-table. 266 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed; 267 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed; 268 269 SanitizerCoverageOptions Options; 270 271 const SpecialCaseList *Allowlist; 272 const SpecialCaseList *Blocklist; 273 }; 274 275 class ModuleSanitizerCoverageLegacyPass : public ModulePass { 276 public: 277 ModuleSanitizerCoverageLegacyPass( 278 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions(), 279 const std::vector<std::string> &AllowlistFiles = 280 std::vector<std::string>(), 281 const std::vector<std::string> &BlocklistFiles = 282 std::vector<std::string>()) 283 : ModulePass(ID), Options(Options) { 284 if (AllowlistFiles.size() > 0) 285 Allowlist = SpecialCaseList::createOrDie(AllowlistFiles, 286 *vfs::getRealFileSystem()); 287 if (BlocklistFiles.size() > 0) 288 Blocklist = SpecialCaseList::createOrDie(BlocklistFiles, 289 *vfs::getRealFileSystem()); 290 initializeModuleSanitizerCoverageLegacyPassPass( 291 *PassRegistry::getPassRegistry()); 292 } 293 bool runOnModule(Module &M) override { 294 ModuleSanitizerCoverage ModuleSancov(Options, Allowlist.get(), 295 Blocklist.get()); 296 auto DTCallback = [this](Function &F) -> const DominatorTree * { 297 return &this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); 298 }; 299 auto PDTCallback = [this](Function &F) -> const PostDominatorTree * { 300 return &this->getAnalysis<PostDominatorTreeWrapperPass>(F) 301 .getPostDomTree(); 302 }; 303 return ModuleSancov.instrumentModule(M, DTCallback, PDTCallback); 304 } 305 306 static char ID; // Pass identification, replacement for typeid 307 StringRef getPassName() const override { return "ModuleSanitizerCoverage"; } 308 309 void getAnalysisUsage(AnalysisUsage &AU) const override { 310 AU.addRequired<DominatorTreeWrapperPass>(); 311 AU.addRequired<PostDominatorTreeWrapperPass>(); 312 } 313 314 private: 315 SanitizerCoverageOptions Options; 316 317 std::unique_ptr<SpecialCaseList> Allowlist; 318 std::unique_ptr<SpecialCaseList> Blocklist; 319 }; 320 321 } // namespace 322 323 PreservedAnalyses ModuleSanitizerCoveragePass::run(Module &M, 324 ModuleAnalysisManager &MAM) { 325 ModuleSanitizerCoverage ModuleSancov(Options, Allowlist.get(), 326 Blocklist.get()); 327 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 328 auto DTCallback = [&FAM](Function &F) -> const DominatorTree * { 329 return &FAM.getResult<DominatorTreeAnalysis>(F); 330 }; 331 auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree * { 332 return &FAM.getResult<PostDominatorTreeAnalysis>(F); 333 }; 334 if (ModuleSancov.instrumentModule(M, DTCallback, PDTCallback)) 335 return PreservedAnalyses::none(); 336 return PreservedAnalyses::all(); 337 } 338 339 std::pair<Value *, Value *> 340 ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section, 341 Type *Ty) { 342 GlobalVariable *SecStart = 343 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr, 344 getSectionStart(Section)); 345 SecStart->setVisibility(GlobalValue::HiddenVisibility); 346 GlobalVariable *SecEnd = 347 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, 348 nullptr, getSectionEnd(Section)); 349 SecEnd->setVisibility(GlobalValue::HiddenVisibility); 350 IRBuilder<> IRB(M.getContext()); 351 Value *SecEndPtr = IRB.CreatePointerCast(SecEnd, Ty); 352 if (!TargetTriple.isOSBinFormatCOFF()) 353 return std::make_pair(IRB.CreatePointerCast(SecStart, Ty), SecEndPtr); 354 355 // Account for the fact that on windows-msvc __start_* symbols actually 356 // point to a uint64_t before the start of the array. 357 auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy); 358 auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr, 359 ConstantInt::get(IntptrTy, sizeof(uint64_t))); 360 return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEndPtr); 361 } 362 363 Function *ModuleSanitizerCoverage::CreateInitCallsForSections( 364 Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty, 365 const char *Section) { 366 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty); 367 auto SecStart = SecStartEnd.first; 368 auto SecEnd = SecStartEnd.second; 369 Function *CtorFunc; 370 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions( 371 M, CtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd}); 372 assert(CtorFunc->getName() == CtorName); 373 374 if (TargetTriple.supportsCOMDAT()) { 375 // Use comdat to dedup CtorFunc. 376 CtorFunc->setComdat(M.getOrInsertComdat(CtorName)); 377 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc); 378 } else { 379 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority); 380 } 381 382 if (TargetTriple.isOSBinFormatCOFF()) { 383 // In COFF files, if the contructors are set as COMDAT (they are because 384 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced 385 // functions and data) is used, the constructors get stripped. To prevent 386 // this, give the constructors weak ODR linkage and ensure the linker knows 387 // to include the sancov constructor. This way the linker can deduplicate 388 // the constructors but always leave one copy. 389 CtorFunc->setLinkage(GlobalValue::WeakODRLinkage); 390 appendToUsed(M, CtorFunc); 391 } 392 return CtorFunc; 393 } 394 395 bool ModuleSanitizerCoverage::instrumentModule( 396 Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) { 397 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None) 398 return false; 399 if (Allowlist && 400 !Allowlist->inSection("coverage", "src", M.getSourceFileName())) 401 return false; 402 if (Blocklist && 403 Blocklist->inSection("coverage", "src", M.getSourceFileName())) 404 return false; 405 C = &(M.getContext()); 406 DL = &M.getDataLayout(); 407 CurModule = &M; 408 CurModuleUniqueId = getUniqueModuleId(CurModule); 409 TargetTriple = Triple(M.getTargetTriple()); 410 FunctionGuardArray = nullptr; 411 Function8bitCounterArray = nullptr; 412 FunctionBoolArray = nullptr; 413 FunctionPCsArray = nullptr; 414 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits()); 415 IntptrPtrTy = PointerType::getUnqual(IntptrTy); 416 Type *VoidTy = Type::getVoidTy(*C); 417 IRBuilder<> IRB(*C); 418 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty()); 419 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty()); 420 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty()); 421 Int1PtrTy = PointerType::getUnqual(IRB.getInt1Ty()); 422 Int64Ty = IRB.getInt64Ty(); 423 Int32Ty = IRB.getInt32Ty(); 424 Int16Ty = IRB.getInt16Ty(); 425 Int8Ty = IRB.getInt8Ty(); 426 Int1Ty = IRB.getInt1Ty(); 427 428 SanCovTracePCIndir = 429 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy); 430 // Make sure smaller parameters are zero-extended to i64 as required by the 431 // x86_64 ABI. 432 AttributeList SanCovTraceCmpZeroExtAL; 433 if (TargetTriple.getArch() == Triple::x86_64) { 434 SanCovTraceCmpZeroExtAL = 435 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt); 436 SanCovTraceCmpZeroExtAL = 437 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt); 438 } 439 440 SanCovTraceCmpFunction[0] = 441 M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy, 442 IRB.getInt8Ty(), IRB.getInt8Ty()); 443 SanCovTraceCmpFunction[1] = 444 M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy, 445 IRB.getInt16Ty(), IRB.getInt16Ty()); 446 SanCovTraceCmpFunction[2] = 447 M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy, 448 IRB.getInt32Ty(), IRB.getInt32Ty()); 449 SanCovTraceCmpFunction[3] = 450 M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty); 451 452 SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction( 453 SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty); 454 SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction( 455 SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty); 456 SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction( 457 SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty); 458 SanCovTraceConstCmpFunction[3] = 459 M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty); 460 461 { 462 AttributeList AL; 463 if (TargetTriple.getArch() == Triple::x86_64) 464 AL = AL.addParamAttribute(*C, 0, Attribute::ZExt); 465 SanCovTraceDivFunction[0] = 466 M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty()); 467 } 468 SanCovTraceDivFunction[1] = 469 M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty); 470 SanCovTraceGepFunction = 471 M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy); 472 SanCovTraceSwitchFunction = 473 M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy); 474 475 Constant *SanCovLowestStackConstant = 476 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy); 477 SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant); 478 if (!SanCovLowestStack) { 479 C->emitError(StringRef("'") + SanCovLowestStackName + 480 "' should not be declared by the user"); 481 return true; 482 } 483 SanCovLowestStack->setThreadLocalMode( 484 GlobalValue::ThreadLocalMode::InitialExecTLSModel); 485 if (Options.StackDepth && !SanCovLowestStack->isDeclaration()) 486 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy)); 487 488 // We insert an empty inline asm after cov callbacks to avoid callback merge. 489 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false), 490 StringRef(""), StringRef(""), 491 /*hasSideEffects=*/true); 492 493 SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy); 494 SanCovTracePCGuard = 495 M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy); 496 497 for (auto &F : M) 498 instrumentFunction(F, DTCallback, PDTCallback); 499 500 Function *Ctor = nullptr; 501 502 if (FunctionGuardArray) 503 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName, 504 SanCovTracePCGuardInitName, Int32PtrTy, 505 SanCovGuardsSectionName); 506 if (Function8bitCounterArray) 507 Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName, 508 SanCov8bitCountersInitName, Int8PtrTy, 509 SanCovCountersSectionName); 510 if (FunctionBoolArray) { 511 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName, 512 SanCovBoolFlagInitName, Int1PtrTy, 513 SanCovBoolFlagSectionName); 514 } 515 if (Ctor && Options.PCTable) { 516 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy); 517 FunctionCallee InitFunction = declareSanitizerInitFunction( 518 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy}); 519 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator()); 520 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second}); 521 } 522 // We don't reference these arrays directly in any of our runtime functions, 523 // so we need to prevent them from being dead stripped. 524 if (TargetTriple.isOSBinFormatMachO()) 525 appendToUsed(M, GlobalsToAppendToUsed); 526 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed); 527 return true; 528 } 529 530 // True if block has successors and it dominates all of them. 531 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) { 532 if (succ_begin(BB) == succ_end(BB)) 533 return false; 534 535 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) { 536 if (!DT->dominates(BB, SUCC)) 537 return false; 538 } 539 540 return true; 541 } 542 543 // True if block has predecessors and it postdominates all of them. 544 static bool isFullPostDominator(const BasicBlock *BB, 545 const PostDominatorTree *PDT) { 546 if (pred_begin(BB) == pred_end(BB)) 547 return false; 548 549 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) { 550 if (!PDT->dominates(BB, PRED)) 551 return false; 552 } 553 554 return true; 555 } 556 557 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, 558 const DominatorTree *DT, 559 const PostDominatorTree *PDT, 560 const SanitizerCoverageOptions &Options) { 561 // Don't insert coverage for blocks containing nothing but unreachable: we 562 // will never call __sanitizer_cov() for them, so counting them in 563 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage 564 // percentage. Also, unreachable instructions frequently have no debug 565 // locations. 566 if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime())) 567 return false; 568 569 // Don't insert coverage into blocks without a valid insertion point 570 // (catchswitch blocks). 571 if (BB->getFirstInsertionPt() == BB->end()) 572 return false; 573 574 if (Options.NoPrune || &F.getEntryBlock() == BB) 575 return true; 576 577 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function && 578 &F.getEntryBlock() != BB) 579 return false; 580 581 // Do not instrument full dominators, or full post-dominators with multiple 582 // predecessors. 583 return !isFullDominator(BB, DT) 584 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor()); 585 } 586 587 588 // Returns true iff From->To is a backedge. 589 // A twist here is that we treat From->To as a backedge if 590 // * To dominates From or 591 // * To->UniqueSuccessor dominates From 592 static bool IsBackEdge(BasicBlock *From, BasicBlock *To, 593 const DominatorTree *DT) { 594 if (DT->dominates(To, From)) 595 return true; 596 if (auto Next = To->getUniqueSuccessor()) 597 if (DT->dominates(Next, From)) 598 return true; 599 return false; 600 } 601 602 // Prunes uninteresting Cmp instrumentation: 603 // * CMP instructions that feed into loop backedge branch. 604 // 605 // Note that Cmp pruning is controlled by the same flag as the 606 // BB pruning. 607 static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT, 608 const SanitizerCoverageOptions &Options) { 609 if (!Options.NoPrune) 610 if (CMP->hasOneUse()) 611 if (auto BR = dyn_cast<BranchInst>(CMP->user_back())) 612 for (BasicBlock *B : BR->successors()) 613 if (IsBackEdge(BR->getParent(), B, DT)) 614 return false; 615 return true; 616 } 617 618 void ModuleSanitizerCoverage::instrumentFunction( 619 Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) { 620 if (F.empty()) 621 return; 622 if (F.getName().find(".module_ctor") != std::string::npos) 623 return; // Should not instrument sanitizer init functions. 624 if (F.getName().startswith("__sanitizer_")) 625 return; // Don't instrument __sanitizer_* callbacks. 626 // Don't touch available_externally functions, their actual body is elewhere. 627 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) 628 return; 629 // Don't instrument MSVC CRT configuration helpers. They may run before normal 630 // initialization. 631 if (F.getName() == "__local_stdio_printf_options" || 632 F.getName() == "__local_stdio_scanf_options") 633 return; 634 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator())) 635 return; 636 // Don't instrument functions using SEH for now. Splitting basic blocks like 637 // we do for coverage breaks WinEHPrepare. 638 // FIXME: Remove this when SEH no longer uses landingpad pattern matching. 639 if (F.hasPersonalityFn() && 640 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) 641 return; 642 if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName())) 643 return; 644 if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName())) 645 return; 646 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) 647 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests()); 648 SmallVector<Instruction *, 8> IndirCalls; 649 SmallVector<BasicBlock *, 16> BlocksToInstrument; 650 SmallVector<Instruction *, 8> CmpTraceTargets; 651 SmallVector<Instruction *, 8> SwitchTraceTargets; 652 SmallVector<BinaryOperator *, 8> DivTraceTargets; 653 SmallVector<GetElementPtrInst *, 8> GepTraceTargets; 654 655 const DominatorTree *DT = DTCallback(F); 656 const PostDominatorTree *PDT = PDTCallback(F); 657 bool IsLeafFunc = true; 658 659 for (auto &BB : F) { 660 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options)) 661 BlocksToInstrument.push_back(&BB); 662 for (auto &Inst : BB) { 663 if (Options.IndirectCalls) { 664 CallBase *CB = dyn_cast<CallBase>(&Inst); 665 if (CB && !CB->getCalledFunction()) 666 IndirCalls.push_back(&Inst); 667 } 668 if (Options.TraceCmp) { 669 if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst)) 670 if (IsInterestingCmp(CMP, DT, Options)) 671 CmpTraceTargets.push_back(&Inst); 672 if (isa<SwitchInst>(&Inst)) 673 SwitchTraceTargets.push_back(&Inst); 674 } 675 if (Options.TraceDiv) 676 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst)) 677 if (BO->getOpcode() == Instruction::SDiv || 678 BO->getOpcode() == Instruction::UDiv) 679 DivTraceTargets.push_back(BO); 680 if (Options.TraceGep) 681 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst)) 682 GepTraceTargets.push_back(GEP); 683 if (Options.StackDepth) 684 if (isa<InvokeInst>(Inst) || 685 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst))) 686 IsLeafFunc = false; 687 } 688 } 689 690 InjectCoverage(F, BlocksToInstrument, IsLeafFunc); 691 InjectCoverageForIndirectCalls(F, IndirCalls); 692 InjectTraceForCmp(F, CmpTraceTargets); 693 InjectTraceForSwitch(F, SwitchTraceTargets); 694 InjectTraceForDiv(F, DivTraceTargets); 695 InjectTraceForGep(F, GepTraceTargets); 696 } 697 698 GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection( 699 size_t NumElements, Function &F, Type *Ty, const char *Section) { 700 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements); 701 auto Array = new GlobalVariable( 702 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage, 703 Constant::getNullValue(ArrayTy), "__sancov_gen_"); 704 705 if (TargetTriple.supportsCOMDAT() && !F.isInterposable()) 706 if (auto Comdat = 707 GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId)) 708 Array->setComdat(Comdat); 709 Array->setSection(getSectionName(Section)); 710 Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedSize())); 711 GlobalsToAppendToUsed.push_back(Array); 712 GlobalsToAppendToCompilerUsed.push_back(Array); 713 MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F)); 714 Array->addMetadata(LLVMContext::MD_associated, *MD); 715 716 return Array; 717 } 718 719 GlobalVariable * 720 ModuleSanitizerCoverage::CreatePCArray(Function &F, 721 ArrayRef<BasicBlock *> AllBlocks) { 722 size_t N = AllBlocks.size(); 723 assert(N); 724 SmallVector<Constant *, 32> PCs; 725 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt()); 726 for (size_t i = 0; i < N; i++) { 727 if (&F.getEntryBlock() == AllBlocks[i]) { 728 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy)); 729 PCs.push_back((Constant *)IRB.CreateIntToPtr( 730 ConstantInt::get(IntptrTy, 1), IntptrPtrTy)); 731 } else { 732 PCs.push_back((Constant *)IRB.CreatePointerCast( 733 BlockAddress::get(AllBlocks[i]), IntptrPtrTy)); 734 PCs.push_back((Constant *)IRB.CreateIntToPtr( 735 ConstantInt::get(IntptrTy, 0), IntptrPtrTy)); 736 } 737 } 738 auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy, 739 SanCovPCsSectionName); 740 PCArray->setInitializer( 741 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs)); 742 PCArray->setConstant(true); 743 744 return PCArray; 745 } 746 747 void ModuleSanitizerCoverage::CreateFunctionLocalArrays( 748 Function &F, ArrayRef<BasicBlock *> AllBlocks) { 749 if (Options.TracePCGuard) 750 FunctionGuardArray = CreateFunctionLocalArrayInSection( 751 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName); 752 753 if (Options.Inline8bitCounters) 754 Function8bitCounterArray = CreateFunctionLocalArrayInSection( 755 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName); 756 if (Options.InlineBoolFlag) 757 FunctionBoolArray = CreateFunctionLocalArrayInSection( 758 AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName); 759 760 if (Options.PCTable) 761 FunctionPCsArray = CreatePCArray(F, AllBlocks); 762 } 763 764 bool ModuleSanitizerCoverage::InjectCoverage(Function &F, 765 ArrayRef<BasicBlock *> AllBlocks, 766 bool IsLeafFunc) { 767 if (AllBlocks.empty()) return false; 768 CreateFunctionLocalArrays(F, AllBlocks); 769 for (size_t i = 0, N = AllBlocks.size(); i < N; i++) 770 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc); 771 return true; 772 } 773 774 // On every indirect call we call a run-time function 775 // __sanitizer_cov_indir_call* with two parameters: 776 // - callee address, 777 // - global cache array that contains CacheSize pointers (zero-initialized). 778 // The cache is used to speed up recording the caller-callee pairs. 779 // The address of the caller is passed implicitly via caller PC. 780 // CacheSize is encoded in the name of the run-time function. 781 void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls( 782 Function &F, ArrayRef<Instruction *> IndirCalls) { 783 if (IndirCalls.empty()) 784 return; 785 assert(Options.TracePC || Options.TracePCGuard || 786 Options.Inline8bitCounters || Options.InlineBoolFlag); 787 for (auto I : IndirCalls) { 788 IRBuilder<> IRB(I); 789 CallBase &CB = cast<CallBase>(*I); 790 Value *Callee = CB.getCalledOperand(); 791 if (isa<InlineAsm>(Callee)) 792 continue; 793 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy)); 794 } 795 } 796 797 // For every switch statement we insert a call: 798 // __sanitizer_cov_trace_switch(CondValue, 799 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... }) 800 801 void ModuleSanitizerCoverage::InjectTraceForSwitch( 802 Function &, ArrayRef<Instruction *> SwitchTraceTargets) { 803 for (auto I : SwitchTraceTargets) { 804 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) { 805 IRBuilder<> IRB(I); 806 SmallVector<Constant *, 16> Initializers; 807 Value *Cond = SI->getCondition(); 808 if (Cond->getType()->getScalarSizeInBits() > 809 Int64Ty->getScalarSizeInBits()) 810 continue; 811 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases())); 812 Initializers.push_back( 813 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits())); 814 if (Cond->getType()->getScalarSizeInBits() < 815 Int64Ty->getScalarSizeInBits()) 816 Cond = IRB.CreateIntCast(Cond, Int64Ty, false); 817 for (auto It : SI->cases()) { 818 Constant *C = It.getCaseValue(); 819 if (C->getType()->getScalarSizeInBits() < 820 Int64Ty->getScalarSizeInBits()) 821 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty); 822 Initializers.push_back(C); 823 } 824 llvm::sort(Initializers.begin() + 2, Initializers.end(), 825 [](const Constant *A, const Constant *B) { 826 return cast<ConstantInt>(A)->getLimitedValue() < 827 cast<ConstantInt>(B)->getLimitedValue(); 828 }); 829 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size()); 830 GlobalVariable *GV = new GlobalVariable( 831 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage, 832 ConstantArray::get(ArrayOfInt64Ty, Initializers), 833 "__sancov_gen_cov_switch_values"); 834 IRB.CreateCall(SanCovTraceSwitchFunction, 835 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)}); 836 } 837 } 838 } 839 840 void ModuleSanitizerCoverage::InjectTraceForDiv( 841 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) { 842 for (auto BO : DivTraceTargets) { 843 IRBuilder<> IRB(BO); 844 Value *A1 = BO->getOperand(1); 845 if (isa<ConstantInt>(A1)) continue; 846 if (!A1->getType()->isIntegerTy()) 847 continue; 848 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType()); 849 int CallbackIdx = TypeSize == 32 ? 0 : 850 TypeSize == 64 ? 1 : -1; 851 if (CallbackIdx < 0) continue; 852 auto Ty = Type::getIntNTy(*C, TypeSize); 853 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx], 854 {IRB.CreateIntCast(A1, Ty, true)}); 855 } 856 } 857 858 void ModuleSanitizerCoverage::InjectTraceForGep( 859 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) { 860 for (auto GEP : GepTraceTargets) { 861 IRBuilder<> IRB(GEP); 862 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) 863 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy()) 864 IRB.CreateCall(SanCovTraceGepFunction, 865 {IRB.CreateIntCast(*I, IntptrTy, true)}); 866 } 867 } 868 869 void ModuleSanitizerCoverage::InjectTraceForCmp( 870 Function &, ArrayRef<Instruction *> CmpTraceTargets) { 871 for (auto I : CmpTraceTargets) { 872 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) { 873 IRBuilder<> IRB(ICMP); 874 Value *A0 = ICMP->getOperand(0); 875 Value *A1 = ICMP->getOperand(1); 876 if (!A0->getType()->isIntegerTy()) 877 continue; 878 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType()); 879 int CallbackIdx = TypeSize == 8 ? 0 : 880 TypeSize == 16 ? 1 : 881 TypeSize == 32 ? 2 : 882 TypeSize == 64 ? 3 : -1; 883 if (CallbackIdx < 0) continue; 884 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1); 885 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx]; 886 bool FirstIsConst = isa<ConstantInt>(A0); 887 bool SecondIsConst = isa<ConstantInt>(A1); 888 // If both are const, then we don't need such a comparison. 889 if (FirstIsConst && SecondIsConst) continue; 890 // If only one is const, then make it the first callback argument. 891 if (FirstIsConst || SecondIsConst) { 892 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx]; 893 if (SecondIsConst) 894 std::swap(A0, A1); 895 } 896 897 auto Ty = Type::getIntNTy(*C, TypeSize); 898 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true), 899 IRB.CreateIntCast(A1, Ty, true)}); 900 } 901 } 902 } 903 904 void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB, 905 size_t Idx, 906 bool IsLeafFunc) { 907 BasicBlock::iterator IP = BB.getFirstInsertionPt(); 908 bool IsEntryBB = &BB == &F.getEntryBlock(); 909 DebugLoc EntryLoc; 910 if (IsEntryBB) { 911 if (auto SP = F.getSubprogram()) 912 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP); 913 // Keep static allocas and llvm.localescape calls in the entry block. Even 914 // if we aren't splitting the block, it's nice for allocas to be before 915 // calls. 916 IP = PrepareToSplitEntryBlock(BB, IP); 917 } else { 918 EntryLoc = IP->getDebugLoc(); 919 } 920 921 IRBuilder<> IRB(&*IP); 922 IRB.SetCurrentDebugLocation(EntryLoc); 923 if (Options.TracePC) { 924 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC. 925 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge. 926 } 927 if (Options.TracePCGuard) { 928 auto GuardPtr = IRB.CreateIntToPtr( 929 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), 930 ConstantInt::get(IntptrTy, Idx * 4)), 931 Int32PtrTy); 932 IRB.CreateCall(SanCovTracePCGuard, GuardPtr); 933 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge. 934 } 935 if (Options.Inline8bitCounters) { 936 auto CounterPtr = IRB.CreateGEP( 937 Function8bitCounterArray->getValueType(), Function8bitCounterArray, 938 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)}); 939 auto Load = IRB.CreateLoad(Int8Ty, CounterPtr); 940 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1)); 941 auto Store = IRB.CreateStore(Inc, CounterPtr); 942 SetNoSanitizeMetadata(Load); 943 SetNoSanitizeMetadata(Store); 944 } 945 if (Options.InlineBoolFlag) { 946 auto FlagPtr = IRB.CreateGEP( 947 FunctionBoolArray->getValueType(), FunctionBoolArray, 948 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)}); 949 auto Load = IRB.CreateLoad(Int1Ty, FlagPtr); 950 auto ThenTerm = 951 SplitBlockAndInsertIfThen(IRB.CreateIsNull(Load), &*IP, false); 952 IRBuilder<> ThenIRB(ThenTerm); 953 auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr); 954 SetNoSanitizeMetadata(Load); 955 SetNoSanitizeMetadata(Store); 956 } 957 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) { 958 // Check stack depth. If it's the deepest so far, record it. 959 Module *M = F.getParent(); 960 Function *GetFrameAddr = Intrinsic::getDeclaration( 961 M, Intrinsic::frameaddress, 962 IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace())); 963 auto FrameAddrPtr = 964 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)}); 965 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy); 966 auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack); 967 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack); 968 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false); 969 IRBuilder<> ThenIRB(ThenTerm); 970 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack); 971 SetNoSanitizeMetadata(LowestStack); 972 SetNoSanitizeMetadata(Store); 973 } 974 } 975 976 std::string 977 ModuleSanitizerCoverage::getSectionName(const std::string &Section) const { 978 if (TargetTriple.isOSBinFormatCOFF()) { 979 if (Section == SanCovCountersSectionName) 980 return ".SCOV$CM"; 981 if (Section == SanCovBoolFlagSectionName) 982 return ".SCOV$BM"; 983 if (Section == SanCovPCsSectionName) 984 return ".SCOVP$M"; 985 return ".SCOV$GM"; // For SanCovGuardsSectionName. 986 } 987 if (TargetTriple.isOSBinFormatMachO()) 988 return "__DATA,__" + Section; 989 return "__" + Section; 990 } 991 992 std::string 993 ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const { 994 if (TargetTriple.isOSBinFormatMachO()) 995 return "\1section$start$__DATA$__" + Section; 996 return "__start___" + Section; 997 } 998 999 std::string 1000 ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const { 1001 if (TargetTriple.isOSBinFormatMachO()) 1002 return "\1section$end$__DATA$__" + Section; 1003 return "__stop___" + Section; 1004 } 1005 1006 char ModuleSanitizerCoverageLegacyPass::ID = 0; 1007 INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov", 1008 "Pass for instrumenting coverage on functions", false, 1009 false) 1010 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1011 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 1012 INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov", 1013 "Pass for instrumenting coverage on functions", false, 1014 false) 1015 ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass( 1016 const SanitizerCoverageOptions &Options, 1017 const std::vector<std::string> &AllowlistFiles, 1018 const std::vector<std::string> &BlocklistFiles) { 1019 return new ModuleSanitizerCoverageLegacyPass(Options, AllowlistFiles, 1020 BlocklistFiles); 1021 } 1022