1 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===// 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 // This file is a part of AddressSanitizer, an address sanity checker. 11 // Details of the algorithm: 12 // http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm 13 // 14 //===----------------------------------------------------------------------===// 15 16 #define DEBUG_TYPE "asan" 17 18 #include "FunctionBlackList.h" 19 #include "llvm/ADT/ArrayRef.h" 20 #include "llvm/ADT/OwningPtr.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/StringExtras.h" 25 #include "llvm/ADT/Triple.h" 26 #include "llvm/Function.h" 27 #include "llvm/IntrinsicInst.h" 28 #include "llvm/LLVMContext.h" 29 #include "llvm/Module.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/DataTypes.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/IRBuilder.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Support/system_error.h" 36 #include "llvm/Target/TargetData.h" 37 #include "llvm/Target/TargetMachine.h" 38 #include "llvm/Transforms/Instrumentation.h" 39 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 40 #include "llvm/Transforms/Utils/ModuleUtils.h" 41 #include "llvm/Type.h" 42 43 #include <string> 44 #include <algorithm> 45 46 using namespace llvm; 47 48 static const uint64_t kDefaultShadowScale = 3; 49 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29; 50 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44; 51 static const uint64_t kDefaultShadowOffsetAndroid = 0; 52 53 static const size_t kMaxStackMallocSize = 1 << 16; // 64K 54 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3; 55 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E; 56 57 static const char *kAsanModuleCtorName = "asan.module_ctor"; 58 static const char *kAsanModuleDtorName = "asan.module_dtor"; 59 static const int kAsanCtorAndCtorPriority = 1; 60 static const char *kAsanReportErrorTemplate = "__asan_report_"; 61 static const char *kAsanRegisterGlobalsName = "__asan_register_globals"; 62 static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals"; 63 static const char *kAsanInitName = "__asan_init"; 64 static const char *kAsanHandleNoReturnName = "__asan_handle_no_return"; 65 static const char *kAsanMappingOffsetName = "__asan_mapping_offset"; 66 static const char *kAsanMappingScaleName = "__asan_mapping_scale"; 67 static const char *kAsanStackMallocName = "__asan_stack_malloc"; 68 static const char *kAsanStackFreeName = "__asan_stack_free"; 69 70 static const int kAsanStackLeftRedzoneMagic = 0xf1; 71 static const int kAsanStackMidRedzoneMagic = 0xf2; 72 static const int kAsanStackRightRedzoneMagic = 0xf3; 73 static const int kAsanStackPartialRedzoneMagic = 0xf4; 74 75 // Command-line flags. 76 77 // This flag may need to be replaced with -f[no-]asan-reads. 78 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads", 79 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true)); 80 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes", 81 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true)); 82 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics", 83 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), 84 cl::Hidden, cl::init(true)); 85 // This flag may need to be replaced with -f[no]asan-stack. 86 static cl::opt<bool> ClStack("asan-stack", 87 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true)); 88 // This flag may need to be replaced with -f[no]asan-use-after-return. 89 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return", 90 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false)); 91 // This flag may need to be replaced with -f[no]asan-globals. 92 static cl::opt<bool> ClGlobals("asan-globals", 93 cl::desc("Handle global objects"), cl::Hidden, cl::init(true)); 94 static cl::opt<bool> ClMemIntrin("asan-memintrin", 95 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true)); 96 // This flag may need to be replaced with -fasan-blacklist. 97 static cl::opt<std::string> ClBlackListFile("asan-blacklist", 98 cl::desc("File containing the list of functions to ignore " 99 "during instrumentation"), cl::Hidden); 100 101 // These flags allow to change the shadow mapping. 102 // The shadow mapping looks like 103 // Shadow = (Mem >> scale) + (1 << offset_log) 104 static cl::opt<int> ClMappingScale("asan-mapping-scale", 105 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0)); 106 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log", 107 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1)); 108 109 // Optimization flags. Not user visible, used mostly for testing 110 // and benchmarking the tool. 111 static cl::opt<bool> ClOpt("asan-opt", 112 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true)); 113 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp", 114 cl::desc("Instrument the same temp just once"), cl::Hidden, 115 cl::init(true)); 116 static cl::opt<bool> ClOptGlobals("asan-opt-globals", 117 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true)); 118 119 // Debug flags. 120 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden, 121 cl::init(0)); 122 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"), 123 cl::Hidden, cl::init(0)); 124 static cl::opt<std::string> ClDebugFunc("asan-debug-func", 125 cl::Hidden, cl::desc("Debug func")); 126 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"), 127 cl::Hidden, cl::init(-1)); 128 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"), 129 cl::Hidden, cl::init(-1)); 130 131 namespace { 132 133 /// AddressSanitizer: instrument the code in module to find memory bugs. 134 struct AddressSanitizer : public ModulePass { 135 AddressSanitizer(); 136 virtual const char *getPassName() const; 137 void instrumentMop(Instruction *I); 138 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB, 139 Value *Addr, uint32_t TypeSize, bool IsWrite); 140 Instruction *generateCrashCode(IRBuilder<> &IRB, Value *Addr, 141 bool IsWrite, uint32_t TypeSize); 142 bool instrumentMemIntrinsic(MemIntrinsic *MI); 143 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr, 144 Value *Size, 145 Instruction *InsertBefore, bool IsWrite); 146 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB); 147 bool handleFunction(Module &M, Function &F); 148 bool maybeInsertAsanInitAtFunctionEntry(Function &F); 149 bool poisonStackInFunction(Module &M, Function &F); 150 virtual bool runOnModule(Module &M); 151 bool insertGlobalRedzones(Module &M); 152 BranchInst *splitBlockAndInsertIfThen(Instruction *SplitBefore, Value *Cmp); 153 static char ID; // Pass identification, replacement for typeid 154 155 private: 156 157 uint64_t getAllocaSizeInBytes(AllocaInst *AI) { 158 Type *Ty = AI->getAllocatedType(); 159 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty); 160 return SizeInBytes; 161 } 162 uint64_t getAlignedSize(uint64_t SizeInBytes) { 163 return ((SizeInBytes + RedzoneSize - 1) 164 / RedzoneSize) * RedzoneSize; 165 } 166 uint64_t getAlignedAllocaSize(AllocaInst *AI) { 167 uint64_t SizeInBytes = getAllocaSizeInBytes(AI); 168 return getAlignedSize(SizeInBytes); 169 } 170 171 Function *checkInterfaceFunction(Constant *FuncOrBitcast); 172 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, 173 Value *ShadowBase, bool DoPoison); 174 bool LooksLikeCodeInBug11395(Instruction *I); 175 176 Module *CurrentModule; 177 LLVMContext *C; 178 TargetData *TD; 179 uint64_t MappingOffset; 180 int MappingScale; 181 size_t RedzoneSize; 182 int LongSize; 183 Type *IntptrTy; 184 Type *IntptrPtrTy; 185 Function *AsanCtorFunction; 186 Function *AsanInitFunction; 187 Instruction *CtorInsertBefore; 188 OwningPtr<FunctionBlackList> BL; 189 }; 190 } // namespace 191 192 char AddressSanitizer::ID = 0; 193 INITIALIZE_PASS(AddressSanitizer, "asan", 194 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", 195 false, false) 196 AddressSanitizer::AddressSanitizer() : ModulePass(ID) { } 197 ModulePass *llvm::createAddressSanitizerPass() { 198 return new AddressSanitizer(); 199 } 200 201 const char *AddressSanitizer::getPassName() const { 202 return "AddressSanitizer"; 203 } 204 205 // Create a constant for Str so that we can pass it to the run-time lib. 206 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) { 207 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str); 208 return new GlobalVariable(M, StrConst->getType(), true, 209 GlobalValue::PrivateLinkage, StrConst, ""); 210 } 211 212 // Split the basic block and insert an if-then code. 213 // Before: 214 // Head 215 // SplitBefore 216 // Tail 217 // After: 218 // Head 219 // if (Cmp) 220 // NewBasicBlock 221 // SplitBefore 222 // Tail 223 // 224 // Returns the NewBasicBlock's terminator. 225 BranchInst *AddressSanitizer::splitBlockAndInsertIfThen( 226 Instruction *SplitBefore, Value *Cmp) { 227 BasicBlock *Head = SplitBefore->getParent(); 228 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore); 229 TerminatorInst *HeadOldTerm = Head->getTerminator(); 230 BasicBlock *NewBasicBlock = 231 BasicBlock::Create(*C, "", Head->getParent()); 232 BranchInst *HeadNewTerm = BranchInst::Create(/*ifTrue*/NewBasicBlock, 233 /*ifFalse*/Tail, 234 Cmp); 235 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm); 236 237 BranchInst *CheckTerm = BranchInst::Create(Tail, NewBasicBlock); 238 return CheckTerm; 239 } 240 241 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) { 242 // Shadow >> scale 243 Shadow = IRB.CreateLShr(Shadow, MappingScale); 244 if (MappingOffset == 0) 245 return Shadow; 246 // (Shadow >> scale) | offset 247 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, 248 MappingOffset)); 249 } 250 251 void AddressSanitizer::instrumentMemIntrinsicParam(Instruction *OrigIns, 252 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) { 253 // Check the first byte. 254 { 255 IRBuilder<> IRB(InsertBefore); 256 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite); 257 } 258 // Check the last byte. 259 { 260 IRBuilder<> IRB(InsertBefore); 261 Value *SizeMinusOne = IRB.CreateSub( 262 Size, ConstantInt::get(Size->getType(), 1)); 263 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false); 264 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy); 265 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne); 266 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite); 267 } 268 } 269 270 // Instrument memset/memmove/memcpy 271 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) { 272 Value *Dst = MI->getDest(); 273 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI); 274 Value *Src = MemTran ? MemTran->getSource() : NULL; 275 Value *Length = MI->getLength(); 276 277 Constant *ConstLength = dyn_cast<Constant>(Length); 278 Instruction *InsertBefore = MI; 279 if (ConstLength) { 280 if (ConstLength->isNullValue()) return false; 281 } else { 282 // The size is not a constant so it could be zero -- check at run-time. 283 IRBuilder<> IRB(InsertBefore); 284 285 Value *Cmp = IRB.CreateICmpNE(Length, 286 Constant::getNullValue(Length->getType())); 287 InsertBefore = splitBlockAndInsertIfThen(InsertBefore, Cmp); 288 } 289 290 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true); 291 if (Src) 292 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false); 293 return true; 294 } 295 296 // If I is an interesting memory access, return the PointerOperand 297 // and set IsWrite. Otherwise return NULL. 298 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) { 299 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 300 if (!ClInstrumentReads) return NULL; 301 *IsWrite = false; 302 return LI->getPointerOperand(); 303 } 304 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 305 if (!ClInstrumentWrites) return NULL; 306 *IsWrite = true; 307 return SI->getPointerOperand(); 308 } 309 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { 310 if (!ClInstrumentAtomics) return NULL; 311 *IsWrite = true; 312 return RMW->getPointerOperand(); 313 } 314 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) { 315 if (!ClInstrumentAtomics) return NULL; 316 *IsWrite = true; 317 return XCHG->getPointerOperand(); 318 } 319 return NULL; 320 } 321 322 void AddressSanitizer::instrumentMop(Instruction *I) { 323 bool IsWrite; 324 Value *Addr = isInterestingMemoryAccess(I, &IsWrite); 325 assert(Addr); 326 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) { 327 // We are accessing a global scalar variable. Nothing to catch here. 328 return; 329 } 330 Type *OrigPtrTy = Addr->getType(); 331 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType(); 332 333 assert(OrigTy->isSized()); 334 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy); 335 336 if (TypeSize != 8 && TypeSize != 16 && 337 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) { 338 // Ignore all unusual sizes. 339 return; 340 } 341 342 IRBuilder<> IRB(I); 343 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite); 344 } 345 346 // Validate the result of Module::getOrInsertFunction called for an interface 347 // function of AddressSanitizer. If the instrumented module defines a function 348 // with the same name, their prototypes must match, otherwise 349 // getOrInsertFunction returns a bitcast. 350 Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) { 351 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast); 352 FuncOrBitcast->dump(); 353 report_fatal_error("trying to redefine an AddressSanitizer " 354 "interface function"); 355 } 356 357 Instruction *AddressSanitizer::generateCrashCode( 358 IRBuilder<> &IRB, Value *Addr, bool IsWrite, uint32_t TypeSize) { 359 // IsWrite and TypeSize are encoded in the function name. 360 std::string FunctionName = std::string(kAsanReportErrorTemplate) + 361 (IsWrite ? "store" : "load") + itostr(TypeSize / 8); 362 Value *ReportWarningFunc = CurrentModule->getOrInsertFunction( 363 FunctionName, IRB.getVoidTy(), IntptrTy, NULL); 364 CallInst *Call = IRB.CreateCall(ReportWarningFunc, Addr); 365 Call->setDoesNotReturn(); 366 return Call; 367 } 368 369 void AddressSanitizer::instrumentAddress(Instruction *OrigIns, 370 IRBuilder<> &IRB, Value *Addr, 371 uint32_t TypeSize, bool IsWrite) { 372 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy); 373 374 Type *ShadowTy = IntegerType::get( 375 *C, std::max(8U, TypeSize >> MappingScale)); 376 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0); 377 Value *ShadowPtr = memToShadow(AddrLong, IRB); 378 Value *CmpVal = Constant::getNullValue(ShadowTy); 379 Value *ShadowValue = IRB.CreateLoad( 380 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy)); 381 382 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal); 383 384 Instruction *CheckTerm = splitBlockAndInsertIfThen( 385 cast<Instruction>(Cmp)->getNextNode(), Cmp); 386 IRBuilder<> IRB2(CheckTerm); 387 388 size_t Granularity = 1 << MappingScale; 389 if (TypeSize < 8 * Granularity) { 390 // Addr & (Granularity - 1) 391 Value *LastAccessedByte = IRB2.CreateAnd( 392 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1)); 393 // (Addr & (Granularity - 1)) + size - 1 394 if (TypeSize / 8 > 1) 395 LastAccessedByte = IRB2.CreateAdd( 396 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)); 397 // (uint8_t) ((Addr & (Granularity-1)) + size - 1) 398 LastAccessedByte = IRB2.CreateIntCast( 399 LastAccessedByte, IRB.getInt8Ty(), false); 400 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue 401 Value *Cmp2 = IRB2.CreateICmpSGE(LastAccessedByte, ShadowValue); 402 403 CheckTerm = splitBlockAndInsertIfThen(CheckTerm, Cmp2); 404 } 405 406 IRBuilder<> IRB1(CheckTerm); 407 Instruction *Crash = generateCrashCode(IRB1, AddrLong, IsWrite, TypeSize); 408 Crash->setDebugLoc(OrigIns->getDebugLoc()); 409 ReplaceInstWithInst(CheckTerm, new UnreachableInst(*C)); 410 } 411 412 // This function replaces all global variables with new variables that have 413 // trailing redzones. It also creates a function that poisons 414 // redzones and inserts this function into llvm.global_ctors. 415 bool AddressSanitizer::insertGlobalRedzones(Module &M) { 416 SmallVector<GlobalVariable *, 16> GlobalsToChange; 417 418 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(), 419 E = M.getGlobalList().end(); G != E; ++G) { 420 Type *Ty = cast<PointerType>(G->getType())->getElementType(); 421 DEBUG(dbgs() << "GLOBAL: " << *G); 422 423 if (!Ty->isSized()) continue; 424 if (!G->hasInitializer()) continue; 425 // Touch only those globals that will not be defined in other modules. 426 // Don't handle ODR type linkages since other modules may be built w/o asan. 427 if (G->getLinkage() != GlobalVariable::ExternalLinkage && 428 G->getLinkage() != GlobalVariable::PrivateLinkage && 429 G->getLinkage() != GlobalVariable::InternalLinkage) 430 continue; 431 // Two problems with thread-locals: 432 // - The address of the main thread's copy can't be computed at link-time. 433 // - Need to poison all copies, not just the main thread's one. 434 if (G->isThreadLocal()) 435 continue; 436 // For now, just ignore this Alloca if the alignment is large. 437 if (G->getAlignment() > RedzoneSize) continue; 438 439 // Ignore all the globals with the names starting with "\01L_OBJC_". 440 // Many of those are put into the .cstring section. The linker compresses 441 // that section by removing the spare \0s after the string terminator, so 442 // our redzones get broken. 443 if ((G->getName().find("\01L_OBJC_") == 0) || 444 (G->getName().find("\01l_OBJC_") == 0)) { 445 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G); 446 continue; 447 } 448 449 if (G->hasSection()) { 450 StringRef Section(G->getSection()); 451 // Ignore the globals from the __OBJC section. The ObjC runtime assumes 452 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to 453 // them. 454 if ((Section.find("__OBJC,") == 0) || 455 (Section.find("__DATA, __objc_") == 0)) { 456 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G); 457 continue; 458 } 459 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32 460 // Constant CFString instances are compiled in the following way: 461 // -- the string buffer is emitted into 462 // __TEXT,__cstring,cstring_literals 463 // -- the constant NSConstantString structure referencing that buffer 464 // is placed into __DATA,__cfstring 465 // Therefore there's no point in placing redzones into __DATA,__cfstring. 466 // Moreover, it causes the linker to crash on OS X 10.7 467 if (Section.find("__DATA,__cfstring") == 0) { 468 DEBUG(dbgs() << "Ignoring CFString: " << *G); 469 continue; 470 } 471 } 472 473 GlobalsToChange.push_back(G); 474 } 475 476 size_t n = GlobalsToChange.size(); 477 if (n == 0) return false; 478 479 // A global is described by a structure 480 // size_t beg; 481 // size_t size; 482 // size_t size_with_redzone; 483 // const char *name; 484 // We initialize an array of such structures and pass it to a run-time call. 485 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy, 486 IntptrTy, IntptrTy, NULL); 487 SmallVector<Constant *, 16> Initializers(n); 488 489 IRBuilder<> IRB(CtorInsertBefore); 490 491 for (size_t i = 0; i < n; i++) { 492 GlobalVariable *G = GlobalsToChange[i]; 493 PointerType *PtrTy = cast<PointerType>(G->getType()); 494 Type *Ty = PtrTy->getElementType(); 495 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty); 496 uint64_t RightRedzoneSize = RedzoneSize + 497 (RedzoneSize - (SizeInBytes % RedzoneSize)); 498 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize); 499 500 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL); 501 Constant *NewInitializer = ConstantStruct::get( 502 NewTy, G->getInitializer(), 503 Constant::getNullValue(RightRedZoneTy), NULL); 504 505 SmallString<2048> DescriptionOfGlobal = G->getName(); 506 DescriptionOfGlobal += " ("; 507 DescriptionOfGlobal += M.getModuleIdentifier(); 508 DescriptionOfGlobal += ")"; 509 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal); 510 511 // Create a new global variable with enough space for a redzone. 512 GlobalVariable *NewGlobal = new GlobalVariable( 513 M, NewTy, G->isConstant(), G->getLinkage(), 514 NewInitializer, "", G, G->isThreadLocal()); 515 NewGlobal->copyAttributesFrom(G); 516 NewGlobal->setAlignment(RedzoneSize); 517 518 Value *Indices2[2]; 519 Indices2[0] = IRB.getInt32(0); 520 Indices2[1] = IRB.getInt32(0); 521 522 G->replaceAllUsesWith( 523 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true)); 524 NewGlobal->takeName(G); 525 G->eraseFromParent(); 526 527 Initializers[i] = ConstantStruct::get( 528 GlobalStructTy, 529 ConstantExpr::getPointerCast(NewGlobal, IntptrTy), 530 ConstantInt::get(IntptrTy, SizeInBytes), 531 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize), 532 ConstantExpr::getPointerCast(Name, IntptrTy), 533 NULL); 534 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal); 535 } 536 537 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n); 538 GlobalVariable *AllGlobals = new GlobalVariable( 539 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage, 540 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), ""); 541 542 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction( 543 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL)); 544 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage); 545 546 IRB.CreateCall2(AsanRegisterGlobals, 547 IRB.CreatePointerCast(AllGlobals, IntptrTy), 548 ConstantInt::get(IntptrTy, n)); 549 550 // We also need to unregister globals at the end, e.g. when a shared library 551 // gets closed. 552 Function *AsanDtorFunction = Function::Create( 553 FunctionType::get(Type::getVoidTy(*C), false), 554 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M); 555 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction); 556 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB)); 557 Function *AsanUnregisterGlobals = 558 checkInterfaceFunction(M.getOrInsertFunction( 559 kAsanUnregisterGlobalsName, 560 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL)); 561 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage); 562 563 IRB_Dtor.CreateCall2(AsanUnregisterGlobals, 564 IRB.CreatePointerCast(AllGlobals, IntptrTy), 565 ConstantInt::get(IntptrTy, n)); 566 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority); 567 568 DEBUG(dbgs() << M); 569 return true; 570 } 571 572 // virtual 573 bool AddressSanitizer::runOnModule(Module &M) { 574 // Initialize the private fields. No one has accessed them before. 575 TD = getAnalysisIfAvailable<TargetData>(); 576 if (!TD) 577 return false; 578 BL.reset(new FunctionBlackList(ClBlackListFile)); 579 580 CurrentModule = &M; 581 C = &(M.getContext()); 582 LongSize = TD->getPointerSizeInBits(); 583 IntptrTy = Type::getIntNTy(*C, LongSize); 584 IntptrPtrTy = PointerType::get(IntptrTy, 0); 585 586 AsanCtorFunction = Function::Create( 587 FunctionType::get(Type::getVoidTy(*C), false), 588 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M); 589 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction); 590 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB); 591 592 // call __asan_init in the module ctor. 593 IRBuilder<> IRB(CtorInsertBefore); 594 AsanInitFunction = checkInterfaceFunction( 595 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL)); 596 AsanInitFunction->setLinkage(Function::ExternalLinkage); 597 IRB.CreateCall(AsanInitFunction); 598 599 llvm::Triple targetTriple(M.getTargetTriple()); 600 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI; 601 602 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid : 603 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64); 604 if (ClMappingOffsetLog >= 0) { 605 if (ClMappingOffsetLog == 0) { 606 // special case 607 MappingOffset = 0; 608 } else { 609 MappingOffset = 1ULL << ClMappingOffsetLog; 610 } 611 } 612 MappingScale = kDefaultShadowScale; 613 if (ClMappingScale) { 614 MappingScale = ClMappingScale; 615 } 616 // Redzone used for stack and globals is at least 32 bytes. 617 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively. 618 RedzoneSize = std::max(32, (int)(1 << MappingScale)); 619 620 bool Res = false; 621 622 if (ClGlobals) 623 Res |= insertGlobalRedzones(M); 624 625 if (ClMappingOffsetLog >= 0) { 626 // Tell the run-time the current values of mapping offset and scale. 627 GlobalValue *asan_mapping_offset = 628 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage, 629 ConstantInt::get(IntptrTy, MappingOffset), 630 kAsanMappingOffsetName); 631 // Read the global, otherwise it may be optimized away. 632 IRB.CreateLoad(asan_mapping_offset, true); 633 } 634 if (ClMappingScale) { 635 GlobalValue *asan_mapping_scale = 636 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage, 637 ConstantInt::get(IntptrTy, MappingScale), 638 kAsanMappingScaleName); 639 // Read the global, otherwise it may be optimized away. 640 IRB.CreateLoad(asan_mapping_scale, true); 641 } 642 643 644 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) { 645 if (F->isDeclaration()) continue; 646 Res |= handleFunction(M, *F); 647 } 648 649 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority); 650 651 return Res; 652 } 653 654 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) { 655 // For each NSObject descendant having a +load method, this method is invoked 656 // by the ObjC runtime before any of the static constructors is called. 657 // Therefore we need to instrument such methods with a call to __asan_init 658 // at the beginning in order to initialize our runtime before any access to 659 // the shadow memory. 660 // We cannot just ignore these methods, because they may call other 661 // instrumented functions. 662 if (F.getName().find(" load]") != std::string::npos) { 663 IRBuilder<> IRB(F.begin()->begin()); 664 IRB.CreateCall(AsanInitFunction); 665 return true; 666 } 667 return false; 668 } 669 670 bool AddressSanitizer::handleFunction(Module &M, Function &F) { 671 if (BL->isIn(F)) return false; 672 if (&F == AsanCtorFunction) return false; 673 674 // If needed, insert __asan_init before checking for AddressSafety attr. 675 maybeInsertAsanInitAtFunctionEntry(F); 676 677 if (!F.hasFnAttr(Attribute::AddressSafety)) return false; 678 679 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) 680 return false; 681 // We want to instrument every address only once per basic block 682 // (unless there are calls between uses). 683 SmallSet<Value*, 16> TempsToInstrument; 684 SmallVector<Instruction*, 16> ToInstrument; 685 SmallVector<Instruction*, 8> NoReturnCalls; 686 bool IsWrite; 687 688 // Fill the set of memory operations to instrument. 689 for (Function::iterator FI = F.begin(), FE = F.end(); 690 FI != FE; ++FI) { 691 TempsToInstrument.clear(); 692 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); 693 BI != BE; ++BI) { 694 if (LooksLikeCodeInBug11395(BI)) return false; 695 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) { 696 if (ClOpt && ClOptSameTemp) { 697 if (!TempsToInstrument.insert(Addr)) 698 continue; // We've seen this temp in the current BB. 699 } 700 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) { 701 // ok, take it. 702 } else { 703 if (CallInst *CI = dyn_cast<CallInst>(BI)) { 704 // A call inside BB. 705 TempsToInstrument.clear(); 706 if (CI->doesNotReturn()) { 707 NoReturnCalls.push_back(CI); 708 } 709 } 710 continue; 711 } 712 ToInstrument.push_back(BI); 713 } 714 } 715 716 // Instrument. 717 int NumInstrumented = 0; 718 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) { 719 Instruction *Inst = ToInstrument[i]; 720 if (ClDebugMin < 0 || ClDebugMax < 0 || 721 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) { 722 if (isInterestingMemoryAccess(Inst, &IsWrite)) 723 instrumentMop(Inst); 724 else 725 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst)); 726 } 727 NumInstrumented++; 728 } 729 730 DEBUG(dbgs() << F); 731 732 bool ChangedStack = poisonStackInFunction(M, F); 733 734 // We must unpoison the stack before every NoReturn call (throw, _exit, etc). 735 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37 736 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) { 737 Instruction *CI = NoReturnCalls[i]; 738 IRBuilder<> IRB(CI); 739 IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName, 740 IRB.getVoidTy(), NULL)); 741 } 742 743 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty(); 744 } 745 746 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) { 747 if (ShadowRedzoneSize == 1) return PoisonByte; 748 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte; 749 if (ShadowRedzoneSize == 4) 750 return (PoisonByte << 24) + (PoisonByte << 16) + 751 (PoisonByte << 8) + (PoisonByte); 752 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4"); 753 } 754 755 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow, 756 size_t Size, 757 size_t RedzoneSize, 758 size_t ShadowGranularity, 759 uint8_t Magic) { 760 for (size_t i = 0; i < RedzoneSize; 761 i+= ShadowGranularity, Shadow++) { 762 if (i + ShadowGranularity <= Size) { 763 *Shadow = 0; // fully addressable 764 } else if (i >= Size) { 765 *Shadow = Magic; // unaddressable 766 } else { 767 *Shadow = Size - i; // first Size-i bytes are addressable 768 } 769 } 770 } 771 772 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, 773 IRBuilder<> IRB, 774 Value *ShadowBase, bool DoPoison) { 775 size_t ShadowRZSize = RedzoneSize >> MappingScale; 776 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4); 777 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8); 778 Type *RZPtrTy = PointerType::get(RZTy, 0); 779 780 Value *PoisonLeft = ConstantInt::get(RZTy, 781 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize)); 782 Value *PoisonMid = ConstantInt::get(RZTy, 783 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize)); 784 Value *PoisonRight = ConstantInt::get(RZTy, 785 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize)); 786 787 // poison the first red zone. 788 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy)); 789 790 // poison all other red zones. 791 uint64_t Pos = RedzoneSize; 792 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) { 793 AllocaInst *AI = AllocaVec[i]; 794 uint64_t SizeInBytes = getAllocaSizeInBytes(AI); 795 uint64_t AlignedSize = getAlignedAllocaSize(AI); 796 assert(AlignedSize - SizeInBytes < RedzoneSize); 797 Value *Ptr = NULL; 798 799 Pos += AlignedSize; 800 801 assert(ShadowBase->getType() == IntptrTy); 802 if (SizeInBytes < AlignedSize) { 803 // Poison the partial redzone at right 804 Ptr = IRB.CreateAdd( 805 ShadowBase, ConstantInt::get(IntptrTy, 806 (Pos >> MappingScale) - ShadowRZSize)); 807 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes); 808 uint32_t Poison = 0; 809 if (DoPoison) { 810 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes, 811 RedzoneSize, 812 1ULL << MappingScale, 813 kAsanStackPartialRedzoneMagic); 814 } 815 Value *PartialPoison = ConstantInt::get(RZTy, Poison); 816 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy)); 817 } 818 819 // Poison the full redzone at right. 820 Ptr = IRB.CreateAdd(ShadowBase, 821 ConstantInt::get(IntptrTy, Pos >> MappingScale)); 822 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid; 823 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy)); 824 825 Pos += RedzoneSize; 826 } 827 } 828 829 // Workaround for bug 11395: we don't want to instrument stack in functions 830 // with large assembly blobs (32-bit only), otherwise reg alloc may crash. 831 // FIXME: remove once the bug 11395 is fixed. 832 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) { 833 if (LongSize != 32) return false; 834 CallInst *CI = dyn_cast<CallInst>(I); 835 if (!CI || !CI->isInlineAsm()) return false; 836 if (CI->getNumArgOperands() <= 5) return false; 837 // We have inline assembly with quite a few arguments. 838 return true; 839 } 840 841 // Find all static Alloca instructions and put 842 // poisoned red zones around all of them. 843 // Then unpoison everything back before the function returns. 844 // 845 // Stack poisoning does not play well with exception handling. 846 // When an exception is thrown, we essentially bypass the code 847 // that unpoisones the stack. This is why the run-time library has 848 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire 849 // stack in the interceptor. This however does not work inside the 850 // actual function which catches the exception. Most likely because the 851 // compiler hoists the load of the shadow value somewhere too high. 852 // This causes asan to report a non-existing bug on 453.povray. 853 // It sounds like an LLVM bug. 854 bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) { 855 if (!ClStack) return false; 856 SmallVector<AllocaInst*, 16> AllocaVec; 857 SmallVector<Instruction*, 8> RetVec; 858 uint64_t TotalSize = 0; 859 860 // Filter out Alloca instructions we want (and can) handle. 861 // Collect Ret instructions. 862 for (Function::iterator FI = F.begin(), FE = F.end(); 863 FI != FE; ++FI) { 864 BasicBlock &BB = *FI; 865 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); 866 BI != BE; ++BI) { 867 if (isa<ReturnInst>(BI)) { 868 RetVec.push_back(BI); 869 continue; 870 } 871 872 AllocaInst *AI = dyn_cast<AllocaInst>(BI); 873 if (!AI) continue; 874 if (AI->isArrayAllocation()) continue; 875 if (!AI->isStaticAlloca()) continue; 876 if (!AI->getAllocatedType()->isSized()) continue; 877 if (AI->getAlignment() > RedzoneSize) continue; 878 AllocaVec.push_back(AI); 879 uint64_t AlignedSize = getAlignedAllocaSize(AI); 880 TotalSize += AlignedSize; 881 } 882 } 883 884 if (AllocaVec.empty()) return false; 885 886 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize; 887 888 bool DoStackMalloc = ClUseAfterReturn 889 && LocalStackSize <= kMaxStackMallocSize; 890 891 Instruction *InsBefore = AllocaVec[0]; 892 IRBuilder<> IRB(InsBefore); 893 894 895 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize); 896 AllocaInst *MyAlloca = 897 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore); 898 MyAlloca->setAlignment(RedzoneSize); 899 assert(MyAlloca->isStaticAlloca()); 900 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy); 901 Value *LocalStackBase = OrigStackBase; 902 903 if (DoStackMalloc) { 904 Value *AsanStackMallocFunc = M.getOrInsertFunction( 905 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL); 906 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc, 907 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase); 908 } 909 910 // This string will be parsed by the run-time (DescribeStackAddress). 911 SmallString<2048> StackDescriptionStorage; 912 raw_svector_ostream StackDescription(StackDescriptionStorage); 913 StackDescription << F.getName() << " " << AllocaVec.size() << " "; 914 915 uint64_t Pos = RedzoneSize; 916 // Replace Alloca instructions with base+offset. 917 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) { 918 AllocaInst *AI = AllocaVec[i]; 919 uint64_t SizeInBytes = getAllocaSizeInBytes(AI); 920 StringRef Name = AI->getName(); 921 StackDescription << Pos << " " << SizeInBytes << " " 922 << Name.size() << " " << Name << " "; 923 uint64_t AlignedSize = getAlignedAllocaSize(AI); 924 assert((AlignedSize % RedzoneSize) == 0); 925 AI->replaceAllUsesWith( 926 IRB.CreateIntToPtr( 927 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)), 928 AI->getType())); 929 Pos += AlignedSize + RedzoneSize; 930 } 931 assert(Pos == LocalStackSize); 932 933 // Write the Magic value and the frame description constant to the redzone. 934 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy); 935 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic), 936 BasePlus0); 937 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase, 938 ConstantInt::get(IntptrTy, LongSize/8)); 939 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy); 940 Value *Description = IRB.CreatePointerCast( 941 createPrivateGlobalForString(M, StackDescription.str()), 942 IntptrTy); 943 IRB.CreateStore(Description, BasePlus1); 944 945 // Poison the stack redzones at the entry. 946 Value *ShadowBase = memToShadow(LocalStackBase, IRB); 947 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true); 948 949 Value *AsanStackFreeFunc = NULL; 950 if (DoStackMalloc) { 951 AsanStackFreeFunc = M.getOrInsertFunction( 952 kAsanStackFreeName, IRB.getVoidTy(), 953 IntptrTy, IntptrTy, IntptrTy, NULL); 954 } 955 956 // Unpoison the stack before all ret instructions. 957 for (size_t i = 0, n = RetVec.size(); i < n; i++) { 958 Instruction *Ret = RetVec[i]; 959 IRBuilder<> IRBRet(Ret); 960 961 // Mark the current frame as retired. 962 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic), 963 BasePlus0); 964 // Unpoison the stack. 965 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false); 966 967 if (DoStackMalloc) { 968 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase, 969 ConstantInt::get(IntptrTy, LocalStackSize), 970 OrigStackBase); 971 } 972 } 973 974 if (ClDebugStack) { 975 DEBUG(dbgs() << F); 976 } 977 978 return true; 979 } 980