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