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