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