1 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asan"
18 #include "FunctionBlackList.h"
19 #include "llvm/Function.h"
20 #include "llvm/IRBuilder.h"
21 #include "llvm/InlineAsm.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/Type.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/OwningPtr.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/Triple.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/DataTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Support/system_error.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Transforms/Instrumentation.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/Transforms/Utils/ModuleUtils.h"
49 static const uint64_t kDefaultShadowScale = 3;
50 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
51 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
52 static const uint64_t kDefaultShadowOffsetAndroid = 0;
54 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
55 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
56 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
58 static const char *kAsanModuleCtorName = "asan.module_ctor";
59 static const char *kAsanModuleDtorName = "asan.module_dtor";
60 static const int kAsanCtorAndCtorPriority = 1;
61 static const char *kAsanReportErrorTemplate = "__asan_report_";
62 static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
63 static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
64 static const char *kAsanInitName = "__asan_init";
65 static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
66 static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
67 static const char *kAsanMappingScaleName = "__asan_mapping_scale";
68 static const char *kAsanStackMallocName = "__asan_stack_malloc";
69 static const char *kAsanStackFreeName = "__asan_stack_free";
71 static const int kAsanStackLeftRedzoneMagic = 0xf1;
72 static const int kAsanStackMidRedzoneMagic = 0xf2;
73 static const int kAsanStackRightRedzoneMagic = 0xf3;
74 static const int kAsanStackPartialRedzoneMagic = 0xf4;
76 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
77 static const size_t kNumberOfAccessSizes = 5;
79 // Command-line flags.
81 // This flag may need to be replaced with -f[no-]asan-reads.
82 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
83 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
84 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
85 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
86 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
87 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
88 cl::Hidden, cl::init(true));
89 // This flag limits the number of instructions to be instrumented
90 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
91 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
93 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
95 cl::desc("maximal number of instructions to instrument in any given BB"),
97 // This flag may need to be replaced with -f[no]asan-stack.
98 static cl::opt<bool> ClStack("asan-stack",
99 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
100 // This flag may need to be replaced with -f[no]asan-use-after-return.
101 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
102 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
103 // This flag may need to be replaced with -f[no]asan-globals.
104 static cl::opt<bool> ClGlobals("asan-globals",
105 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
106 static cl::opt<bool> ClMemIntrin("asan-memintrin",
107 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
108 // This flag may need to be replaced with -fasan-blacklist.
109 static cl::opt<std::string> ClBlackListFile("asan-blacklist",
110 cl::desc("File containing the list of functions to ignore "
111 "during instrumentation"), cl::Hidden);
113 // These flags allow to change the shadow mapping.
114 // The shadow mapping looks like
115 // Shadow = (Mem >> scale) + (1 << offset_log)
116 static cl::opt<int> ClMappingScale("asan-mapping-scale",
117 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
118 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
119 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
121 // Optimization flags. Not user visible, used mostly for testing
122 // and benchmarking the tool.
123 static cl::opt<bool> ClOpt("asan-opt",
124 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
125 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
126 cl::desc("Instrument the same temp just once"), cl::Hidden,
128 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
129 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
132 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
134 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
135 cl::Hidden, cl::init(0));
136 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
137 cl::Hidden, cl::desc("Debug func"));
138 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
139 cl::Hidden, cl::init(-1));
140 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
141 cl::Hidden, cl::init(-1));
145 /// An object of this type is created while instrumenting every function.
146 struct AsanFunctionContext {
147 AsanFunctionContext(Function &Function) : F(Function) { }
152 /// AddressSanitizer: instrument the code in module to find memory bugs.
153 struct AddressSanitizer : public ModulePass {
155 virtual const char *getPassName() const;
156 void instrumentMop(AsanFunctionContext &AFC, Instruction *I);
157 void instrumentAddress(AsanFunctionContext &AFC,
158 Instruction *OrigIns, IRBuilder<> &IRB,
159 Value *Addr, uint32_t TypeSize, bool IsWrite);
160 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
161 Value *ShadowValue, uint32_t TypeSize);
162 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
163 bool IsWrite, size_t AccessSizeIndex);
164 bool instrumentMemIntrinsic(AsanFunctionContext &AFC, MemIntrinsic *MI);
165 void instrumentMemIntrinsicParam(AsanFunctionContext &AFC,
166 Instruction *OrigIns, Value *Addr,
168 Instruction *InsertBefore, bool IsWrite);
169 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
170 bool handleFunction(Module &M, Function &F);
171 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
172 bool poisonStackInFunction(Module &M, Function &F);
173 virtual bool runOnModule(Module &M);
174 bool insertGlobalRedzones(Module &M);
175 static char ID; // Pass identification, replacement for typeid
179 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
180 Type *Ty = AI->getAllocatedType();
181 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
184 uint64_t getAlignedSize(uint64_t SizeInBytes) {
185 return ((SizeInBytes + RedzoneSize - 1)
186 / RedzoneSize) * RedzoneSize;
188 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
189 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
190 return getAlignedSize(SizeInBytes);
193 Function *checkInterfaceFunction(Constant *FuncOrBitcast);
194 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
195 Value *ShadowBase, bool DoPoison);
196 bool LooksLikeCodeInBug11395(Instruction *I);
200 uint64_t MappingOffset;
206 Function *AsanCtorFunction;
207 Function *AsanInitFunction;
208 Instruction *CtorInsertBefore;
209 OwningPtr<FunctionBlackList> BL;
210 // This array is indexed by AccessIsWrite and log2(AccessSize).
211 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
217 char AddressSanitizer::ID = 0;
218 INITIALIZE_PASS(AddressSanitizer, "asan",
219 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
221 AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
222 ModulePass *llvm::createAddressSanitizerPass() {
223 return new AddressSanitizer();
226 const char *AddressSanitizer::getPassName() const {
227 return "AddressSanitizer";
230 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
231 size_t Res = CountTrailingZeros_32(TypeSize / 8);
232 assert(Res < kNumberOfAccessSizes);
236 // Create a constant for Str so that we can pass it to the run-time lib.
237 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
238 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
239 return new GlobalVariable(M, StrConst->getType(), true,
240 GlobalValue::PrivateLinkage, StrConst, "");
243 // Split the basic block and insert an if-then code.
254 // ThenBlock block is created and its terminator is returned.
255 // If Unreachable, ThenBlock is terminated with UnreachableInst, otherwise
256 // it is terminated with BranchInst to Tail.
257 static TerminatorInst *splitBlockAndInsertIfThen(Value *Cmp, bool Unreachable) {
258 Instruction *SplitBefore = cast<Instruction>(Cmp)->getNextNode();
259 BasicBlock *Head = SplitBefore->getParent();
260 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
261 TerminatorInst *HeadOldTerm = Head->getTerminator();
262 LLVMContext &C = Head->getParent()->getParent()->getContext();
263 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
264 TerminatorInst *CheckTerm;
266 CheckTerm = new UnreachableInst(C, ThenBlock);
268 CheckTerm = BranchInst::Create(Tail, ThenBlock);
269 BranchInst *HeadNewTerm =
270 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
271 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
275 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
277 Shadow = IRB.CreateLShr(Shadow, MappingScale);
278 if (MappingOffset == 0)
280 // (Shadow >> scale) | offset
281 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
285 void AddressSanitizer::instrumentMemIntrinsicParam(
286 AsanFunctionContext &AFC, Instruction *OrigIns,
287 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
288 // Check the first byte.
290 IRBuilder<> IRB(InsertBefore);
291 instrumentAddress(AFC, OrigIns, IRB, Addr, 8, IsWrite);
293 // Check the last byte.
295 IRBuilder<> IRB(InsertBefore);
296 Value *SizeMinusOne = IRB.CreateSub(
297 Size, ConstantInt::get(Size->getType(), 1));
298 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
299 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
300 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
301 instrumentAddress(AFC, OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
305 // Instrument memset/memmove/memcpy
306 bool AddressSanitizer::instrumentMemIntrinsic(AsanFunctionContext &AFC,
308 Value *Dst = MI->getDest();
309 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
310 Value *Src = MemTran ? MemTran->getSource() : 0;
311 Value *Length = MI->getLength();
313 Constant *ConstLength = dyn_cast<Constant>(Length);
314 Instruction *InsertBefore = MI;
316 if (ConstLength->isNullValue()) return false;
318 // The size is not a constant so it could be zero -- check at run-time.
319 IRBuilder<> IRB(InsertBefore);
321 Value *Cmp = IRB.CreateICmpNE(Length,
322 Constant::getNullValue(Length->getType()));
323 InsertBefore = splitBlockAndInsertIfThen(Cmp, false);
326 instrumentMemIntrinsicParam(AFC, MI, Dst, Length, InsertBefore, true);
328 instrumentMemIntrinsicParam(AFC, MI, Src, Length, InsertBefore, false);
332 // If I is an interesting memory access, return the PointerOperand
333 // and set IsWrite. Otherwise return NULL.
334 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
335 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
336 if (!ClInstrumentReads) return NULL;
338 return LI->getPointerOperand();
340 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
341 if (!ClInstrumentWrites) return NULL;
343 return SI->getPointerOperand();
345 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
346 if (!ClInstrumentAtomics) return NULL;
348 return RMW->getPointerOperand();
350 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
351 if (!ClInstrumentAtomics) return NULL;
353 return XCHG->getPointerOperand();
358 void AddressSanitizer::instrumentMop(AsanFunctionContext &AFC, Instruction *I) {
360 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
362 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
363 // We are accessing a global scalar variable. Nothing to catch here.
366 Type *OrigPtrTy = Addr->getType();
367 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
369 assert(OrigTy->isSized());
370 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
372 if (TypeSize != 8 && TypeSize != 16 &&
373 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
374 // Ignore all unusual sizes.
379 instrumentAddress(AFC, I, IRB, Addr, TypeSize, IsWrite);
382 // Validate the result of Module::getOrInsertFunction called for an interface
383 // function of AddressSanitizer. If the instrumented module defines a function
384 // with the same name, their prototypes must match, otherwise
385 // getOrInsertFunction returns a bitcast.
386 Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
387 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
388 FuncOrBitcast->dump();
389 report_fatal_error("trying to redefine an AddressSanitizer "
390 "interface function");
393 Instruction *AddressSanitizer::generateCrashCode(
394 Instruction *InsertBefore, Value *Addr,
395 bool IsWrite, size_t AccessSizeIndex) {
396 IRBuilder<> IRB(InsertBefore);
397 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
399 // We don't do Call->setDoesNotReturn() because the BB already has
400 // UnreachableInst at the end.
401 // This EmptyAsm is required to avoid callback merge.
402 IRB.CreateCall(EmptyAsm);
406 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
409 size_t Granularity = 1 << MappingScale;
410 // Addr & (Granularity - 1)
411 Value *LastAccessedByte = IRB.CreateAnd(
412 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
413 // (Addr & (Granularity - 1)) + size - 1
414 if (TypeSize / 8 > 1)
415 LastAccessedByte = IRB.CreateAdd(
416 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
417 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
418 LastAccessedByte = IRB.CreateIntCast(
419 LastAccessedByte, IRB.getInt8Ty(), false);
420 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
421 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
424 void AddressSanitizer::instrumentAddress(AsanFunctionContext &AFC,
425 Instruction *OrigIns,
426 IRBuilder<> &IRB, Value *Addr,
427 uint32_t TypeSize, bool IsWrite) {
428 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
430 Type *ShadowTy = IntegerType::get(
431 *C, std::max(8U, TypeSize >> MappingScale));
432 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
433 Value *ShadowPtr = memToShadow(AddrLong, IRB);
434 Value *CmpVal = Constant::getNullValue(ShadowTy);
435 Value *ShadowValue = IRB.CreateLoad(
436 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
438 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
439 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
440 size_t Granularity = 1 << MappingScale;
441 TerminatorInst *CrashTerm = 0;
443 if (TypeSize < 8 * Granularity) {
444 TerminatorInst *CheckTerm = splitBlockAndInsertIfThen(Cmp, false);
445 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
446 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
447 IRB.SetInsertPoint(CheckTerm);
448 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
449 BasicBlock *CrashBlock = BasicBlock::Create(*C, "", &AFC.F, NextBB);
450 CrashTerm = new UnreachableInst(*C, CrashBlock);
451 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
452 ReplaceInstWithInst(CheckTerm, NewTerm);
454 CrashTerm = splitBlockAndInsertIfThen(Cmp, true);
458 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
459 Crash->setDebugLoc(OrigIns->getDebugLoc());
462 // This function replaces all global variables with new variables that have
463 // trailing redzones. It also creates a function that poisons
464 // redzones and inserts this function into llvm.global_ctors.
465 bool AddressSanitizer::insertGlobalRedzones(Module &M) {
466 SmallVector<GlobalVariable *, 16> GlobalsToChange;
468 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
469 E = M.getGlobalList().end(); G != E; ++G) {
470 Type *Ty = cast<PointerType>(G->getType())->getElementType();
471 DEBUG(dbgs() << "GLOBAL: " << *G);
473 if (!Ty->isSized()) continue;
474 if (!G->hasInitializer()) continue;
475 // Touch only those globals that will not be defined in other modules.
476 // Don't handle ODR type linkages since other modules may be built w/o asan.
477 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
478 G->getLinkage() != GlobalVariable::PrivateLinkage &&
479 G->getLinkage() != GlobalVariable::InternalLinkage)
481 // Two problems with thread-locals:
482 // - The address of the main thread's copy can't be computed at link-time.
483 // - Need to poison all copies, not just the main thread's one.
484 if (G->isThreadLocal())
486 // For now, just ignore this Alloca if the alignment is large.
487 if (G->getAlignment() > RedzoneSize) continue;
489 // Ignore all the globals with the names starting with "\01L_OBJC_".
490 // Many of those are put into the .cstring section. The linker compresses
491 // that section by removing the spare \0s after the string terminator, so
492 // our redzones get broken.
493 if ((G->getName().find("\01L_OBJC_") == 0) ||
494 (G->getName().find("\01l_OBJC_") == 0)) {
495 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
499 if (G->hasSection()) {
500 StringRef Section(G->getSection());
501 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
502 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
504 if ((Section.find("__OBJC,") == 0) ||
505 (Section.find("__DATA, __objc_") == 0)) {
506 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
509 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
510 // Constant CFString instances are compiled in the following way:
511 // -- the string buffer is emitted into
512 // __TEXT,__cstring,cstring_literals
513 // -- the constant NSConstantString structure referencing that buffer
514 // is placed into __DATA,__cfstring
515 // Therefore there's no point in placing redzones into __DATA,__cfstring.
516 // Moreover, it causes the linker to crash on OS X 10.7
517 if (Section.find("__DATA,__cfstring") == 0) {
518 DEBUG(dbgs() << "Ignoring CFString: " << *G);
523 GlobalsToChange.push_back(G);
526 size_t n = GlobalsToChange.size();
527 if (n == 0) return false;
529 // A global is described by a structure
532 // size_t size_with_redzone;
534 // We initialize an array of such structures and pass it to a run-time call.
535 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
536 IntptrTy, IntptrTy, NULL);
537 SmallVector<Constant *, 16> Initializers(n);
539 IRBuilder<> IRB(CtorInsertBefore);
541 for (size_t i = 0; i < n; i++) {
542 GlobalVariable *G = GlobalsToChange[i];
543 PointerType *PtrTy = cast<PointerType>(G->getType());
544 Type *Ty = PtrTy->getElementType();
545 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
546 uint64_t RightRedzoneSize = RedzoneSize +
547 (RedzoneSize - (SizeInBytes % RedzoneSize));
548 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
550 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
551 Constant *NewInitializer = ConstantStruct::get(
552 NewTy, G->getInitializer(),
553 Constant::getNullValue(RightRedZoneTy), NULL);
555 SmallString<2048> DescriptionOfGlobal = G->getName();
556 DescriptionOfGlobal += " (";
557 DescriptionOfGlobal += M.getModuleIdentifier();
558 DescriptionOfGlobal += ")";
559 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
561 // Create a new global variable with enough space for a redzone.
562 GlobalVariable *NewGlobal = new GlobalVariable(
563 M, NewTy, G->isConstant(), G->getLinkage(),
564 NewInitializer, "", G, G->getThreadLocalMode());
565 NewGlobal->copyAttributesFrom(G);
566 NewGlobal->setAlignment(RedzoneSize);
569 Indices2[0] = IRB.getInt32(0);
570 Indices2[1] = IRB.getInt32(0);
572 G->replaceAllUsesWith(
573 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
574 NewGlobal->takeName(G);
575 G->eraseFromParent();
577 Initializers[i] = ConstantStruct::get(
579 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
580 ConstantInt::get(IntptrTy, SizeInBytes),
581 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
582 ConstantExpr::getPointerCast(Name, IntptrTy),
584 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
587 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
588 GlobalVariable *AllGlobals = new GlobalVariable(
589 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
590 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
592 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
593 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
594 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
596 IRB.CreateCall2(AsanRegisterGlobals,
597 IRB.CreatePointerCast(AllGlobals, IntptrTy),
598 ConstantInt::get(IntptrTy, n));
600 // We also need to unregister globals at the end, e.g. when a shared library
602 Function *AsanDtorFunction = Function::Create(
603 FunctionType::get(Type::getVoidTy(*C), false),
604 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
605 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
606 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
607 Function *AsanUnregisterGlobals =
608 checkInterfaceFunction(M.getOrInsertFunction(
609 kAsanUnregisterGlobalsName,
610 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
611 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
613 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
614 IRB.CreatePointerCast(AllGlobals, IntptrTy),
615 ConstantInt::get(IntptrTy, n));
616 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
623 bool AddressSanitizer::runOnModule(Module &M) {
624 // Initialize the private fields. No one has accessed them before.
625 TD = getAnalysisIfAvailable<TargetData>();
628 BL.reset(new FunctionBlackList(ClBlackListFile));
630 C = &(M.getContext());
631 LongSize = TD->getPointerSizeInBits();
632 IntptrTy = Type::getIntNTy(*C, LongSize);
633 IntptrPtrTy = PointerType::get(IntptrTy, 0);
635 AsanCtorFunction = Function::Create(
636 FunctionType::get(Type::getVoidTy(*C), false),
637 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
638 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
639 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
641 // call __asan_init in the module ctor.
642 IRBuilder<> IRB(CtorInsertBefore);
643 AsanInitFunction = checkInterfaceFunction(
644 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
645 AsanInitFunction->setLinkage(Function::ExternalLinkage);
646 IRB.CreateCall(AsanInitFunction);
648 // Create __asan_report* callbacks.
649 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
650 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
652 // IsWrite and TypeSize are encoded in the function name.
653 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
654 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
655 // If we are merging crash callbacks, they have two parameters.
656 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
657 M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
660 // We insert an empty inline asm after __asan_report* to avoid callback merge.
661 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
662 StringRef(""), StringRef(""),
663 /*hasSideEffects=*/true);
665 llvm::Triple targetTriple(M.getTargetTriple());
666 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
668 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
669 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
670 if (ClMappingOffsetLog >= 0) {
671 if (ClMappingOffsetLog == 0) {
675 MappingOffset = 1ULL << ClMappingOffsetLog;
678 MappingScale = kDefaultShadowScale;
679 if (ClMappingScale) {
680 MappingScale = ClMappingScale;
682 // Redzone used for stack and globals is at least 32 bytes.
683 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
684 RedzoneSize = std::max(32, (int)(1 << MappingScale));
689 Res |= insertGlobalRedzones(M);
691 if (ClMappingOffsetLog >= 0) {
692 // Tell the run-time the current values of mapping offset and scale.
693 GlobalValue *asan_mapping_offset =
694 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
695 ConstantInt::get(IntptrTy, MappingOffset),
696 kAsanMappingOffsetName);
697 // Read the global, otherwise it may be optimized away.
698 IRB.CreateLoad(asan_mapping_offset, true);
700 if (ClMappingScale) {
701 GlobalValue *asan_mapping_scale =
702 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
703 ConstantInt::get(IntptrTy, MappingScale),
704 kAsanMappingScaleName);
705 // Read the global, otherwise it may be optimized away.
706 IRB.CreateLoad(asan_mapping_scale, true);
710 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
711 if (F->isDeclaration()) continue;
712 Res |= handleFunction(M, *F);
715 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
720 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
721 // For each NSObject descendant having a +load method, this method is invoked
722 // by the ObjC runtime before any of the static constructors is called.
723 // Therefore we need to instrument such methods with a call to __asan_init
724 // at the beginning in order to initialize our runtime before any access to
725 // the shadow memory.
726 // We cannot just ignore these methods, because they may call other
727 // instrumented functions.
728 if (F.getName().find(" load]") != std::string::npos) {
729 IRBuilder<> IRB(F.begin()->begin());
730 IRB.CreateCall(AsanInitFunction);
736 bool AddressSanitizer::handleFunction(Module &M, Function &F) {
737 if (BL->isIn(F)) return false;
738 if (&F == AsanCtorFunction) return false;
740 // If needed, insert __asan_init before checking for AddressSafety attr.
741 maybeInsertAsanInitAtFunctionEntry(F);
743 if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
745 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
747 // We want to instrument every address only once per basic block
748 // (unless there are calls between uses).
749 SmallSet<Value*, 16> TempsToInstrument;
750 SmallVector<Instruction*, 16> ToInstrument;
751 SmallVector<Instruction*, 8> NoReturnCalls;
754 // Fill the set of memory operations to instrument.
755 for (Function::iterator FI = F.begin(), FE = F.end();
757 TempsToInstrument.clear();
758 int NumInsnsPerBB = 0;
759 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
761 if (LooksLikeCodeInBug11395(BI)) return false;
762 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
763 if (ClOpt && ClOptSameTemp) {
764 if (!TempsToInstrument.insert(Addr))
765 continue; // We've seen this temp in the current BB.
767 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
770 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
772 TempsToInstrument.clear();
773 if (CI->doesNotReturn()) {
774 NoReturnCalls.push_back(CI);
779 ToInstrument.push_back(BI);
781 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
786 AsanFunctionContext AFC(F);
789 int NumInstrumented = 0;
790 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
791 Instruction *Inst = ToInstrument[i];
792 if (ClDebugMin < 0 || ClDebugMax < 0 ||
793 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
794 if (isInterestingMemoryAccess(Inst, &IsWrite))
795 instrumentMop(AFC, Inst);
797 instrumentMemIntrinsic(AFC, cast<MemIntrinsic>(Inst));
804 bool ChangedStack = poisonStackInFunction(M, F);
806 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
807 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
808 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
809 Instruction *CI = NoReturnCalls[i];
811 IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
812 IRB.getVoidTy(), NULL));
815 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
818 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
819 if (ShadowRedzoneSize == 1) return PoisonByte;
820 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
821 if (ShadowRedzoneSize == 4)
822 return (PoisonByte << 24) + (PoisonByte << 16) +
823 (PoisonByte << 8) + (PoisonByte);
824 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
827 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
830 size_t ShadowGranularity,
832 for (size_t i = 0; i < RedzoneSize;
833 i+= ShadowGranularity, Shadow++) {
834 if (i + ShadowGranularity <= Size) {
835 *Shadow = 0; // fully addressable
836 } else if (i >= Size) {
837 *Shadow = Magic; // unaddressable
839 *Shadow = Size - i; // first Size-i bytes are addressable
844 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
846 Value *ShadowBase, bool DoPoison) {
847 size_t ShadowRZSize = RedzoneSize >> MappingScale;
848 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
849 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
850 Type *RZPtrTy = PointerType::get(RZTy, 0);
852 Value *PoisonLeft = ConstantInt::get(RZTy,
853 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
854 Value *PoisonMid = ConstantInt::get(RZTy,
855 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
856 Value *PoisonRight = ConstantInt::get(RZTy,
857 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
859 // poison the first red zone.
860 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
862 // poison all other red zones.
863 uint64_t Pos = RedzoneSize;
864 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
865 AllocaInst *AI = AllocaVec[i];
866 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
867 uint64_t AlignedSize = getAlignedAllocaSize(AI);
868 assert(AlignedSize - SizeInBytes < RedzoneSize);
873 assert(ShadowBase->getType() == IntptrTy);
874 if (SizeInBytes < AlignedSize) {
875 // Poison the partial redzone at right
877 ShadowBase, ConstantInt::get(IntptrTy,
878 (Pos >> MappingScale) - ShadowRZSize));
879 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
882 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
884 1ULL << MappingScale,
885 kAsanStackPartialRedzoneMagic);
887 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
888 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
891 // Poison the full redzone at right.
892 Ptr = IRB.CreateAdd(ShadowBase,
893 ConstantInt::get(IntptrTy, Pos >> MappingScale));
894 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
895 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
901 // Workaround for bug 11395: we don't want to instrument stack in functions
902 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
903 // FIXME: remove once the bug 11395 is fixed.
904 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
905 if (LongSize != 32) return false;
906 CallInst *CI = dyn_cast<CallInst>(I);
907 if (!CI || !CI->isInlineAsm()) return false;
908 if (CI->getNumArgOperands() <= 5) return false;
909 // We have inline assembly with quite a few arguments.
913 // Find all static Alloca instructions and put
914 // poisoned red zones around all of them.
915 // Then unpoison everything back before the function returns.
917 // Stack poisoning does not play well with exception handling.
918 // When an exception is thrown, we essentially bypass the code
919 // that unpoisones the stack. This is why the run-time library has
920 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
921 // stack in the interceptor. This however does not work inside the
922 // actual function which catches the exception. Most likely because the
923 // compiler hoists the load of the shadow value somewhere too high.
924 // This causes asan to report a non-existing bug on 453.povray.
925 // It sounds like an LLVM bug.
926 bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
927 if (!ClStack) return false;
928 SmallVector<AllocaInst*, 16> AllocaVec;
929 SmallVector<Instruction*, 8> RetVec;
930 uint64_t TotalSize = 0;
932 // Filter out Alloca instructions we want (and can) handle.
933 // Collect Ret instructions.
934 for (Function::iterator FI = F.begin(), FE = F.end();
936 BasicBlock &BB = *FI;
937 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
939 if (isa<ReturnInst>(BI)) {
940 RetVec.push_back(BI);
944 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
946 if (AI->isArrayAllocation()) continue;
947 if (!AI->isStaticAlloca()) continue;
948 if (!AI->getAllocatedType()->isSized()) continue;
949 if (AI->getAlignment() > RedzoneSize) continue;
950 AllocaVec.push_back(AI);
951 uint64_t AlignedSize = getAlignedAllocaSize(AI);
952 TotalSize += AlignedSize;
956 if (AllocaVec.empty()) return false;
958 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
960 bool DoStackMalloc = ClUseAfterReturn
961 && LocalStackSize <= kMaxStackMallocSize;
963 Instruction *InsBefore = AllocaVec[0];
964 IRBuilder<> IRB(InsBefore);
967 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
968 AllocaInst *MyAlloca =
969 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
970 MyAlloca->setAlignment(RedzoneSize);
971 assert(MyAlloca->isStaticAlloca());
972 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
973 Value *LocalStackBase = OrigStackBase;
976 Value *AsanStackMallocFunc = M.getOrInsertFunction(
977 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
978 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
979 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
982 // This string will be parsed by the run-time (DescribeStackAddress).
983 SmallString<2048> StackDescriptionStorage;
984 raw_svector_ostream StackDescription(StackDescriptionStorage);
985 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
987 uint64_t Pos = RedzoneSize;
988 // Replace Alloca instructions with base+offset.
989 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
990 AllocaInst *AI = AllocaVec[i];
991 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
992 StringRef Name = AI->getName();
993 StackDescription << Pos << " " << SizeInBytes << " "
994 << Name.size() << " " << Name << " ";
995 uint64_t AlignedSize = getAlignedAllocaSize(AI);
996 assert((AlignedSize % RedzoneSize) == 0);
997 AI->replaceAllUsesWith(
999 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1001 Pos += AlignedSize + RedzoneSize;
1003 assert(Pos == LocalStackSize);
1005 // Write the Magic value and the frame description constant to the redzone.
1006 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1007 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1009 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1010 ConstantInt::get(IntptrTy, LongSize/8));
1011 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1012 Value *Description = IRB.CreatePointerCast(
1013 createPrivateGlobalForString(M, StackDescription.str()),
1015 IRB.CreateStore(Description, BasePlus1);
1017 // Poison the stack redzones at the entry.
1018 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1019 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1021 Value *AsanStackFreeFunc = NULL;
1022 if (DoStackMalloc) {
1023 AsanStackFreeFunc = M.getOrInsertFunction(
1024 kAsanStackFreeName, IRB.getVoidTy(),
1025 IntptrTy, IntptrTy, IntptrTy, NULL);
1028 // Unpoison the stack before all ret instructions.
1029 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1030 Instruction *Ret = RetVec[i];
1031 IRBuilder<> IRBRet(Ret);
1033 // Mark the current frame as retired.
1034 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1036 // Unpoison the stack.
1037 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1039 if (DoStackMalloc) {
1040 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1041 ConstantInt::get(IntptrTy, LocalStackSize),