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