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 if required by the 429 // target ABI. 430 AttributeList SanCovTraceCmpZeroExtAL; 431 SanCovTraceCmpZeroExtAL = 432 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt); 433 SanCovTraceCmpZeroExtAL = 434 SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt); 435 436 SanCovTraceCmpFunction[0] = 437 M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy, 438 IRB.getInt8Ty(), IRB.getInt8Ty()); 439 SanCovTraceCmpFunction[1] = 440 M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy, 441 IRB.getInt16Ty(), IRB.getInt16Ty()); 442 SanCovTraceCmpFunction[2] = 443 M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy, 444 IRB.getInt32Ty(), IRB.getInt32Ty()); 445 SanCovTraceCmpFunction[3] = 446 M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty); 447 448 SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction( 449 SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty); 450 SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction( 451 SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty); 452 SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction( 453 SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty); 454 SanCovTraceConstCmpFunction[3] = 455 M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty); 456 457 { 458 AttributeList AL; 459 AL = AL.addParamAttribute(*C, 0, Attribute::ZExt); 460 SanCovTraceDivFunction[0] = 461 M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty()); 462 } 463 SanCovTraceDivFunction[1] = 464 M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty); 465 SanCovTraceGepFunction = 466 M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy); 467 SanCovTraceSwitchFunction = 468 M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy); 469 470 Constant *SanCovLowestStackConstant = 471 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy); 472 SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant); 473 if (!SanCovLowestStack) { 474 C->emitError(StringRef("'") + SanCovLowestStackName + 475 "' should not be declared by the user"); 476 return true; 477 } 478 SanCovLowestStack->setThreadLocalMode( 479 GlobalValue::ThreadLocalMode::InitialExecTLSModel); 480 if (Options.StackDepth && !SanCovLowestStack->isDeclaration()) 481 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy)); 482 483 SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy); 484 SanCovTracePCGuard = 485 M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy); 486 487 for (auto &F : M) 488 instrumentFunction(F, DTCallback, PDTCallback); 489 490 Function *Ctor = nullptr; 491 492 if (FunctionGuardArray) 493 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName, 494 SanCovTracePCGuardInitName, Int32PtrTy, 495 SanCovGuardsSectionName); 496 if (Function8bitCounterArray) 497 Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName, 498 SanCov8bitCountersInitName, Int8PtrTy, 499 SanCovCountersSectionName); 500 if (FunctionBoolArray) { 501 Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName, 502 SanCovBoolFlagInitName, Int1PtrTy, 503 SanCovBoolFlagSectionName); 504 } 505 if (Ctor && Options.PCTable) { 506 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy); 507 FunctionCallee InitFunction = declareSanitizerInitFunction( 508 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy}); 509 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator()); 510 IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second}); 511 } 512 // We don't reference these arrays directly in any of our runtime functions, 513 // so we need to prevent them from being dead stripped. 514 if (TargetTriple.isOSBinFormatMachO()) 515 appendToUsed(M, GlobalsToAppendToUsed); 516 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed); 517 return true; 518 } 519 520 // True if block has successors and it dominates all of them. 521 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) { 522 if (succ_empty(BB)) 523 return false; 524 525 return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) { 526 return DT->dominates(BB, SUCC); 527 }); 528 } 529 530 // True if block has predecessors and it postdominates all of them. 531 static bool isFullPostDominator(const BasicBlock *BB, 532 const PostDominatorTree *PDT) { 533 if (pred_empty(BB)) 534 return false; 535 536 return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) { 537 return PDT->dominates(BB, PRED); 538 }); 539 } 540 541 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, 542 const DominatorTree *DT, 543 const PostDominatorTree *PDT, 544 const SanitizerCoverageOptions &Options) { 545 // Don't insert coverage for blocks containing nothing but unreachable: we 546 // will never call __sanitizer_cov() for them, so counting them in 547 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage 548 // percentage. Also, unreachable instructions frequently have no debug 549 // locations. 550 if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime())) 551 return false; 552 553 // Don't insert coverage into blocks without a valid insertion point 554 // (catchswitch blocks). 555 if (BB->getFirstInsertionPt() == BB->end()) 556 return false; 557 558 if (Options.NoPrune || &F.getEntryBlock() == BB) 559 return true; 560 561 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function && 562 &F.getEntryBlock() != BB) 563 return false; 564 565 // Do not instrument full dominators, or full post-dominators with multiple 566 // predecessors. 567 return !isFullDominator(BB, DT) 568 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor()); 569 } 570 571 572 // Returns true iff From->To is a backedge. 573 // A twist here is that we treat From->To as a backedge if 574 // * To dominates From or 575 // * To->UniqueSuccessor dominates From 576 static bool IsBackEdge(BasicBlock *From, BasicBlock *To, 577 const DominatorTree *DT) { 578 if (DT->dominates(To, From)) 579 return true; 580 if (auto Next = To->getUniqueSuccessor()) 581 if (DT->dominates(Next, From)) 582 return true; 583 return false; 584 } 585 586 // Prunes uninteresting Cmp instrumentation: 587 // * CMP instructions that feed into loop backedge branch. 588 // 589 // Note that Cmp pruning is controlled by the same flag as the 590 // BB pruning. 591 static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT, 592 const SanitizerCoverageOptions &Options) { 593 if (!Options.NoPrune) 594 if (CMP->hasOneUse()) 595 if (auto BR = dyn_cast<BranchInst>(CMP->user_back())) 596 for (BasicBlock *B : BR->successors()) 597 if (IsBackEdge(BR->getParent(), B, DT)) 598 return false; 599 return true; 600 } 601 602 void ModuleSanitizerCoverage::instrumentFunction( 603 Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) { 604 if (F.empty()) 605 return; 606 if (F.getName().find(".module_ctor") != std::string::npos) 607 return; // Should not instrument sanitizer init functions. 608 if (F.getName().startswith("__sanitizer_")) 609 return; // Don't instrument __sanitizer_* callbacks. 610 // Don't touch available_externally functions, their actual body is elewhere. 611 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) 612 return; 613 // Don't instrument MSVC CRT configuration helpers. They may run before normal 614 // initialization. 615 if (F.getName() == "__local_stdio_printf_options" || 616 F.getName() == "__local_stdio_scanf_options") 617 return; 618 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator())) 619 return; 620 // Don't instrument functions using SEH for now. Splitting basic blocks like 621 // we do for coverage breaks WinEHPrepare. 622 // FIXME: Remove this when SEH no longer uses landingpad pattern matching. 623 if (F.hasPersonalityFn() && 624 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) 625 return; 626 if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName())) 627 return; 628 if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName())) 629 return; 630 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) 631 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests()); 632 SmallVector<Instruction *, 8> IndirCalls; 633 SmallVector<BasicBlock *, 16> BlocksToInstrument; 634 SmallVector<Instruction *, 8> CmpTraceTargets; 635 SmallVector<Instruction *, 8> SwitchTraceTargets; 636 SmallVector<BinaryOperator *, 8> DivTraceTargets; 637 SmallVector<GetElementPtrInst *, 8> GepTraceTargets; 638 639 const DominatorTree *DT = DTCallback(F); 640 const PostDominatorTree *PDT = PDTCallback(F); 641 bool IsLeafFunc = true; 642 643 for (auto &BB : F) { 644 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options)) 645 BlocksToInstrument.push_back(&BB); 646 for (auto &Inst : BB) { 647 if (Options.IndirectCalls) { 648 CallBase *CB = dyn_cast<CallBase>(&Inst); 649 if (CB && !CB->getCalledFunction()) 650 IndirCalls.push_back(&Inst); 651 } 652 if (Options.TraceCmp) { 653 if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst)) 654 if (IsInterestingCmp(CMP, DT, Options)) 655 CmpTraceTargets.push_back(&Inst); 656 if (isa<SwitchInst>(&Inst)) 657 SwitchTraceTargets.push_back(&Inst); 658 } 659 if (Options.TraceDiv) 660 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst)) 661 if (BO->getOpcode() == Instruction::SDiv || 662 BO->getOpcode() == Instruction::UDiv) 663 DivTraceTargets.push_back(BO); 664 if (Options.TraceGep) 665 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst)) 666 GepTraceTargets.push_back(GEP); 667 if (Options.StackDepth) 668 if (isa<InvokeInst>(Inst) || 669 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst))) 670 IsLeafFunc = false; 671 } 672 } 673 674 InjectCoverage(F, BlocksToInstrument, IsLeafFunc); 675 InjectCoverageForIndirectCalls(F, IndirCalls); 676 InjectTraceForCmp(F, CmpTraceTargets); 677 InjectTraceForSwitch(F, SwitchTraceTargets); 678 InjectTraceForDiv(F, DivTraceTargets); 679 InjectTraceForGep(F, GepTraceTargets); 680 } 681 682 GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection( 683 size_t NumElements, Function &F, Type *Ty, const char *Section) { 684 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements); 685 auto Array = new GlobalVariable( 686 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage, 687 Constant::getNullValue(ArrayTy), "__sancov_gen_"); 688 689 if (TargetTriple.supportsCOMDAT() && !F.isInterposable()) 690 if (auto Comdat = 691 GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId)) 692 Array->setComdat(Comdat); 693 Array->setSection(getSectionName(Section)); 694 Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedSize())); 695 GlobalsToAppendToUsed.push_back(Array); 696 GlobalsToAppendToCompilerUsed.push_back(Array); 697 MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F)); 698 Array->addMetadata(LLVMContext::MD_associated, *MD); 699 700 return Array; 701 } 702 703 GlobalVariable * 704 ModuleSanitizerCoverage::CreatePCArray(Function &F, 705 ArrayRef<BasicBlock *> AllBlocks) { 706 size_t N = AllBlocks.size(); 707 assert(N); 708 SmallVector<Constant *, 32> PCs; 709 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt()); 710 for (size_t i = 0; i < N; i++) { 711 if (&F.getEntryBlock() == AllBlocks[i]) { 712 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy)); 713 PCs.push_back((Constant *)IRB.CreateIntToPtr( 714 ConstantInt::get(IntptrTy, 1), IntptrPtrTy)); 715 } else { 716 PCs.push_back((Constant *)IRB.CreatePointerCast( 717 BlockAddress::get(AllBlocks[i]), IntptrPtrTy)); 718 PCs.push_back((Constant *)IRB.CreateIntToPtr( 719 ConstantInt::get(IntptrTy, 0), IntptrPtrTy)); 720 } 721 } 722 auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy, 723 SanCovPCsSectionName); 724 PCArray->setInitializer( 725 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs)); 726 PCArray->setConstant(true); 727 728 return PCArray; 729 } 730 731 void ModuleSanitizerCoverage::CreateFunctionLocalArrays( 732 Function &F, ArrayRef<BasicBlock *> AllBlocks) { 733 if (Options.TracePCGuard) 734 FunctionGuardArray = CreateFunctionLocalArrayInSection( 735 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName); 736 737 if (Options.Inline8bitCounters) 738 Function8bitCounterArray = CreateFunctionLocalArrayInSection( 739 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName); 740 if (Options.InlineBoolFlag) 741 FunctionBoolArray = CreateFunctionLocalArrayInSection( 742 AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName); 743 744 if (Options.PCTable) 745 FunctionPCsArray = CreatePCArray(F, AllBlocks); 746 } 747 748 bool ModuleSanitizerCoverage::InjectCoverage(Function &F, 749 ArrayRef<BasicBlock *> AllBlocks, 750 bool IsLeafFunc) { 751 if (AllBlocks.empty()) return false; 752 CreateFunctionLocalArrays(F, AllBlocks); 753 for (size_t i = 0, N = AllBlocks.size(); i < N; i++) 754 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc); 755 return true; 756 } 757 758 // On every indirect call we call a run-time function 759 // __sanitizer_cov_indir_call* with two parameters: 760 // - callee address, 761 // - global cache array that contains CacheSize pointers (zero-initialized). 762 // The cache is used to speed up recording the caller-callee pairs. 763 // The address of the caller is passed implicitly via caller PC. 764 // CacheSize is encoded in the name of the run-time function. 765 void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls( 766 Function &F, ArrayRef<Instruction *> IndirCalls) { 767 if (IndirCalls.empty()) 768 return; 769 assert(Options.TracePC || Options.TracePCGuard || 770 Options.Inline8bitCounters || Options.InlineBoolFlag); 771 for (auto I : IndirCalls) { 772 IRBuilder<> IRB(I); 773 CallBase &CB = cast<CallBase>(*I); 774 Value *Callee = CB.getCalledOperand(); 775 if (isa<InlineAsm>(Callee)) 776 continue; 777 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy)); 778 } 779 } 780 781 // For every switch statement we insert a call: 782 // __sanitizer_cov_trace_switch(CondValue, 783 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... }) 784 785 void ModuleSanitizerCoverage::InjectTraceForSwitch( 786 Function &, ArrayRef<Instruction *> SwitchTraceTargets) { 787 for (auto I : SwitchTraceTargets) { 788 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) { 789 IRBuilder<> IRB(I); 790 SmallVector<Constant *, 16> Initializers; 791 Value *Cond = SI->getCondition(); 792 if (Cond->getType()->getScalarSizeInBits() > 793 Int64Ty->getScalarSizeInBits()) 794 continue; 795 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases())); 796 Initializers.push_back( 797 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits())); 798 if (Cond->getType()->getScalarSizeInBits() < 799 Int64Ty->getScalarSizeInBits()) 800 Cond = IRB.CreateIntCast(Cond, Int64Ty, false); 801 for (auto It : SI->cases()) { 802 Constant *C = It.getCaseValue(); 803 if (C->getType()->getScalarSizeInBits() < 804 Int64Ty->getScalarSizeInBits()) 805 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty); 806 Initializers.push_back(C); 807 } 808 llvm::sort(Initializers.begin() + 2, Initializers.end(), 809 [](const Constant *A, const Constant *B) { 810 return cast<ConstantInt>(A)->getLimitedValue() < 811 cast<ConstantInt>(B)->getLimitedValue(); 812 }); 813 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size()); 814 GlobalVariable *GV = new GlobalVariable( 815 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage, 816 ConstantArray::get(ArrayOfInt64Ty, Initializers), 817 "__sancov_gen_cov_switch_values"); 818 IRB.CreateCall(SanCovTraceSwitchFunction, 819 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)}); 820 } 821 } 822 } 823 824 void ModuleSanitizerCoverage::InjectTraceForDiv( 825 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) { 826 for (auto BO : DivTraceTargets) { 827 IRBuilder<> IRB(BO); 828 Value *A1 = BO->getOperand(1); 829 if (isa<ConstantInt>(A1)) continue; 830 if (!A1->getType()->isIntegerTy()) 831 continue; 832 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType()); 833 int CallbackIdx = TypeSize == 32 ? 0 : 834 TypeSize == 64 ? 1 : -1; 835 if (CallbackIdx < 0) continue; 836 auto Ty = Type::getIntNTy(*C, TypeSize); 837 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx], 838 {IRB.CreateIntCast(A1, Ty, true)}); 839 } 840 } 841 842 void ModuleSanitizerCoverage::InjectTraceForGep( 843 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) { 844 for (auto GEP : GepTraceTargets) { 845 IRBuilder<> IRB(GEP); 846 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) 847 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy()) 848 IRB.CreateCall(SanCovTraceGepFunction, 849 {IRB.CreateIntCast(*I, IntptrTy, true)}); 850 } 851 } 852 853 void ModuleSanitizerCoverage::InjectTraceForCmp( 854 Function &, ArrayRef<Instruction *> CmpTraceTargets) { 855 for (auto I : CmpTraceTargets) { 856 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) { 857 IRBuilder<> IRB(ICMP); 858 Value *A0 = ICMP->getOperand(0); 859 Value *A1 = ICMP->getOperand(1); 860 if (!A0->getType()->isIntegerTy()) 861 continue; 862 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType()); 863 int CallbackIdx = TypeSize == 8 ? 0 : 864 TypeSize == 16 ? 1 : 865 TypeSize == 32 ? 2 : 866 TypeSize == 64 ? 3 : -1; 867 if (CallbackIdx < 0) continue; 868 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1); 869 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx]; 870 bool FirstIsConst = isa<ConstantInt>(A0); 871 bool SecondIsConst = isa<ConstantInt>(A1); 872 // If both are const, then we don't need such a comparison. 873 if (FirstIsConst && SecondIsConst) continue; 874 // If only one is const, then make it the first callback argument. 875 if (FirstIsConst || SecondIsConst) { 876 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx]; 877 if (SecondIsConst) 878 std::swap(A0, A1); 879 } 880 881 auto Ty = Type::getIntNTy(*C, TypeSize); 882 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true), 883 IRB.CreateIntCast(A1, Ty, true)}); 884 } 885 } 886 } 887 888 void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB, 889 size_t Idx, 890 bool IsLeafFunc) { 891 BasicBlock::iterator IP = BB.getFirstInsertionPt(); 892 bool IsEntryBB = &BB == &F.getEntryBlock(); 893 DebugLoc EntryLoc; 894 if (IsEntryBB) { 895 if (auto SP = F.getSubprogram()) 896 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP); 897 // Keep static allocas and llvm.localescape calls in the entry block. Even 898 // if we aren't splitting the block, it's nice for allocas to be before 899 // calls. 900 IP = PrepareToSplitEntryBlock(BB, IP); 901 } else { 902 EntryLoc = IP->getDebugLoc(); 903 } 904 905 IRBuilder<> IRB(&*IP); 906 IRB.SetCurrentDebugLocation(EntryLoc); 907 if (Options.TracePC) { 908 IRB.CreateCall(SanCovTracePC) 909 ->setCannotMerge(); // gets the PC using GET_CALLER_PC. 910 } 911 if (Options.TracePCGuard) { 912 auto GuardPtr = IRB.CreateIntToPtr( 913 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), 914 ConstantInt::get(IntptrTy, Idx * 4)), 915 Int32PtrTy); 916 IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge(); 917 } 918 if (Options.Inline8bitCounters) { 919 auto CounterPtr = IRB.CreateGEP( 920 Function8bitCounterArray->getValueType(), Function8bitCounterArray, 921 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)}); 922 auto Load = IRB.CreateLoad(Int8Ty, CounterPtr); 923 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1)); 924 auto Store = IRB.CreateStore(Inc, CounterPtr); 925 SetNoSanitizeMetadata(Load); 926 SetNoSanitizeMetadata(Store); 927 } 928 if (Options.InlineBoolFlag) { 929 auto FlagPtr = IRB.CreateGEP( 930 FunctionBoolArray->getValueType(), FunctionBoolArray, 931 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)}); 932 auto Load = IRB.CreateLoad(Int1Ty, FlagPtr); 933 auto ThenTerm = 934 SplitBlockAndInsertIfThen(IRB.CreateIsNull(Load), &*IP, false); 935 IRBuilder<> ThenIRB(ThenTerm); 936 auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr); 937 SetNoSanitizeMetadata(Load); 938 SetNoSanitizeMetadata(Store); 939 } 940 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) { 941 // Check stack depth. If it's the deepest so far, record it. 942 Module *M = F.getParent(); 943 Function *GetFrameAddr = Intrinsic::getDeclaration( 944 M, Intrinsic::frameaddress, 945 IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace())); 946 auto FrameAddrPtr = 947 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)}); 948 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy); 949 auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack); 950 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack); 951 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false); 952 IRBuilder<> ThenIRB(ThenTerm); 953 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack); 954 SetNoSanitizeMetadata(LowestStack); 955 SetNoSanitizeMetadata(Store); 956 } 957 } 958 959 std::string 960 ModuleSanitizerCoverage::getSectionName(const std::string &Section) const { 961 if (TargetTriple.isOSBinFormatCOFF()) { 962 if (Section == SanCovCountersSectionName) 963 return ".SCOV$CM"; 964 if (Section == SanCovBoolFlagSectionName) 965 return ".SCOV$BM"; 966 if (Section == SanCovPCsSectionName) 967 return ".SCOVP$M"; 968 return ".SCOV$GM"; // For SanCovGuardsSectionName. 969 } 970 if (TargetTriple.isOSBinFormatMachO()) 971 return "__DATA,__" + Section; 972 return "__" + Section; 973 } 974 975 std::string 976 ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const { 977 if (TargetTriple.isOSBinFormatMachO()) 978 return "\1section$start$__DATA$__" + Section; 979 return "__start___" + Section; 980 } 981 982 std::string 983 ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const { 984 if (TargetTriple.isOSBinFormatMachO()) 985 return "\1section$end$__DATA$__" + Section; 986 return "__stop___" + Section; 987 } 988 989 char ModuleSanitizerCoverageLegacyPass::ID = 0; 990 INITIALIZE_PASS_BEGIN(ModuleSanitizerCoverageLegacyPass, "sancov", 991 "Pass for instrumenting coverage on functions", false, 992 false) 993 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 994 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 995 INITIALIZE_PASS_END(ModuleSanitizerCoverageLegacyPass, "sancov", 996 "Pass for instrumenting coverage on functions", false, 997 false) 998 ModulePass *llvm::createModuleSanitizerCoverageLegacyPassPass( 999 const SanitizerCoverageOptions &Options, 1000 const std::vector<std::string> &AllowlistFiles, 1001 const std::vector<std::string> &BlocklistFiles) { 1002 return new ModuleSanitizerCoverageLegacyPass(Options, AllowlistFiles, 1003 BlocklistFiles); 1004 } 1005