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