1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Coverage instrumentation done on LLVM IR level, works with Sanitizers. 11 // 12 //===----------------------------------------------------------------------===// 13 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/CallSite.h" 20 #include "llvm/IR/Constant.h" 21 #include "llvm/IR/DataLayout.h" 22 #include "llvm/IR/DebugInfo.h" 23 #include "llvm/IR/Dominators.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/GlobalVariable.h" 26 #include "llvm/IR/IRBuilder.h" 27 #include "llvm/IR/InlineAsm.h" 28 #include "llvm/IR/IntrinsicInst.h" 29 #include "llvm/IR/Intrinsics.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/MDBuilder.h" 32 #include "llvm/IR/Mangler.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/Type.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include "llvm/Transforms/Instrumentation.h" 39 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 40 #include "llvm/Transforms/Utils/ModuleUtils.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "sancov" 45 46 static const char *const SanCovTracePCIndirName = 47 "__sanitizer_cov_trace_pc_indir"; 48 static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc"; 49 static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1"; 50 static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2"; 51 static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4"; 52 static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8"; 53 static const char *const SanCovTraceConstCmp1 = 54 "__sanitizer_cov_trace_const_cmp1"; 55 static const char *const SanCovTraceConstCmp2 = 56 "__sanitizer_cov_trace_const_cmp2"; 57 static const char *const SanCovTraceConstCmp4 = 58 "__sanitizer_cov_trace_const_cmp4"; 59 static const char *const SanCovTraceConstCmp8 = 60 "__sanitizer_cov_trace_const_cmp8"; 61 static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4"; 62 static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8"; 63 static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep"; 64 static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch"; 65 static const char *const SanCovModuleCtorName = "sancov.module_ctor"; 66 static const uint64_t SanCtorAndDtorPriority = 2; 67 68 static const char *const SanCovTracePCGuardName = 69 "__sanitizer_cov_trace_pc_guard"; 70 static const char *const SanCovTracePCGuardInitName = 71 "__sanitizer_cov_trace_pc_guard_init"; 72 static const char *const SanCov8bitCountersInitName = 73 "__sanitizer_cov_8bit_counters_init"; 74 static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init"; 75 76 static const char *const SanCovGuardsSectionName = "sancov_guards"; 77 static const char *const SanCovCountersSectionName = "sancov_cntrs"; 78 static const char *const SanCovPCsSectionName = "sancov_pcs"; 79 80 static const char *const 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 and inline-8bit-counters. 101 static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table", 102 cl::desc("create a static PC table"), 103 cl::Hidden, cl::init(false)); 104 105 static cl::opt<bool> 106 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters", 107 cl::desc("increments 8-bit counter for every edge"), 108 cl::Hidden, cl::init(false)); 109 110 static cl::opt<bool> 111 ClCMPTracing("sanitizer-coverage-trace-compares", 112 cl::desc("Tracing of CMP and similar instructions"), 113 cl::Hidden, cl::init(false)); 114 115 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs", 116 cl::desc("Tracing of DIV instructions"), 117 cl::Hidden, cl::init(false)); 118 119 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps", 120 cl::desc("Tracing of GEP instructions"), 121 cl::Hidden, cl::init(false)); 122 123 static cl::opt<bool> 124 ClPruneBlocks("sanitizer-coverage-prune-blocks", 125 cl::desc("Reduce the number of instrumented blocks"), 126 cl::Hidden, cl::init(true)); 127 128 static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth", 129 cl::desc("max stack depth tracing"), 130 cl::Hidden, cl::init(false)); 131 132 namespace { 133 134 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) { 135 SanitizerCoverageOptions Res; 136 switch (LegacyCoverageLevel) { 137 case 0: 138 Res.CoverageType = SanitizerCoverageOptions::SCK_None; 139 break; 140 case 1: 141 Res.CoverageType = SanitizerCoverageOptions::SCK_Function; 142 break; 143 case 2: 144 Res.CoverageType = SanitizerCoverageOptions::SCK_BB; 145 break; 146 case 3: 147 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge; 148 break; 149 case 4: 150 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge; 151 Res.IndirectCalls = true; 152 break; 153 } 154 return Res; 155 } 156 157 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) { 158 // Sets CoverageType and IndirectCalls. 159 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel); 160 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType); 161 Options.IndirectCalls |= CLOpts.IndirectCalls; 162 Options.TraceCmp |= ClCMPTracing; 163 Options.TraceDiv |= ClDIVTracing; 164 Options.TraceGep |= ClGEPTracing; 165 Options.TracePC |= ClTracePC; 166 Options.TracePCGuard |= ClTracePCGuard; 167 Options.Inline8bitCounters |= ClInline8bitCounters; 168 Options.PCTable |= ClCreatePCTable; 169 Options.NoPrune |= !ClPruneBlocks; 170 Options.StackDepth |= ClStackDepth; 171 if (!Options.TracePCGuard && !Options.TracePC && 172 !Options.Inline8bitCounters && !Options.StackDepth) 173 Options.TracePCGuard = true; // TracePCGuard is default. 174 return Options; 175 } 176 177 class SanitizerCoverageModule : public ModulePass { 178 public: 179 SanitizerCoverageModule( 180 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions()) 181 : ModulePass(ID), Options(OverrideFromCL(Options)) { 182 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry()); 183 } 184 bool runOnModule(Module &M) override; 185 bool runOnFunction(Function &F); 186 static char ID; // Pass identification, replacement for typeid 187 StringRef getPassName() const override { return "SanitizerCoverageModule"; } 188 189 void getAnalysisUsage(AnalysisUsage &AU) const override { 190 AU.addRequired<DominatorTreeWrapperPass>(); 191 AU.addRequired<PostDominatorTreeWrapperPass>(); 192 } 193 194 private: 195 void InjectCoverageForIndirectCalls(Function &F, 196 ArrayRef<Instruction *> IndirCalls); 197 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets); 198 void InjectTraceForDiv(Function &F, 199 ArrayRef<BinaryOperator *> DivTraceTargets); 200 void InjectTraceForGep(Function &F, 201 ArrayRef<GetElementPtrInst *> GepTraceTargets); 202 void InjectTraceForSwitch(Function &F, 203 ArrayRef<Instruction *> SwitchTraceTargets); 204 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks, 205 bool IsLeafFunc = true); 206 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements, 207 Function &F, Type *Ty, 208 const char *Section); 209 GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks); 210 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks); 211 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx, 212 bool IsLeafFunc = true); 213 Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName, 214 Type *Ty, const char *Section); 215 std::pair<GlobalVariable *, GlobalVariable *> 216 CreateSecStartEnd(Module &M, const char *Section, Type *Ty); 217 218 void SetNoSanitizeMetadata(Instruction *I) { 219 I->setMetadata(I->getModule()->getMDKindID("nosanitize"), 220 MDNode::get(*C, None)); 221 } 222 223 std::string getSectionName(const std::string &Section) const; 224 std::string getSectionStart(const std::string &Section) const; 225 std::string getSectionEnd(const std::string &Section) const; 226 Function *SanCovTracePCIndir; 227 Function *SanCovTracePC, *SanCovTracePCGuard; 228 Function *SanCovTraceCmpFunction[4]; 229 Function *SanCovTraceConstCmpFunction[4]; 230 Function *SanCovTraceDivFunction[2]; 231 Function *SanCovTraceGepFunction; 232 Function *SanCovTraceSwitchFunction; 233 GlobalVariable *SanCovLowestStack; 234 InlineAsm *EmptyAsm; 235 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy, 236 *Int16Ty, *Int8Ty, *Int8PtrTy; 237 Module *CurModule; 238 std::string CurModuleUniqueId; 239 Triple TargetTriple; 240 LLVMContext *C; 241 const DataLayout *DL; 242 243 GlobalVariable *FunctionGuardArray; // for trace-pc-guard. 244 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters. 245 GlobalVariable *FunctionPCsArray; // for pc-table. 246 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed; 247 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed; 248 249 SanitizerCoverageOptions Options; 250 }; 251 252 } // namespace 253 254 std::pair<GlobalVariable *, GlobalVariable *> 255 SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section, 256 Type *Ty) { 257 GlobalVariable *SecStart = 258 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr, 259 getSectionStart(Section)); 260 SecStart->setVisibility(GlobalValue::HiddenVisibility); 261 GlobalVariable *SecEnd = 262 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, 263 nullptr, getSectionEnd(Section)); 264 SecEnd->setVisibility(GlobalValue::HiddenVisibility); 265 266 return std::make_pair(SecStart, SecEnd); 267 } 268 269 270 Function *SanitizerCoverageModule::CreateInitCallsForSections( 271 Module &M, const char *InitFunctionName, Type *Ty, 272 const char *Section) { 273 IRBuilder<> IRB(M.getContext()); 274 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty); 275 auto SecStart = SecStartEnd.first; 276 auto SecEnd = SecStartEnd.second; 277 Function *CtorFunc; 278 Value *SecStartPtr = nullptr; 279 // Account for the fact that on windows-msvc __start_* symbols actually 280 // point to a uint64_t before the start of the array. 281 if (TargetTriple.getObjectFormat() == Triple::COFF) { 282 auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy); 283 auto GEP = IRB.CreateGEP(SecStartI8Ptr, 284 ConstantInt::get(IntptrTy, sizeof(uint64_t))); 285 SecStartPtr = IRB.CreatePointerCast(GEP, Ty); 286 } else { 287 SecStartPtr = IRB.CreatePointerCast(SecStart, Ty); 288 } 289 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions( 290 M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty}, 291 {SecStartPtr, IRB.CreatePointerCast(SecEnd, Ty)}); 292 293 if (TargetTriple.supportsCOMDAT()) { 294 // Use comdat to dedup CtorFunc. 295 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName)); 296 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc); 297 } else { 298 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority); 299 } 300 301 if (TargetTriple.getObjectFormat() == Triple::COFF) { 302 // In COFF files, if the contructors are set as COMDAT (they are because 303 // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced 304 // functions and data) is used, the constructors get stripped. To prevent 305 // this, give the constructors weak ODR linkage and tell the linker to 306 // always include the sancov constructor. This way the linker can 307 // deduplicate the constructors but always leave one copy. 308 CtorFunc->setLinkage(GlobalValue::WeakODRLinkage); 309 SmallString<20> PartialIncDirective("/include:"); 310 // Get constructor's mangled name in order to support i386. 311 SmallString<40> MangledName; 312 Mangler().getNameWithPrefix(MangledName, CtorFunc, true); 313 Twine IncDirective = PartialIncDirective + MangledName; 314 Metadata *Args[1] = {MDString::get(*C, IncDirective.str())}; 315 MDNode *MetadataNode = MDNode::get(*C, Args); 316 NamedMDNode *NamedMetadata = 317 M.getOrInsertNamedMetadata("llvm.linker.options"); 318 NamedMetadata->addOperand(MetadataNode); 319 } 320 return CtorFunc; 321 } 322 323 bool SanitizerCoverageModule::runOnModule(Module &M) { 324 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None) 325 return false; 326 C = &(M.getContext()); 327 DL = &M.getDataLayout(); 328 CurModule = &M; 329 CurModuleUniqueId = getUniqueModuleId(CurModule); 330 TargetTriple = Triple(M.getTargetTriple()); 331 FunctionGuardArray = nullptr; 332 Function8bitCounterArray = nullptr; 333 FunctionPCsArray = nullptr; 334 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits()); 335 IntptrPtrTy = PointerType::getUnqual(IntptrTy); 336 Type *VoidTy = Type::getVoidTy(*C); 337 IRBuilder<> IRB(*C); 338 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty()); 339 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty()); 340 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty()); 341 Int64Ty = IRB.getInt64Ty(); 342 Int32Ty = IRB.getInt32Ty(); 343 Int16Ty = IRB.getInt16Ty(); 344 Int8Ty = IRB.getInt8Ty(); 345 346 SanCovTracePCIndir = checkSanitizerInterfaceFunction( 347 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy)); 348 SanCovTraceCmpFunction[0] = 349 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 350 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty())); 351 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction( 352 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(), 353 IRB.getInt16Ty())); 354 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction( 355 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(), 356 IRB.getInt32Ty())); 357 SanCovTraceCmpFunction[3] = 358 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 359 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty)); 360 361 SanCovTraceConstCmpFunction[0] = 362 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 363 SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty)); 364 SanCovTraceConstCmpFunction[1] = 365 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 366 SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty)); 367 SanCovTraceConstCmpFunction[2] = 368 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 369 SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty)); 370 SanCovTraceConstCmpFunction[3] = 371 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 372 SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty)); 373 374 SanCovTraceDivFunction[0] = 375 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 376 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty())); 377 SanCovTraceDivFunction[1] = 378 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 379 SanCovTraceDiv8, VoidTy, Int64Ty)); 380 SanCovTraceGepFunction = 381 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 382 SanCovTraceGep, VoidTy, IntptrTy)); 383 SanCovTraceSwitchFunction = 384 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 385 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy)); 386 387 Constant *SanCovLowestStackConstant = 388 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy); 389 SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant); 390 SanCovLowestStack->setThreadLocalMode( 391 GlobalValue::ThreadLocalMode::InitialExecTLSModel); 392 if (Options.StackDepth && !SanCovLowestStack->isDeclaration()) 393 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy)); 394 395 // Make sure smaller parameters are zero-extended to i64 as required by the 396 // x86_64 ABI. 397 if (TargetTriple.getArch() == Triple::x86_64) { 398 for (int i = 0; i < 3; i++) { 399 SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt); 400 SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt); 401 SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt); 402 SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt); 403 } 404 SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt); 405 } 406 407 408 // We insert an empty inline asm after cov callbacks to avoid callback merge. 409 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false), 410 StringRef(""), StringRef(""), 411 /*hasSideEffects=*/true); 412 413 SanCovTracePC = checkSanitizerInterfaceFunction( 414 M.getOrInsertFunction(SanCovTracePCName, VoidTy)); 415 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction( 416 SanCovTracePCGuardName, VoidTy, Int32PtrTy)); 417 418 for (auto &F : M) 419 runOnFunction(F); 420 421 Function *Ctor = nullptr; 422 423 if (FunctionGuardArray) 424 Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy, 425 SanCovGuardsSectionName); 426 if (Function8bitCounterArray) 427 Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy, 428 SanCovCountersSectionName); 429 if (Ctor && Options.PCTable) { 430 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy); 431 Function *InitFunction = declareSanitizerInitFunction( 432 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy}); 433 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator()); 434 Value *SecStartPtr = nullptr; 435 // Account for the fact that on windows-msvc __start_pc_table actually 436 // points to a uint64_t before the start of the PC table. 437 if (TargetTriple.getObjectFormat() == Triple::COFF) { 438 auto SecStartI8Ptr = IRB.CreatePointerCast(SecStartEnd.first, Int8PtrTy); 439 auto GEP = IRB.CreateGEP(SecStartI8Ptr, 440 ConstantInt::get(IntptrTy, sizeof(uint64_t))); 441 SecStartPtr = IRB.CreatePointerCast(GEP, IntptrPtrTy); 442 } else { 443 SecStartPtr = IRB.CreatePointerCast(SecStartEnd.first, IntptrPtrTy); 444 } 445 IRBCtor.CreateCall( 446 InitFunction, 447 {SecStartPtr, IRB.CreatePointerCast(SecStartEnd.second, IntptrPtrTy)}); 448 } 449 // We don't reference these arrays directly in any of our runtime functions, 450 // so we need to prevent them from being dead stripped. 451 if (TargetTriple.isOSBinFormatMachO()) 452 appendToUsed(M, GlobalsToAppendToUsed); 453 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed); 454 return true; 455 } 456 457 // True if block has successors and it dominates all of them. 458 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) { 459 if (succ_begin(BB) == succ_end(BB)) 460 return false; 461 462 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) { 463 if (!DT->dominates(BB, SUCC)) 464 return false; 465 } 466 467 return true; 468 } 469 470 // True if block has predecessors and it postdominates all of them. 471 static bool isFullPostDominator(const BasicBlock *BB, 472 const PostDominatorTree *PDT) { 473 if (pred_begin(BB) == pred_end(BB)) 474 return false; 475 476 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) { 477 if (!PDT->dominates(BB, PRED)) 478 return false; 479 } 480 481 return true; 482 } 483 484 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, 485 const DominatorTree *DT, 486 const PostDominatorTree *PDT, 487 const SanitizerCoverageOptions &Options) { 488 // Don't insert coverage for unreachable blocks: we will never call 489 // __sanitizer_cov() for them, so counting them in 490 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage 491 // percentage. Also, unreachable instructions frequently have no debug 492 // locations. 493 if (isa<UnreachableInst>(BB->getTerminator())) 494 return false; 495 496 // Don't insert coverage into blocks without a valid insertion point 497 // (catchswitch blocks). 498 if (BB->getFirstInsertionPt() == BB->end()) 499 return false; 500 501 if (Options.NoPrune || &F.getEntryBlock() == BB) 502 return true; 503 504 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function && 505 &F.getEntryBlock() != BB) 506 return false; 507 508 // Do not instrument full dominators, or full post-dominators with multiple 509 // predecessors. 510 return !isFullDominator(BB, DT) 511 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor()); 512 } 513 514 bool SanitizerCoverageModule::runOnFunction(Function &F) { 515 if (F.empty()) 516 return false; 517 if (F.getName().find(".module_ctor") != std::string::npos) 518 return false; // Should not instrument sanitizer init functions. 519 if (F.getName().startswith("__sanitizer_")) 520 return false; // Don't instrument __sanitizer_* callbacks. 521 // Don't touch available_externally functions, their actual body is elewhere. 522 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) 523 return false; 524 // Don't instrument MSVC CRT configuration helpers. They may run before normal 525 // initialization. 526 if (F.getName() == "__local_stdio_printf_options" || 527 F.getName() == "__local_stdio_scanf_options") 528 return false; 529 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator())) 530 return false; 531 // Don't instrument functions using SEH for now. Splitting basic blocks like 532 // we do for coverage breaks WinEHPrepare. 533 // FIXME: Remove this when SEH no longer uses landingpad pattern matching. 534 if (F.hasPersonalityFn() && 535 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) 536 return false; 537 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) 538 SplitAllCriticalEdges(F); 539 SmallVector<Instruction *, 8> IndirCalls; 540 SmallVector<BasicBlock *, 16> BlocksToInstrument; 541 SmallVector<Instruction *, 8> CmpTraceTargets; 542 SmallVector<Instruction *, 8> SwitchTraceTargets; 543 SmallVector<BinaryOperator *, 8> DivTraceTargets; 544 SmallVector<GetElementPtrInst *, 8> GepTraceTargets; 545 546 const DominatorTree *DT = 547 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); 548 const PostDominatorTree *PDT = 549 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree(); 550 bool IsLeafFunc = true; 551 552 for (auto &BB : F) { 553 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options)) 554 BlocksToInstrument.push_back(&BB); 555 for (auto &Inst : BB) { 556 if (Options.IndirectCalls) { 557 CallSite CS(&Inst); 558 if (CS && !CS.getCalledFunction()) 559 IndirCalls.push_back(&Inst); 560 } 561 if (Options.TraceCmp) { 562 if (isa<ICmpInst>(&Inst)) 563 CmpTraceTargets.push_back(&Inst); 564 if (isa<SwitchInst>(&Inst)) 565 SwitchTraceTargets.push_back(&Inst); 566 } 567 if (Options.TraceDiv) 568 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst)) 569 if (BO->getOpcode() == Instruction::SDiv || 570 BO->getOpcode() == Instruction::UDiv) 571 DivTraceTargets.push_back(BO); 572 if (Options.TraceGep) 573 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst)) 574 GepTraceTargets.push_back(GEP); 575 if (Options.StackDepth) 576 if (isa<InvokeInst>(Inst) || 577 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst))) 578 IsLeafFunc = false; 579 } 580 } 581 582 InjectCoverage(F, BlocksToInstrument, IsLeafFunc); 583 InjectCoverageForIndirectCalls(F, IndirCalls); 584 InjectTraceForCmp(F, CmpTraceTargets); 585 InjectTraceForSwitch(F, SwitchTraceTargets); 586 InjectTraceForDiv(F, DivTraceTargets); 587 InjectTraceForGep(F, GepTraceTargets); 588 return true; 589 } 590 591 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection( 592 size_t NumElements, Function &F, Type *Ty, const char *Section) { 593 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements); 594 auto Array = new GlobalVariable( 595 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage, 596 Constant::getNullValue(ArrayTy), "__sancov_gen_"); 597 598 if (TargetTriple.isOSBinFormatELF()) 599 if (auto Comdat = GetOrCreateFunctionComdat(F, CurModuleUniqueId)) 600 Array->setComdat(Comdat); 601 Array->setSection(getSectionName(Section)); 602 Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize() 603 : Ty->getPrimitiveSizeInBits() / 8); 604 GlobalsToAppendToUsed.push_back(Array); 605 GlobalsToAppendToCompilerUsed.push_back(Array); 606 MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F)); 607 Array->addMetadata(LLVMContext::MD_associated, *MD); 608 609 return Array; 610 } 611 612 GlobalVariable * 613 SanitizerCoverageModule::CreatePCArray(Function &F, 614 ArrayRef<BasicBlock *> AllBlocks) { 615 size_t N = AllBlocks.size(); 616 assert(N); 617 SmallVector<Constant *, 32> PCs; 618 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt()); 619 for (size_t i = 0; i < N; i++) { 620 if (&F.getEntryBlock() == AllBlocks[i]) { 621 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy)); 622 PCs.push_back((Constant *)IRB.CreateIntToPtr( 623 ConstantInt::get(IntptrTy, 1), IntptrPtrTy)); 624 } else { 625 PCs.push_back((Constant *)IRB.CreatePointerCast( 626 BlockAddress::get(AllBlocks[i]), IntptrPtrTy)); 627 PCs.push_back((Constant *)IRB.CreateIntToPtr( 628 ConstantInt::get(IntptrTy, 0), IntptrPtrTy)); 629 } 630 } 631 auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy, 632 SanCovPCsSectionName); 633 PCArray->setInitializer( 634 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs)); 635 PCArray->setConstant(true); 636 637 return PCArray; 638 } 639 640 void SanitizerCoverageModule::CreateFunctionLocalArrays( 641 Function &F, ArrayRef<BasicBlock *> AllBlocks) { 642 if (Options.TracePCGuard) 643 FunctionGuardArray = CreateFunctionLocalArrayInSection( 644 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName); 645 646 if (Options.Inline8bitCounters) 647 Function8bitCounterArray = CreateFunctionLocalArrayInSection( 648 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName); 649 650 if (Options.PCTable) 651 FunctionPCsArray = CreatePCArray(F, AllBlocks); 652 } 653 654 bool SanitizerCoverageModule::InjectCoverage(Function &F, 655 ArrayRef<BasicBlock *> AllBlocks, 656 bool IsLeafFunc) { 657 if (AllBlocks.empty()) return false; 658 CreateFunctionLocalArrays(F, AllBlocks); 659 for (size_t i = 0, N = AllBlocks.size(); i < N; i++) 660 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc); 661 return true; 662 } 663 664 // On every indirect call we call a run-time function 665 // __sanitizer_cov_indir_call* with two parameters: 666 // - callee address, 667 // - global cache array that contains CacheSize pointers (zero-initialized). 668 // The cache is used to speed up recording the caller-callee pairs. 669 // The address of the caller is passed implicitly via caller PC. 670 // CacheSize is encoded in the name of the run-time function. 671 void SanitizerCoverageModule::InjectCoverageForIndirectCalls( 672 Function &F, ArrayRef<Instruction *> IndirCalls) { 673 if (IndirCalls.empty()) 674 return; 675 assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters); 676 for (auto I : IndirCalls) { 677 IRBuilder<> IRB(I); 678 CallSite CS(I); 679 Value *Callee = CS.getCalledValue(); 680 if (isa<InlineAsm>(Callee)) 681 continue; 682 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy)); 683 } 684 } 685 686 // For every switch statement we insert a call: 687 // __sanitizer_cov_trace_switch(CondValue, 688 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... }) 689 690 void SanitizerCoverageModule::InjectTraceForSwitch( 691 Function &, ArrayRef<Instruction *> SwitchTraceTargets) { 692 for (auto I : SwitchTraceTargets) { 693 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) { 694 IRBuilder<> IRB(I); 695 SmallVector<Constant *, 16> Initializers; 696 Value *Cond = SI->getCondition(); 697 if (Cond->getType()->getScalarSizeInBits() > 698 Int64Ty->getScalarSizeInBits()) 699 continue; 700 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases())); 701 Initializers.push_back( 702 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits())); 703 if (Cond->getType()->getScalarSizeInBits() < 704 Int64Ty->getScalarSizeInBits()) 705 Cond = IRB.CreateIntCast(Cond, Int64Ty, false); 706 for (auto It : SI->cases()) { 707 Constant *C = It.getCaseValue(); 708 if (C->getType()->getScalarSizeInBits() < 709 Int64Ty->getScalarSizeInBits()) 710 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty); 711 Initializers.push_back(C); 712 } 713 llvm::sort(Initializers.begin() + 2, Initializers.end(), 714 [](const Constant *A, const Constant *B) { 715 return cast<ConstantInt>(A)->getLimitedValue() < 716 cast<ConstantInt>(B)->getLimitedValue(); 717 }); 718 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size()); 719 GlobalVariable *GV = new GlobalVariable( 720 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage, 721 ConstantArray::get(ArrayOfInt64Ty, Initializers), 722 "__sancov_gen_cov_switch_values"); 723 IRB.CreateCall(SanCovTraceSwitchFunction, 724 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)}); 725 } 726 } 727 } 728 729 void SanitizerCoverageModule::InjectTraceForDiv( 730 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) { 731 for (auto BO : DivTraceTargets) { 732 IRBuilder<> IRB(BO); 733 Value *A1 = BO->getOperand(1); 734 if (isa<ConstantInt>(A1)) continue; 735 if (!A1->getType()->isIntegerTy()) 736 continue; 737 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType()); 738 int CallbackIdx = TypeSize == 32 ? 0 : 739 TypeSize == 64 ? 1 : -1; 740 if (CallbackIdx < 0) continue; 741 auto Ty = Type::getIntNTy(*C, TypeSize); 742 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx], 743 {IRB.CreateIntCast(A1, Ty, true)}); 744 } 745 } 746 747 void SanitizerCoverageModule::InjectTraceForGep( 748 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) { 749 for (auto GEP : GepTraceTargets) { 750 IRBuilder<> IRB(GEP); 751 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) 752 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy()) 753 IRB.CreateCall(SanCovTraceGepFunction, 754 {IRB.CreateIntCast(*I, IntptrTy, true)}); 755 } 756 } 757 758 void SanitizerCoverageModule::InjectTraceForCmp( 759 Function &, ArrayRef<Instruction *> CmpTraceTargets) { 760 for (auto I : CmpTraceTargets) { 761 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) { 762 IRBuilder<> IRB(ICMP); 763 Value *A0 = ICMP->getOperand(0); 764 Value *A1 = ICMP->getOperand(1); 765 if (!A0->getType()->isIntegerTy()) 766 continue; 767 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType()); 768 int CallbackIdx = TypeSize == 8 ? 0 : 769 TypeSize == 16 ? 1 : 770 TypeSize == 32 ? 2 : 771 TypeSize == 64 ? 3 : -1; 772 if (CallbackIdx < 0) continue; 773 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1); 774 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx]; 775 bool FirstIsConst = isa<ConstantInt>(A0); 776 bool SecondIsConst = isa<ConstantInt>(A1); 777 // If both are const, then we don't need such a comparison. 778 if (FirstIsConst && SecondIsConst) continue; 779 // If only one is const, then make it the first callback argument. 780 if (FirstIsConst || SecondIsConst) { 781 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx]; 782 if (SecondIsConst) 783 std::swap(A0, A1); 784 } 785 786 auto Ty = Type::getIntNTy(*C, TypeSize); 787 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true), 788 IRB.CreateIntCast(A1, Ty, true)}); 789 } 790 } 791 } 792 793 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB, 794 size_t Idx, 795 bool IsLeafFunc) { 796 BasicBlock::iterator IP = BB.getFirstInsertionPt(); 797 bool IsEntryBB = &BB == &F.getEntryBlock(); 798 DebugLoc EntryLoc; 799 if (IsEntryBB) { 800 if (auto SP = F.getSubprogram()) 801 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP); 802 // Keep static allocas and llvm.localescape calls in the entry block. Even 803 // if we aren't splitting the block, it's nice for allocas to be before 804 // calls. 805 IP = PrepareToSplitEntryBlock(BB, IP); 806 } else { 807 EntryLoc = IP->getDebugLoc(); 808 } 809 810 IRBuilder<> IRB(&*IP); 811 IRB.SetCurrentDebugLocation(EntryLoc); 812 if (Options.TracePC) { 813 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC. 814 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge. 815 } 816 if (Options.TracePCGuard) { 817 auto GuardPtr = IRB.CreateIntToPtr( 818 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), 819 ConstantInt::get(IntptrTy, Idx * 4)), 820 Int32PtrTy); 821 IRB.CreateCall(SanCovTracePCGuard, GuardPtr); 822 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge. 823 } 824 if (Options.Inline8bitCounters) { 825 auto CounterPtr = IRB.CreateGEP( 826 Function8bitCounterArray, 827 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)}); 828 auto Load = IRB.CreateLoad(CounterPtr); 829 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1)); 830 auto Store = IRB.CreateStore(Inc, CounterPtr); 831 SetNoSanitizeMetadata(Load); 832 SetNoSanitizeMetadata(Store); 833 } 834 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) { 835 // Check stack depth. If it's the deepest so far, record it. 836 Function *GetFrameAddr = 837 Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress); 838 auto FrameAddrPtr = 839 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)}); 840 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy); 841 auto LowestStack = IRB.CreateLoad(SanCovLowestStack); 842 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack); 843 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false); 844 IRBuilder<> ThenIRB(ThenTerm); 845 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack); 846 SetNoSanitizeMetadata(LowestStack); 847 SetNoSanitizeMetadata(Store); 848 } 849 } 850 851 std::string 852 SanitizerCoverageModule::getSectionName(const std::string &Section) const { 853 if (TargetTriple.getObjectFormat() == Triple::COFF) { 854 if (Section == SanCovCountersSectionName) 855 return ".SCOV$CM"; 856 if (Section == SanCovPCsSectionName) 857 return ".SCOVP$M"; 858 return ".SCOV$GM"; // For SanCovGuardsSectionName. 859 } 860 if (TargetTriple.isOSBinFormatMachO()) 861 return "__DATA,__" + Section; 862 return "__" + Section; 863 } 864 865 std::string 866 SanitizerCoverageModule::getSectionStart(const std::string &Section) const { 867 if (TargetTriple.isOSBinFormatMachO()) 868 return "\1section$start$__DATA$__" + Section; 869 return "__start___" + Section; 870 } 871 872 std::string 873 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const { 874 if (TargetTriple.isOSBinFormatMachO()) 875 return "\1section$end$__DATA$__" + Section; 876 return "__stop___" + Section; 877 } 878 879 880 char SanitizerCoverageModule::ID = 0; 881 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov", 882 "SanitizerCoverage: TODO." 883 "ModulePass", 884 false, false) 885 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 886 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 887 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov", 888 "SanitizerCoverage: TODO." 889 "ModulePass", 890 false, false) 891 ModulePass *llvm::createSanitizerCoverageModulePass( 892 const SanitizerCoverageOptions &Options) { 893 return new SanitizerCoverageModule(Options); 894 } 895