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