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/Module.h" 33 #include "llvm/IR/Type.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Transforms/Instrumentation.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 bool IsLeafFunc = true); 205 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements, 206 Function &F, Type *Ty, 207 const char *Section); 208 GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks); 209 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks); 210 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx, 211 bool IsLeafFunc = true); 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 GlobalVariable *SanCovLowestStack; 233 InlineAsm *EmptyAsm; 234 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy, 235 *Int16Ty, *Int8Ty, *Int8PtrTy; 236 Module *CurModule; 237 Triple TargetTriple; 238 LLVMContext *C; 239 const DataLayout *DL; 240 241 GlobalVariable *FunctionGuardArray; // for trace-pc-guard. 242 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters. 243 GlobalVariable *FunctionPCsArray; // for pc-table. 244 SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed; 245 SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed; 246 247 SanitizerCoverageOptions Options; 248 }; 249 250 } // namespace 251 252 std::pair<GlobalVariable *, GlobalVariable *> 253 SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section, 254 Type *Ty) { 255 GlobalVariable *SecStart = 256 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr, 257 getSectionStart(Section)); 258 SecStart->setVisibility(GlobalValue::HiddenVisibility); 259 GlobalVariable *SecEnd = 260 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, 261 nullptr, getSectionEnd(Section)); 262 SecEnd->setVisibility(GlobalValue::HiddenVisibility); 263 264 return std::make_pair(SecStart, SecEnd); 265 } 266 267 268 Function *SanitizerCoverageModule::CreateInitCallsForSections( 269 Module &M, const char *InitFunctionName, Type *Ty, 270 const char *Section) { 271 IRBuilder<> IRB(M.getContext()); 272 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty); 273 auto SecStart = SecStartEnd.first; 274 auto SecEnd = SecStartEnd.second; 275 Function *CtorFunc; 276 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions( 277 M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty}, 278 {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)}); 279 280 if (TargetTriple.supportsCOMDAT()) { 281 // Use comdat to dedup CtorFunc. 282 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName)); 283 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc); 284 } else { 285 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority); 286 } 287 return CtorFunc; 288 } 289 290 bool SanitizerCoverageModule::runOnModule(Module &M) { 291 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None) 292 return false; 293 C = &(M.getContext()); 294 DL = &M.getDataLayout(); 295 CurModule = &M; 296 TargetTriple = Triple(M.getTargetTriple()); 297 FunctionGuardArray = nullptr; 298 Function8bitCounterArray = nullptr; 299 FunctionPCsArray = nullptr; 300 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits()); 301 IntptrPtrTy = PointerType::getUnqual(IntptrTy); 302 Type *VoidTy = Type::getVoidTy(*C); 303 IRBuilder<> IRB(*C); 304 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty()); 305 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty()); 306 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty()); 307 Int64Ty = IRB.getInt64Ty(); 308 Int32Ty = IRB.getInt32Ty(); 309 Int16Ty = IRB.getInt16Ty(); 310 Int8Ty = IRB.getInt8Ty(); 311 312 SanCovTracePCIndir = checkSanitizerInterfaceFunction( 313 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy)); 314 SanCovTraceCmpFunction[0] = 315 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 316 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty())); 317 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction( 318 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(), 319 IRB.getInt16Ty())); 320 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction( 321 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(), 322 IRB.getInt32Ty())); 323 SanCovTraceCmpFunction[3] = 324 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 325 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty)); 326 327 SanCovTraceConstCmpFunction[0] = 328 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 329 SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty)); 330 SanCovTraceConstCmpFunction[1] = 331 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 332 SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty)); 333 SanCovTraceConstCmpFunction[2] = 334 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 335 SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty)); 336 SanCovTraceConstCmpFunction[3] = 337 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 338 SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty)); 339 340 SanCovTraceDivFunction[0] = 341 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 342 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty())); 343 SanCovTraceDivFunction[1] = 344 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 345 SanCovTraceDiv8, VoidTy, Int64Ty)); 346 SanCovTraceGepFunction = 347 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 348 SanCovTraceGep, VoidTy, IntptrTy)); 349 SanCovTraceSwitchFunction = 350 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 351 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy)); 352 353 Constant *SanCovLowestStackConstant = 354 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy); 355 SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant); 356 SanCovLowestStack->setThreadLocalMode( 357 GlobalValue::ThreadLocalMode::InitialExecTLSModel); 358 if (Options.StackDepth && !SanCovLowestStack->isDeclaration()) 359 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy)); 360 361 // Make sure smaller parameters are zero-extended to i64 as required by the 362 // x86_64 ABI. 363 if (TargetTriple.getArch() == Triple::x86_64) { 364 for (int i = 0; i < 3; i++) { 365 SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt); 366 SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt); 367 SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt); 368 SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt); 369 } 370 SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt); 371 } 372 373 374 // We insert an empty inline asm after cov callbacks to avoid callback merge. 375 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false), 376 StringRef(""), StringRef(""), 377 /*hasSideEffects=*/true); 378 379 SanCovTracePC = checkSanitizerInterfaceFunction( 380 M.getOrInsertFunction(SanCovTracePCName, VoidTy)); 381 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction( 382 SanCovTracePCGuardName, VoidTy, Int32PtrTy)); 383 384 for (auto &F : M) 385 runOnFunction(F); 386 387 Function *Ctor = nullptr; 388 389 if (FunctionGuardArray) 390 Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy, 391 SanCovGuardsSectionName); 392 if (Function8bitCounterArray) 393 Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy, 394 SanCovCountersSectionName); 395 if (Ctor && Options.PCTable) { 396 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy); 397 Function *InitFunction = declareSanitizerInitFunction( 398 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy}); 399 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator()); 400 IRBCtor.CreateCall(InitFunction, 401 {IRB.CreatePointerCast(SecStartEnd.first, IntptrPtrTy), 402 IRB.CreatePointerCast(SecStartEnd.second, IntptrPtrTy)}); 403 } 404 // We don't reference these arrays directly in any of our runtime functions, 405 // so we need to prevent them from being dead stripped. 406 if (TargetTriple.isOSBinFormatMachO()) 407 appendToUsed(M, GlobalsToAppendToUsed); 408 appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed); 409 return true; 410 } 411 412 // True if block has successors and it dominates all of them. 413 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) { 414 if (succ_begin(BB) == succ_end(BB)) 415 return false; 416 417 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) { 418 if (!DT->dominates(BB, SUCC)) 419 return false; 420 } 421 422 return true; 423 } 424 425 // True if block has predecessors and it postdominates all of them. 426 static bool isFullPostDominator(const BasicBlock *BB, 427 const PostDominatorTree *PDT) { 428 if (pred_begin(BB) == pred_end(BB)) 429 return false; 430 431 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) { 432 if (!PDT->dominates(BB, PRED)) 433 return false; 434 } 435 436 return true; 437 } 438 439 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, 440 const DominatorTree *DT, 441 const PostDominatorTree *PDT, 442 const SanitizerCoverageOptions &Options) { 443 // Don't insert coverage for unreachable blocks: we will never call 444 // __sanitizer_cov() for them, so counting them in 445 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage 446 // percentage. Also, unreachable instructions frequently have no debug 447 // locations. 448 if (isa<UnreachableInst>(BB->getTerminator())) 449 return false; 450 451 // Don't insert coverage into blocks without a valid insertion point 452 // (catchswitch blocks). 453 if (BB->getFirstInsertionPt() == BB->end()) 454 return false; 455 456 if (Options.NoPrune || &F.getEntryBlock() == BB) 457 return true; 458 459 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function && 460 &F.getEntryBlock() != BB) 461 return false; 462 463 // Do not instrument full dominators, or full post-dominators with multiple 464 // predecessors. 465 return !isFullDominator(BB, DT) 466 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor()); 467 } 468 469 bool SanitizerCoverageModule::runOnFunction(Function &F) { 470 if (F.empty()) 471 return false; 472 if (F.getName().find(".module_ctor") != std::string::npos) 473 return false; // Should not instrument sanitizer init functions. 474 if (F.getName().startswith("__sanitizer_")) 475 return false; // Don't instrument __sanitizer_* callbacks. 476 // Don't touch available_externally functions, their actual body is elewhere. 477 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) 478 return false; 479 // Don't instrument MSVC CRT configuration helpers. They may run before normal 480 // initialization. 481 if (F.getName() == "__local_stdio_printf_options" || 482 F.getName() == "__local_stdio_scanf_options") 483 return false; 484 if (isa<UnreachableInst>(F.getEntryBlock().getTerminator())) 485 return false; 486 // Don't instrument functions using SEH for now. Splitting basic blocks like 487 // we do for coverage breaks WinEHPrepare. 488 // FIXME: Remove this when SEH no longer uses landingpad pattern matching. 489 if (F.hasPersonalityFn() && 490 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) 491 return false; 492 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) 493 SplitAllCriticalEdges(F); 494 SmallVector<Instruction *, 8> IndirCalls; 495 SmallVector<BasicBlock *, 16> BlocksToInstrument; 496 SmallVector<Instruction *, 8> CmpTraceTargets; 497 SmallVector<Instruction *, 8> SwitchTraceTargets; 498 SmallVector<BinaryOperator *, 8> DivTraceTargets; 499 SmallVector<GetElementPtrInst *, 8> GepTraceTargets; 500 501 const DominatorTree *DT = 502 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); 503 const PostDominatorTree *PDT = 504 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree(); 505 bool IsLeafFunc = true; 506 507 for (auto &BB : F) { 508 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options)) 509 BlocksToInstrument.push_back(&BB); 510 for (auto &Inst : BB) { 511 if (Options.IndirectCalls) { 512 CallSite CS(&Inst); 513 if (CS && !CS.getCalledFunction()) 514 IndirCalls.push_back(&Inst); 515 } 516 if (Options.TraceCmp) { 517 if (isa<ICmpInst>(&Inst)) 518 CmpTraceTargets.push_back(&Inst); 519 if (isa<SwitchInst>(&Inst)) 520 SwitchTraceTargets.push_back(&Inst); 521 } 522 if (Options.TraceDiv) 523 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst)) 524 if (BO->getOpcode() == Instruction::SDiv || 525 BO->getOpcode() == Instruction::UDiv) 526 DivTraceTargets.push_back(BO); 527 if (Options.TraceGep) 528 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst)) 529 GepTraceTargets.push_back(GEP); 530 if (Options.StackDepth) 531 if (isa<InvokeInst>(Inst) || 532 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst))) 533 IsLeafFunc = false; 534 } 535 } 536 537 InjectCoverage(F, BlocksToInstrument, IsLeafFunc); 538 InjectCoverageForIndirectCalls(F, IndirCalls); 539 InjectTraceForCmp(F, CmpTraceTargets); 540 InjectTraceForSwitch(F, SwitchTraceTargets); 541 InjectTraceForDiv(F, DivTraceTargets); 542 InjectTraceForGep(F, GepTraceTargets); 543 return true; 544 } 545 546 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection( 547 size_t NumElements, Function &F, Type *Ty, const char *Section) { 548 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements); 549 auto Array = new GlobalVariable( 550 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage, 551 Constant::getNullValue(ArrayTy), "__sancov_gen_"); 552 if (auto Comdat = F.getComdat()) 553 Array->setComdat(Comdat); 554 Array->setSection(getSectionName(Section)); 555 Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize() 556 : Ty->getPrimitiveSizeInBits() / 8); 557 return Array; 558 } 559 560 GlobalVariable * 561 SanitizerCoverageModule::CreatePCArray(Function &F, 562 ArrayRef<BasicBlock *> AllBlocks) { 563 size_t N = AllBlocks.size(); 564 assert(N); 565 SmallVector<Constant *, 32> PCs; 566 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt()); 567 for (size_t i = 0; i < N; i++) { 568 if (&F.getEntryBlock() == AllBlocks[i]) { 569 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy)); 570 PCs.push_back((Constant *)IRB.CreateIntToPtr( 571 ConstantInt::get(IntptrTy, 1), IntptrPtrTy)); 572 } else { 573 PCs.push_back((Constant *)IRB.CreatePointerCast( 574 BlockAddress::get(AllBlocks[i]), IntptrPtrTy)); 575 PCs.push_back((Constant *)IRB.CreateIntToPtr( 576 ConstantInt::get(IntptrTy, 0), IntptrPtrTy)); 577 } 578 } 579 auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy, 580 SanCovPCsSectionName); 581 PCArray->setInitializer( 582 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs)); 583 PCArray->setConstant(true); 584 585 return PCArray; 586 } 587 588 void SanitizerCoverageModule::CreateFunctionLocalArrays( 589 Function &F, ArrayRef<BasicBlock *> AllBlocks) { 590 if (Options.TracePCGuard) { 591 FunctionGuardArray = CreateFunctionLocalArrayInSection( 592 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName); 593 GlobalsToAppendToUsed.push_back(FunctionGuardArray); 594 GlobalsToAppendToCompilerUsed.push_back(FunctionGuardArray); 595 MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F)); 596 FunctionGuardArray->addMetadata(LLVMContext::MD_associated, *MD); 597 } 598 if (Options.Inline8bitCounters) { 599 Function8bitCounterArray = CreateFunctionLocalArrayInSection( 600 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName); 601 GlobalsToAppendToCompilerUsed.push_back(Function8bitCounterArray); 602 MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F)); 603 Function8bitCounterArray->addMetadata(LLVMContext::MD_associated, *MD); 604 } 605 if (Options.PCTable) { 606 FunctionPCsArray = CreatePCArray(F, AllBlocks); 607 GlobalsToAppendToCompilerUsed.push_back(FunctionPCsArray); 608 MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F)); 609 FunctionPCsArray->addMetadata(LLVMContext::MD_associated, *MD); 610 } 611 } 612 613 bool SanitizerCoverageModule::InjectCoverage(Function &F, 614 ArrayRef<BasicBlock *> AllBlocks, 615 bool IsLeafFunc) { 616 if (AllBlocks.empty()) return false; 617 CreateFunctionLocalArrays(F, AllBlocks); 618 for (size_t i = 0, N = AllBlocks.size(); i < N; i++) 619 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc); 620 return true; 621 } 622 623 // On every indirect call we call a run-time function 624 // __sanitizer_cov_indir_call* with two parameters: 625 // - callee address, 626 // - global cache array that contains CacheSize pointers (zero-initialized). 627 // The cache is used to speed up recording the caller-callee pairs. 628 // The address of the caller is passed implicitly via caller PC. 629 // CacheSize is encoded in the name of the run-time function. 630 void SanitizerCoverageModule::InjectCoverageForIndirectCalls( 631 Function &F, ArrayRef<Instruction *> IndirCalls) { 632 if (IndirCalls.empty()) 633 return; 634 assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters); 635 for (auto I : IndirCalls) { 636 IRBuilder<> IRB(I); 637 CallSite CS(I); 638 Value *Callee = CS.getCalledValue(); 639 if (isa<InlineAsm>(Callee)) 640 continue; 641 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy)); 642 } 643 } 644 645 // For every switch statement we insert a call: 646 // __sanitizer_cov_trace_switch(CondValue, 647 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... }) 648 649 void SanitizerCoverageModule::InjectTraceForSwitch( 650 Function &, ArrayRef<Instruction *> SwitchTraceTargets) { 651 for (auto I : SwitchTraceTargets) { 652 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) { 653 IRBuilder<> IRB(I); 654 SmallVector<Constant *, 16> Initializers; 655 Value *Cond = SI->getCondition(); 656 if (Cond->getType()->getScalarSizeInBits() > 657 Int64Ty->getScalarSizeInBits()) 658 continue; 659 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases())); 660 Initializers.push_back( 661 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits())); 662 if (Cond->getType()->getScalarSizeInBits() < 663 Int64Ty->getScalarSizeInBits()) 664 Cond = IRB.CreateIntCast(Cond, Int64Ty, false); 665 for (auto It : SI->cases()) { 666 Constant *C = It.getCaseValue(); 667 if (C->getType()->getScalarSizeInBits() < 668 Int64Ty->getScalarSizeInBits()) 669 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty); 670 Initializers.push_back(C); 671 } 672 llvm::sort(Initializers.begin() + 2, Initializers.end(), 673 [](const Constant *A, const Constant *B) { 674 return cast<ConstantInt>(A)->getLimitedValue() < 675 cast<ConstantInt>(B)->getLimitedValue(); 676 }); 677 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size()); 678 GlobalVariable *GV = new GlobalVariable( 679 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage, 680 ConstantArray::get(ArrayOfInt64Ty, Initializers), 681 "__sancov_gen_cov_switch_values"); 682 IRB.CreateCall(SanCovTraceSwitchFunction, 683 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)}); 684 } 685 } 686 } 687 688 void SanitizerCoverageModule::InjectTraceForDiv( 689 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) { 690 for (auto BO : DivTraceTargets) { 691 IRBuilder<> IRB(BO); 692 Value *A1 = BO->getOperand(1); 693 if (isa<ConstantInt>(A1)) continue; 694 if (!A1->getType()->isIntegerTy()) 695 continue; 696 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType()); 697 int CallbackIdx = TypeSize == 32 ? 0 : 698 TypeSize == 64 ? 1 : -1; 699 if (CallbackIdx < 0) continue; 700 auto Ty = Type::getIntNTy(*C, TypeSize); 701 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx], 702 {IRB.CreateIntCast(A1, Ty, true)}); 703 } 704 } 705 706 void SanitizerCoverageModule::InjectTraceForGep( 707 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) { 708 for (auto GEP : GepTraceTargets) { 709 IRBuilder<> IRB(GEP); 710 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) 711 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy()) 712 IRB.CreateCall(SanCovTraceGepFunction, 713 {IRB.CreateIntCast(*I, IntptrTy, true)}); 714 } 715 } 716 717 void SanitizerCoverageModule::InjectTraceForCmp( 718 Function &, ArrayRef<Instruction *> CmpTraceTargets) { 719 for (auto I : CmpTraceTargets) { 720 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) { 721 IRBuilder<> IRB(ICMP); 722 Value *A0 = ICMP->getOperand(0); 723 Value *A1 = ICMP->getOperand(1); 724 if (!A0->getType()->isIntegerTy()) 725 continue; 726 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType()); 727 int CallbackIdx = TypeSize == 8 ? 0 : 728 TypeSize == 16 ? 1 : 729 TypeSize == 32 ? 2 : 730 TypeSize == 64 ? 3 : -1; 731 if (CallbackIdx < 0) continue; 732 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1); 733 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx]; 734 bool FirstIsConst = isa<ConstantInt>(A0); 735 bool SecondIsConst = isa<ConstantInt>(A1); 736 // If both are const, then we don't need such a comparison. 737 if (FirstIsConst && SecondIsConst) continue; 738 // If only one is const, then make it the first callback argument. 739 if (FirstIsConst || SecondIsConst) { 740 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx]; 741 if (SecondIsConst) 742 std::swap(A0, A1); 743 } 744 745 auto Ty = Type::getIntNTy(*C, TypeSize); 746 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true), 747 IRB.CreateIntCast(A1, Ty, true)}); 748 } 749 } 750 } 751 752 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB, 753 size_t Idx, 754 bool IsLeafFunc) { 755 BasicBlock::iterator IP = BB.getFirstInsertionPt(); 756 bool IsEntryBB = &BB == &F.getEntryBlock(); 757 DebugLoc EntryLoc; 758 if (IsEntryBB) { 759 if (auto SP = F.getSubprogram()) 760 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP); 761 // Keep static allocas and llvm.localescape calls in the entry block. Even 762 // if we aren't splitting the block, it's nice for allocas to be before 763 // calls. 764 IP = PrepareToSplitEntryBlock(BB, IP); 765 } else { 766 EntryLoc = IP->getDebugLoc(); 767 } 768 769 IRBuilder<> IRB(&*IP); 770 IRB.SetCurrentDebugLocation(EntryLoc); 771 if (Options.TracePC) { 772 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC. 773 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge. 774 } 775 if (Options.TracePCGuard) { 776 auto GuardPtr = IRB.CreateIntToPtr( 777 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), 778 ConstantInt::get(IntptrTy, Idx * 4)), 779 Int32PtrTy); 780 IRB.CreateCall(SanCovTracePCGuard, GuardPtr); 781 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge. 782 } 783 if (Options.Inline8bitCounters) { 784 auto CounterPtr = IRB.CreateGEP( 785 Function8bitCounterArray, 786 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)}); 787 auto Load = IRB.CreateLoad(CounterPtr); 788 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1)); 789 auto Store = IRB.CreateStore(Inc, CounterPtr); 790 SetNoSanitizeMetadata(Load); 791 SetNoSanitizeMetadata(Store); 792 } 793 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) { 794 // Check stack depth. If it's the deepest so far, record it. 795 Function *GetFrameAddr = 796 Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress); 797 auto FrameAddrPtr = 798 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)}); 799 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy); 800 auto LowestStack = IRB.CreateLoad(SanCovLowestStack); 801 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack); 802 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false); 803 IRBuilder<> ThenIRB(ThenTerm); 804 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack); 805 SetNoSanitizeMetadata(LowestStack); 806 SetNoSanitizeMetadata(Store); 807 } 808 } 809 810 std::string 811 SanitizerCoverageModule::getSectionName(const std::string &Section) const { 812 if (TargetTriple.getObjectFormat() == Triple::COFF) 813 return ".SCOV$M"; 814 if (TargetTriple.isOSBinFormatMachO()) 815 return "__DATA,__" + Section; 816 return "__" + Section; 817 } 818 819 std::string 820 SanitizerCoverageModule::getSectionStart(const std::string &Section) const { 821 if (TargetTriple.isOSBinFormatMachO()) 822 return "\1section$start$__DATA$__" + Section; 823 return "__start___" + Section; 824 } 825 826 std::string 827 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const { 828 if (TargetTriple.isOSBinFormatMachO()) 829 return "\1section$end$__DATA$__" + Section; 830 return "__stop___" + Section; 831 } 832 833 834 char SanitizerCoverageModule::ID = 0; 835 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov", 836 "SanitizerCoverage: TODO." 837 "ModulePass", 838 false, false) 839 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 840 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 841 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov", 842 "SanitizerCoverage: TODO." 843 "ModulePass", 844 false, false) 845 ModulePass *llvm::createSanitizerCoverageModulePass( 846 const SanitizerCoverageOptions &Options) { 847 return new SanitizerCoverageModule(Options); 848 } 849