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 that works with AddressSanitizer 11 // and potentially with other Sanitizers. 12 // 13 // We create a Guard variable with the same linkage 14 // as the function and inject this code into the entry block (SCK_Function) 15 // or all blocks (SCK_BB): 16 // if (Guard < 0) { 17 // __sanitizer_cov(&Guard); 18 // } 19 // The accesses to Guard are atomic. The rest of the logic is 20 // in __sanitizer_cov (it's fine to call it more than once). 21 // 22 // With SCK_Edge we also split critical edges this effectively 23 // instrumenting all edges. 24 // 25 // This coverage implementation provides very limited data: 26 // it only tells if a given function (block) was ever executed. No counters. 27 // But for many use cases this is what we need and the added slowdown small. 28 // 29 //===----------------------------------------------------------------------===// 30 31 #include "llvm/Transforms/Instrumentation.h" 32 #include "llvm/ADT/ArrayRef.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/IR/CallSite.h" 35 #include "llvm/IR/DataLayout.h" 36 #include "llvm/IR/Function.h" 37 #include "llvm/IR/IRBuilder.h" 38 #include "llvm/IR/InlineAsm.h" 39 #include "llvm/IR/LLVMContext.h" 40 #include "llvm/IR/MDBuilder.h" 41 #include "llvm/IR/Module.h" 42 #include "llvm/IR/Type.h" 43 #include "llvm/Support/CommandLine.h" 44 #include "llvm/Support/Debug.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Transforms/Scalar.h" 47 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 48 #include "llvm/Transforms/Utils/ModuleUtils.h" 49 50 using namespace llvm; 51 52 #define DEBUG_TYPE "sancov" 53 54 static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init"; 55 static const char *const kSanCovName = "__sanitizer_cov"; 56 static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check"; 57 static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16"; 58 static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter"; 59 static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block"; 60 static const char *const kSanCovTraceCmp = "__sanitizer_cov_trace_cmp"; 61 static const char *const kSanCovModuleCtorName = "sancov.module_ctor"; 62 static const uint64_t kSanCtorAndDtorPriority = 2; 63 64 static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level", 65 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, " 66 "3: all blocks and critical edges, " 67 "4: above plus indirect calls"), 68 cl::Hidden, cl::init(0)); 69 70 static cl::opt<unsigned> ClCoverageBlockThreshold( 71 "sanitizer-coverage-block-threshold", 72 cl::desc("Use a callback with a guard check inside it if there are" 73 " more than this number of blocks."), 74 cl::Hidden, cl::init(500)); 75 76 static cl::opt<bool> 77 ClExperimentalTracing("sanitizer-coverage-experimental-tracing", 78 cl::desc("Experimental basic-block tracing: insert " 79 "callbacks at every basic block"), 80 cl::Hidden, cl::init(false)); 81 82 static cl::opt<bool> 83 ClExperimentalCMPTracing("sanitizer-coverage-experimental-trace-compares", 84 cl::desc("Experimental tracing of CMP and similar " 85 "instructions"), 86 cl::Hidden, cl::init(false)); 87 88 // Experimental 8-bit counters used as an additional search heuristic during 89 // coverage-guided fuzzing. 90 // The counters are not thread-friendly: 91 // - contention on these counters may cause significant slowdown; 92 // - the counter updates are racy and the results may be inaccurate. 93 // They are also inaccurate due to 8-bit integer overflow. 94 static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters", 95 cl::desc("Experimental 8-bit counters"), 96 cl::Hidden, cl::init(false)); 97 98 namespace { 99 100 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) { 101 SanitizerCoverageOptions Res; 102 switch (LegacyCoverageLevel) { 103 case 0: 104 Res.CoverageType = SanitizerCoverageOptions::SCK_None; 105 break; 106 case 1: 107 Res.CoverageType = SanitizerCoverageOptions::SCK_Function; 108 break; 109 case 2: 110 Res.CoverageType = SanitizerCoverageOptions::SCK_BB; 111 break; 112 case 3: 113 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge; 114 break; 115 case 4: 116 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge; 117 Res.IndirectCalls = true; 118 break; 119 } 120 return Res; 121 } 122 123 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) { 124 // Sets CoverageType and IndirectCalls. 125 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel); 126 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType); 127 Options.IndirectCalls |= CLOpts.IndirectCalls; 128 Options.TraceBB |= ClExperimentalTracing; 129 Options.TraceCmp |= ClExperimentalCMPTracing; 130 Options.Use8bitCounters |= ClUse8bitCounters; 131 return Options; 132 } 133 134 class SanitizerCoverageModule : public ModulePass { 135 public: 136 SanitizerCoverageModule( 137 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions()) 138 : ModulePass(ID), Options(OverrideFromCL(Options)) {} 139 bool runOnModule(Module &M) override; 140 bool runOnFunction(Function &F); 141 static char ID; // Pass identification, replacement for typeid 142 const char *getPassName() const override { 143 return "SanitizerCoverageModule"; 144 } 145 146 private: 147 void InjectCoverageForIndirectCalls(Function &F, 148 ArrayRef<Instruction *> IndirCalls); 149 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets); 150 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks); 151 void SetNoSanitizeMetadata(Instruction *I); 152 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls); 153 unsigned NumberOfInstrumentedBlocks() { 154 return SanCovFunction->getNumUses() + SanCovWithCheckFunction->getNumUses(); 155 } 156 Function *SanCovFunction; 157 Function *SanCovWithCheckFunction; 158 Function *SanCovIndirCallFunction; 159 Function *SanCovTraceEnter, *SanCovTraceBB; 160 Function *SanCovTraceCmpFunction; 161 InlineAsm *EmptyAsm; 162 Type *IntptrTy, *Int64Ty; 163 LLVMContext *C; 164 const DataLayout *DL; 165 166 GlobalVariable *GuardArray; 167 GlobalVariable *EightBitCounterArray; 168 169 SanitizerCoverageOptions Options; 170 }; 171 172 } // namespace 173 174 bool SanitizerCoverageModule::runOnModule(Module &M) { 175 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None) 176 return false; 177 C = &(M.getContext()); 178 DL = &M.getDataLayout(); 179 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits()); 180 Type *VoidTy = Type::getVoidTy(*C); 181 IRBuilder<> IRB(*C); 182 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty()); 183 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty()); 184 Int64Ty = IRB.getInt64Ty(); 185 186 SanCovFunction = checkSanitizerInterfaceFunction( 187 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr)); 188 SanCovWithCheckFunction = checkSanitizerInterfaceFunction( 189 M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr)); 190 SanCovIndirCallFunction = 191 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 192 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr)); 193 SanCovTraceCmpFunction = 194 checkSanitizerInterfaceFunction(M.getOrInsertFunction( 195 kSanCovTraceCmp, VoidTy, Int64Ty, Int64Ty, Int64Ty, nullptr)); 196 197 // We insert an empty inline asm after cov callbacks to avoid callback merge. 198 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false), 199 StringRef(""), StringRef(""), 200 /*hasSideEffects=*/true); 201 202 if (Options.TraceBB) { 203 SanCovTraceEnter = checkSanitizerInterfaceFunction( 204 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr)); 205 SanCovTraceBB = checkSanitizerInterfaceFunction( 206 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr)); 207 } 208 209 // At this point we create a dummy array of guards because we don't 210 // know how many elements we will need. 211 Type *Int32Ty = IRB.getInt32Ty(); 212 Type *Int8Ty = IRB.getInt8Ty(); 213 214 GuardArray = 215 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage, 216 nullptr, "__sancov_gen_cov_tmp"); 217 if (Options.Use8bitCounters) 218 EightBitCounterArray = 219 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage, 220 nullptr, "__sancov_gen_cov_tmp"); 221 222 for (auto &F : M) 223 runOnFunction(F); 224 225 auto N = NumberOfInstrumentedBlocks(); 226 227 // Now we know how many elements we need. Create an array of guards 228 // with one extra element at the beginning for the size. 229 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1); 230 GlobalVariable *RealGuardArray = new GlobalVariable( 231 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage, 232 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov"); 233 234 235 // Replace the dummy array with the real one. 236 GuardArray->replaceAllUsesWith( 237 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy)); 238 GuardArray->eraseFromParent(); 239 240 GlobalVariable *RealEightBitCounterArray; 241 if (Options.Use8bitCounters) { 242 // Make sure the array is 16-aligned. 243 static const int kCounterAlignment = 16; 244 Type *Int8ArrayNTy = 245 ArrayType::get(Int8Ty, RoundUpToAlignment(N, kCounterAlignment)); 246 RealEightBitCounterArray = new GlobalVariable( 247 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage, 248 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter"); 249 RealEightBitCounterArray->setAlignment(kCounterAlignment); 250 EightBitCounterArray->replaceAllUsesWith( 251 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)); 252 EightBitCounterArray->eraseFromParent(); 253 } 254 255 // Create variable for module (compilation unit) name 256 Constant *ModNameStrConst = 257 ConstantDataArray::getString(M.getContext(), M.getName(), true); 258 GlobalVariable *ModuleName = 259 new GlobalVariable(M, ModNameStrConst->getType(), true, 260 GlobalValue::PrivateLinkage, ModNameStrConst); 261 262 Function *CtorFunc; 263 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions( 264 M, kSanCovModuleCtorName, kSanCovModuleInitName, 265 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy}, 266 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy), 267 ConstantInt::get(IntptrTy, N), 268 Options.Use8bitCounters 269 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy) 270 : Constant::getNullValue(Int8PtrTy), 271 IRB.CreatePointerCast(ModuleName, Int8PtrTy)}); 272 273 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority); 274 275 return true; 276 } 277 278 bool SanitizerCoverageModule::runOnFunction(Function &F) { 279 if (F.empty()) return false; 280 if (F.getName().find(".module_ctor") != std::string::npos) 281 return false; // Should not instrument sanitizer init functions. 282 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) 283 SplitAllCriticalEdges(F); 284 SmallVector<Instruction*, 8> IndirCalls; 285 SmallVector<BasicBlock*, 16> AllBlocks; 286 SmallVector<Instruction*, 8> CmpTraceTargets; 287 for (auto &BB : F) { 288 AllBlocks.push_back(&BB); 289 for (auto &Inst : BB) { 290 if (Options.IndirectCalls) { 291 CallSite CS(&Inst); 292 if (CS && !CS.getCalledFunction()) 293 IndirCalls.push_back(&Inst); 294 } 295 if (Options.TraceCmp && isa<ICmpInst>(&Inst)) 296 CmpTraceTargets.push_back(&Inst); 297 } 298 } 299 InjectCoverage(F, AllBlocks); 300 InjectCoverageForIndirectCalls(F, IndirCalls); 301 InjectTraceForCmp(F, CmpTraceTargets); 302 return true; 303 } 304 305 bool SanitizerCoverageModule::InjectCoverage(Function &F, 306 ArrayRef<BasicBlock *> AllBlocks) { 307 switch (Options.CoverageType) { 308 case SanitizerCoverageOptions::SCK_None: 309 return false; 310 case SanitizerCoverageOptions::SCK_Function: 311 InjectCoverageAtBlock(F, F.getEntryBlock(), false); 312 return true; 313 default: { 314 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size(); 315 for (auto BB : AllBlocks) 316 InjectCoverageAtBlock(F, *BB, UseCalls); 317 return true; 318 } 319 } 320 } 321 322 // On every indirect call we call a run-time function 323 // __sanitizer_cov_indir_call* with two parameters: 324 // - callee address, 325 // - global cache array that contains kCacheSize pointers (zero-initialized). 326 // The cache is used to speed up recording the caller-callee pairs. 327 // The address of the caller is passed implicitly via caller PC. 328 // kCacheSize is encoded in the name of the run-time function. 329 void SanitizerCoverageModule::InjectCoverageForIndirectCalls( 330 Function &F, ArrayRef<Instruction *> IndirCalls) { 331 if (IndirCalls.empty()) return; 332 const int kCacheSize = 16; 333 const int kCacheAlignment = 64; // Align for better performance. 334 Type *Ty = ArrayType::get(IntptrTy, kCacheSize); 335 for (auto I : IndirCalls) { 336 IRBuilder<> IRB(I); 337 CallSite CS(I); 338 Value *Callee = CS.getCalledValue(); 339 if (isa<InlineAsm>(Callee)) continue; 340 GlobalVariable *CalleeCache = new GlobalVariable( 341 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage, 342 Constant::getNullValue(Ty), "__sancov_gen_callee_cache"); 343 CalleeCache->setAlignment(kCacheAlignment); 344 IRB.CreateCall(SanCovIndirCallFunction, 345 {IRB.CreatePointerCast(Callee, IntptrTy), 346 IRB.CreatePointerCast(CalleeCache, IntptrTy)}); 347 } 348 } 349 350 void SanitizerCoverageModule::InjectTraceForCmp( 351 Function &F, ArrayRef<Instruction *> CmpTraceTargets) { 352 for (auto I : CmpTraceTargets) { 353 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) { 354 IRBuilder<> IRB(ICMP); 355 Value *A0 = ICMP->getOperand(0); 356 Value *A1 = ICMP->getOperand(1); 357 if (!A0->getType()->isIntegerTy()) continue; 358 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType()); 359 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1); 360 IRB.CreateCall( 361 SanCovTraceCmpFunction, 362 {ConstantInt::get(Int64Ty, (TypeSize << 32) | ICMP->getPredicate()), 363 IRB.CreateIntCast(A0, Int64Ty, true), 364 IRB.CreateIntCast(A1, Int64Ty, true)}); 365 } 366 } 367 } 368 369 void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) { 370 I->setMetadata( 371 I->getParent()->getParent()->getParent()->getMDKindID("nosanitize"), 372 MDNode::get(*C, None)); 373 } 374 375 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB, 376 bool UseCalls) { 377 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end(); 378 // Skip static allocas at the top of the entry block so they don't become 379 // dynamic when we split the block. If we used our optimized stack layout, 380 // then there will only be one alloca and it will come first. 381 for (; IP != BE; ++IP) { 382 AllocaInst *AI = dyn_cast<AllocaInst>(IP); 383 if (!AI || !AI->isStaticAlloca()) 384 break; 385 } 386 387 bool IsEntryBB = &BB == &F.getEntryBlock(); 388 DebugLoc EntryLoc = IsEntryBB && IP->getDebugLoc() 389 ? IP->getDebugLoc().getFnDebugLoc() 390 : IP->getDebugLoc(); 391 IRBuilder<> IRB(IP); 392 IRB.SetCurrentDebugLocation(EntryLoc); 393 SmallVector<Value *, 1> Indices; 394 Value *GuardP = IRB.CreateAdd( 395 IRB.CreatePointerCast(GuardArray, IntptrTy), 396 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4)); 397 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty()); 398 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy); 399 if (UseCalls) { 400 IRB.CreateCall(SanCovWithCheckFunction, GuardP); 401 } else { 402 LoadInst *Load = IRB.CreateLoad(GuardP); 403 Load->setAtomic(Monotonic); 404 Load->setAlignment(4); 405 SetNoSanitizeMetadata(Load); 406 Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load); 407 Instruction *Ins = SplitBlockAndInsertIfThen( 408 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000)); 409 IRB.SetInsertPoint(Ins); 410 IRB.SetCurrentDebugLocation(EntryLoc); 411 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC. 412 IRB.CreateCall(SanCovFunction, GuardP); 413 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge. 414 } 415 416 if (Options.Use8bitCounters) { 417 IRB.SetInsertPoint(IP); 418 Value *P = IRB.CreateAdd( 419 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy), 420 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1)); 421 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy()); 422 LoadInst *LI = IRB.CreateLoad(P); 423 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1)); 424 StoreInst *SI = IRB.CreateStore(Inc, P); 425 SetNoSanitizeMetadata(LI); 426 SetNoSanitizeMetadata(SI); 427 } 428 429 if (Options.TraceBB) { 430 // Experimental support for tracing. 431 // Insert a callback with the same guard variable as used for coverage. 432 IRB.SetInsertPoint(IP); 433 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP); 434 } 435 } 436 437 char SanitizerCoverageModule::ID = 0; 438 INITIALIZE_PASS(SanitizerCoverageModule, "sancov", 439 "SanitizerCoverage: TODO." 440 "ModulePass", false, false) 441 ModulePass *llvm::createSanitizerCoverageModulePass( 442 const SanitizerCoverageOptions &Options) { 443 return new SanitizerCoverageModule(Options); 444 } 445