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