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/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/Type.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/OwningPtr.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/DataTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Support/system_error.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Transforms/Instrumentation.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/ModuleUtils.h"
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;
53 static const size_t kMaxStackMallocSize = 1 << 16; // 64K
54 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
55 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
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";
70 static const int kAsanStackLeftRedzoneMagic = 0xf1;
71 static const int kAsanStackMidRedzoneMagic = 0xf2;
72 static const int kAsanStackRightRedzoneMagic = 0xf3;
73 static const int kAsanStackPartialRedzoneMagic = 0xf4;
75 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
76 static const size_t kNumberOfAccessSizes = 5;
78 // Command-line flags.
80 // This flag may need to be replaced with -f[no-]asan-reads.
81 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
82 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
83 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
84 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
85 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
86 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
87 cl::Hidden, cl::init(true));
88 static cl::opt<bool> ClMergeCallbacks("asan-merge-callbacks",
89 cl::desc("merge __asan_report_ callbacks to create fewer BBs"),
90 cl::Hidden, cl::init(false));
91 // This flag limits the number of instructions to be instrumented
92 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
93 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
95 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
97 cl::desc("maximal number of instructions to instrument in any given BB"),
99 // This flag may need to be replaced with -f[no]asan-stack.
100 static cl::opt<bool> ClStack("asan-stack",
101 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
102 // This flag may need to be replaced with -f[no]asan-use-after-return.
103 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
104 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
105 // This flag may need to be replaced with -f[no]asan-globals.
106 static cl::opt<bool> ClGlobals("asan-globals",
107 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
108 static cl::opt<bool> ClMemIntrin("asan-memintrin",
109 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
110 // This flag may need to be replaced with -fasan-blacklist.
111 static cl::opt<std::string> ClBlackListFile("asan-blacklist",
112 cl::desc("File containing the list of functions to ignore "
113 "during instrumentation"), cl::Hidden);
115 // These flags allow to change the shadow mapping.
116 // The shadow mapping looks like
117 // Shadow = (Mem >> scale) + (1 << offset_log)
118 static cl::opt<int> ClMappingScale("asan-mapping-scale",
119 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
120 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
121 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
123 // Optimization flags. Not user visible, used mostly for testing
124 // and benchmarking the tool.
125 static cl::opt<bool> ClOpt("asan-opt",
126 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
127 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
128 cl::desc("Instrument the same temp just once"), cl::Hidden,
130 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
131 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
134 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
136 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
137 cl::Hidden, cl::init(0));
138 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
139 cl::Hidden, cl::desc("Debug func"));
140 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
141 cl::Hidden, cl::init(-1));
142 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
143 cl::Hidden, cl::init(-1));
147 /// An object of this type is created while instrumenting every function.
148 struct AsanFunctionContext {
149 AsanFunctionContext() {
150 memset(this, 0, sizeof(*this));
153 // These are initially zero. If we require at least one call to
154 // __asan_report_{read,write}{1,2,4,8,16}, an appropriate BB is created.
155 BasicBlock *CrashBlock[2][kNumberOfAccessSizes];
158 /// AddressSanitizer: instrument the code in module to find memory bugs.
159 struct AddressSanitizer : public ModulePass {
161 virtual const char *getPassName() const;
162 void instrumentMop(AsanFunctionContext &AFC, Instruction *I);
163 void instrumentAddress(AsanFunctionContext &AFC,
164 Instruction *OrigIns, IRBuilder<> &IRB,
165 Value *Addr, uint32_t TypeSize, bool IsWrite);
166 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
167 Value *ShadowValue, uint32_t TypeSize);
168 Instruction *generateCrashCode(BasicBlock *BB, Value *Addr,
169 bool IsWrite, uint32_t TypeSize);
170 bool instrumentMemIntrinsic(AsanFunctionContext &AFC, MemIntrinsic *MI);
171 void instrumentMemIntrinsicParam(AsanFunctionContext &AFC,
172 Instruction *OrigIns, Value *Addr,
174 Instruction *InsertBefore, bool IsWrite);
175 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
176 bool handleFunction(Module &M, Function &F);
177 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
178 bool poisonStackInFunction(Module &M, Function &F);
179 virtual bool runOnModule(Module &M);
180 bool insertGlobalRedzones(Module &M);
181 static char ID; // Pass identification, replacement for typeid
185 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
186 Type *Ty = AI->getAllocatedType();
187 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
190 uint64_t getAlignedSize(uint64_t SizeInBytes) {
191 return ((SizeInBytes + RedzoneSize - 1)
192 / RedzoneSize) * RedzoneSize;
194 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
195 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
196 return getAlignedSize(SizeInBytes);
199 Function *checkInterfaceFunction(Constant *FuncOrBitcast);
200 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
201 Value *ShadowBase, bool DoPoison);
202 bool LooksLikeCodeInBug11395(Instruction *I);
206 uint64_t MappingOffset;
212 Function *AsanCtorFunction;
213 Function *AsanInitFunction;
214 Instruction *CtorInsertBefore;
215 OwningPtr<FunctionBlackList> BL;
216 // This array is indexed by AccessIsWrite and log2(AccessSize).
217 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
222 char AddressSanitizer::ID = 0;
223 INITIALIZE_PASS(AddressSanitizer, "asan",
224 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
226 AddressSanitizer::AddressSanitizer() : ModulePass(ID) { }
227 ModulePass *llvm::createAddressSanitizerPass() {
228 return new AddressSanitizer();
231 const char *AddressSanitizer::getPassName() const {
232 return "AddressSanitizer";
235 // Create a constant for Str so that we can pass it to the run-time lib.
236 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
237 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
238 return new GlobalVariable(M, StrConst->getType(), true,
239 GlobalValue::PrivateLinkage, StrConst, "");
242 // Split the basic block and insert an if-then code.
253 // If ThenBlock is zero, a new block is created and its terminator is returned.
254 // Otherwize NULL is returned.
255 static BranchInst *splitBlockAndInsertIfThen(Value *Cmp,
256 BasicBlock *ThenBlock = 0) {
257 Instruction *SplitBefore = cast<Instruction>(Cmp)->getNextNode();
258 BasicBlock *Head = SplitBefore->getParent();
259 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
260 TerminatorInst *HeadOldTerm = Head->getTerminator();
261 BranchInst *CheckTerm = NULL;
263 LLVMContext &C = Head->getParent()->getParent()->getContext();
264 ThenBlock = BasicBlock::Create(C, "", Head->getParent());
265 CheckTerm = BranchInst::Create(Tail, ThenBlock);
267 BranchInst *HeadNewTerm =
268 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
269 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
274 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
276 Shadow = IRB.CreateLShr(Shadow, MappingScale);
277 if (MappingOffset == 0)
279 // (Shadow >> scale) | offset
280 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
284 void AddressSanitizer::instrumentMemIntrinsicParam(
285 AsanFunctionContext &AFC, Instruction *OrigIns,
286 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
287 // Check the first byte.
289 IRBuilder<> IRB(InsertBefore);
290 instrumentAddress(AFC, OrigIns, IRB, Addr, 8, IsWrite);
292 // Check the last byte.
294 IRBuilder<> IRB(InsertBefore);
295 Value *SizeMinusOne = IRB.CreateSub(
296 Size, ConstantInt::get(Size->getType(), 1));
297 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
298 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
299 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
300 instrumentAddress(AFC, OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
304 // Instrument memset/memmove/memcpy
305 bool AddressSanitizer::instrumentMemIntrinsic(AsanFunctionContext &AFC,
307 Value *Dst = MI->getDest();
308 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
309 Value *Src = MemTran ? MemTran->getSource() : NULL;
310 Value *Length = MI->getLength();
312 Constant *ConstLength = dyn_cast<Constant>(Length);
313 Instruction *InsertBefore = MI;
315 if (ConstLength->isNullValue()) return false;
317 // The size is not a constant so it could be zero -- check at run-time.
318 IRBuilder<> IRB(InsertBefore);
320 Value *Cmp = IRB.CreateICmpNE(Length,
321 Constant::getNullValue(Length->getType()));
322 InsertBefore = splitBlockAndInsertIfThen(Cmp);
325 instrumentMemIntrinsicParam(AFC, MI, Dst, Length, InsertBefore, true);
327 instrumentMemIntrinsicParam(AFC, MI, Src, Length, InsertBefore, false);
331 // If I is an interesting memory access, return the PointerOperand
332 // and set IsWrite. Otherwise return NULL.
333 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
334 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
335 if (!ClInstrumentReads) return NULL;
337 return LI->getPointerOperand();
339 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
340 if (!ClInstrumentWrites) return NULL;
342 return SI->getPointerOperand();
344 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
345 if (!ClInstrumentAtomics) return NULL;
347 return RMW->getPointerOperand();
349 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
350 if (!ClInstrumentAtomics) return NULL;
352 return XCHG->getPointerOperand();
357 void AddressSanitizer::instrumentMop(AsanFunctionContext &AFC, Instruction *I) {
359 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
361 if (ClOpt && ClOptGlobals && isa<GlobalVariable>(Addr)) {
362 // We are accessing a global scalar variable. Nothing to catch here.
365 Type *OrigPtrTy = Addr->getType();
366 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
368 assert(OrigTy->isSized());
369 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
371 if (TypeSize != 8 && TypeSize != 16 &&
372 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
373 // Ignore all unusual sizes.
378 instrumentAddress(AFC, I, IRB, Addr, TypeSize, IsWrite);
381 // Validate the result of Module::getOrInsertFunction called for an interface
382 // function of AddressSanitizer. If the instrumented module defines a function
383 // with the same name, their prototypes must match, otherwise
384 // getOrInsertFunction returns a bitcast.
385 Function *AddressSanitizer::checkInterfaceFunction(Constant *FuncOrBitcast) {
386 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
387 FuncOrBitcast->dump();
388 report_fatal_error("trying to redefine an AddressSanitizer "
389 "interface function");
392 Instruction *AddressSanitizer::generateCrashCode(
393 BasicBlock *BB, Value *Addr, bool IsWrite, uint32_t TypeSize) {
394 IRBuilder<> IRB(BB->getFirstNonPHI());
395 size_t AccessSizeIndex = CountTrailingZeros_32(TypeSize / 8);
396 assert(AccessSizeIndex < kNumberOfAccessSizes);
397 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
399 Call->setDoesNotReturn();
403 Value * AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
406 size_t Granularity = 1 << MappingScale;
407 // Addr & (Granularity - 1)
408 Value *LastAccessedByte = IRB.CreateAnd(
409 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
410 // (Addr & (Granularity - 1)) + size - 1
411 if (TypeSize / 8 > 1)
412 LastAccessedByte = IRB.CreateAdd(
413 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
414 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
415 LastAccessedByte = IRB.CreateIntCast(
416 LastAccessedByte, IRB.getInt8Ty(), false);
417 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
418 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
421 void AddressSanitizer::instrumentAddress(AsanFunctionContext &AFC,
422 Instruction *OrigIns,
423 IRBuilder<> &IRB, Value *Addr,
424 uint32_t TypeSize, bool IsWrite) {
425 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
427 Type *ShadowTy = IntegerType::get(
428 *C, std::max(8U, TypeSize >> MappingScale));
429 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
430 Value *ShadowPtr = memToShadow(AddrLong, IRB);
431 Value *CmpVal = Constant::getNullValue(ShadowTy);
432 Value *ShadowValue = IRB.CreateLoad(
433 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
435 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
437 BasicBlock *CrashBlock = NULL;
438 if (ClMergeCallbacks) {
439 llvm_unreachable("unimplemented yet");
441 CrashBlock = BasicBlock::Create(*C, "crash_bb",
442 OrigIns->getParent()->getParent());
443 new UnreachableInst(*C, CrashBlock);
445 generateCrashCode(CrashBlock, AddrLong, IsWrite, TypeSize);
446 Crash->setDebugLoc(OrigIns->getDebugLoc());
449 size_t Granularity = 1 << MappingScale;
450 if (TypeSize < 8 * Granularity) {
451 Instruction *CheckTerm = splitBlockAndInsertIfThen(Cmp);
452 IRB.SetInsertPoint(CheckTerm);
453 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
454 splitBlockAndInsertIfThen(Cmp2, CrashBlock);
456 splitBlockAndInsertIfThen(Cmp, CrashBlock);
460 // This function replaces all global variables with new variables that have
461 // trailing redzones. It also creates a function that poisons
462 // redzones and inserts this function into llvm.global_ctors.
463 bool AddressSanitizer::insertGlobalRedzones(Module &M) {
464 SmallVector<GlobalVariable *, 16> GlobalsToChange;
466 for (Module::GlobalListType::iterator G = M.getGlobalList().begin(),
467 E = M.getGlobalList().end(); G != E; ++G) {
468 Type *Ty = cast<PointerType>(G->getType())->getElementType();
469 DEBUG(dbgs() << "GLOBAL: " << *G);
471 if (!Ty->isSized()) continue;
472 if (!G->hasInitializer()) continue;
473 // Touch only those globals that will not be defined in other modules.
474 // Don't handle ODR type linkages since other modules may be built w/o asan.
475 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
476 G->getLinkage() != GlobalVariable::PrivateLinkage &&
477 G->getLinkage() != GlobalVariable::InternalLinkage)
479 // Two problems with thread-locals:
480 // - The address of the main thread's copy can't be computed at link-time.
481 // - Need to poison all copies, not just the main thread's one.
482 if (G->isThreadLocal())
484 // For now, just ignore this Alloca if the alignment is large.
485 if (G->getAlignment() > RedzoneSize) continue;
487 // Ignore all the globals with the names starting with "\01L_OBJC_".
488 // Many of those are put into the .cstring section. The linker compresses
489 // that section by removing the spare \0s after the string terminator, so
490 // our redzones get broken.
491 if ((G->getName().find("\01L_OBJC_") == 0) ||
492 (G->getName().find("\01l_OBJC_") == 0)) {
493 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
497 if (G->hasSection()) {
498 StringRef Section(G->getSection());
499 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
500 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
502 if ((Section.find("__OBJC,") == 0) ||
503 (Section.find("__DATA, __objc_") == 0)) {
504 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
507 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
508 // Constant CFString instances are compiled in the following way:
509 // -- the string buffer is emitted into
510 // __TEXT,__cstring,cstring_literals
511 // -- the constant NSConstantString structure referencing that buffer
512 // is placed into __DATA,__cfstring
513 // Therefore there's no point in placing redzones into __DATA,__cfstring.
514 // Moreover, it causes the linker to crash on OS X 10.7
515 if (Section.find("__DATA,__cfstring") == 0) {
516 DEBUG(dbgs() << "Ignoring CFString: " << *G);
521 GlobalsToChange.push_back(G);
524 size_t n = GlobalsToChange.size();
525 if (n == 0) return false;
527 // A global is described by a structure
530 // size_t size_with_redzone;
532 // We initialize an array of such structures and pass it to a run-time call.
533 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
534 IntptrTy, IntptrTy, NULL);
535 SmallVector<Constant *, 16> Initializers(n);
537 IRBuilder<> IRB(CtorInsertBefore);
539 for (size_t i = 0; i < n; i++) {
540 GlobalVariable *G = GlobalsToChange[i];
541 PointerType *PtrTy = cast<PointerType>(G->getType());
542 Type *Ty = PtrTy->getElementType();
543 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
544 uint64_t RightRedzoneSize = RedzoneSize +
545 (RedzoneSize - (SizeInBytes % RedzoneSize));
546 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
548 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
549 Constant *NewInitializer = ConstantStruct::get(
550 NewTy, G->getInitializer(),
551 Constant::getNullValue(RightRedZoneTy), NULL);
553 SmallString<2048> DescriptionOfGlobal = G->getName();
554 DescriptionOfGlobal += " (";
555 DescriptionOfGlobal += M.getModuleIdentifier();
556 DescriptionOfGlobal += ")";
557 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
559 // Create a new global variable with enough space for a redzone.
560 GlobalVariable *NewGlobal = new GlobalVariable(
561 M, NewTy, G->isConstant(), G->getLinkage(),
562 NewInitializer, "", G, G->getThreadLocalMode());
563 NewGlobal->copyAttributesFrom(G);
564 NewGlobal->setAlignment(RedzoneSize);
567 Indices2[0] = IRB.getInt32(0);
568 Indices2[1] = IRB.getInt32(0);
570 G->replaceAllUsesWith(
571 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
572 NewGlobal->takeName(G);
573 G->eraseFromParent();
575 Initializers[i] = ConstantStruct::get(
577 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
578 ConstantInt::get(IntptrTy, SizeInBytes),
579 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
580 ConstantExpr::getPointerCast(Name, IntptrTy),
582 DEBUG(dbgs() << "NEW GLOBAL:\n" << *NewGlobal);
585 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
586 GlobalVariable *AllGlobals = new GlobalVariable(
587 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
588 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
590 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
591 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
592 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
594 IRB.CreateCall2(AsanRegisterGlobals,
595 IRB.CreatePointerCast(AllGlobals, IntptrTy),
596 ConstantInt::get(IntptrTy, n));
598 // We also need to unregister globals at the end, e.g. when a shared library
600 Function *AsanDtorFunction = Function::Create(
601 FunctionType::get(Type::getVoidTy(*C), false),
602 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
603 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
604 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
605 Function *AsanUnregisterGlobals =
606 checkInterfaceFunction(M.getOrInsertFunction(
607 kAsanUnregisterGlobalsName,
608 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
609 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
611 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
612 IRB.CreatePointerCast(AllGlobals, IntptrTy),
613 ConstantInt::get(IntptrTy, n));
614 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
621 bool AddressSanitizer::runOnModule(Module &M) {
622 // Initialize the private fields. No one has accessed them before.
623 TD = getAnalysisIfAvailable<TargetData>();
626 BL.reset(new FunctionBlackList(ClBlackListFile));
628 C = &(M.getContext());
629 LongSize = TD->getPointerSizeInBits();
630 IntptrTy = Type::getIntNTy(*C, LongSize);
631 IntptrPtrTy = PointerType::get(IntptrTy, 0);
633 AsanCtorFunction = Function::Create(
634 FunctionType::get(Type::getVoidTy(*C), false),
635 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
636 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
637 CtorInsertBefore = ReturnInst::Create(*C, AsanCtorBB);
639 // call __asan_init in the module ctor.
640 IRBuilder<> IRB(CtorInsertBefore);
641 AsanInitFunction = checkInterfaceFunction(
642 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
643 AsanInitFunction->setLinkage(Function::ExternalLinkage);
644 IRB.CreateCall(AsanInitFunction);
646 // Create __asan_report* callbacks.
647 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
648 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
650 // IsWrite and TypeSize are encoded in the function name.
651 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
652 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
653 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] = cast<Function>(
654 M.getOrInsertFunction(FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
658 llvm::Triple targetTriple(M.getTargetTriple());
659 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::ANDROIDEABI;
661 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
662 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
663 if (ClMappingOffsetLog >= 0) {
664 if (ClMappingOffsetLog == 0) {
668 MappingOffset = 1ULL << ClMappingOffsetLog;
671 MappingScale = kDefaultShadowScale;
672 if (ClMappingScale) {
673 MappingScale = ClMappingScale;
675 // Redzone used for stack and globals is at least 32 bytes.
676 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
677 RedzoneSize = std::max(32, (int)(1 << MappingScale));
682 Res |= insertGlobalRedzones(M);
684 if (ClMappingOffsetLog >= 0) {
685 // Tell the run-time the current values of mapping offset and scale.
686 GlobalValue *asan_mapping_offset =
687 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
688 ConstantInt::get(IntptrTy, MappingOffset),
689 kAsanMappingOffsetName);
690 // Read the global, otherwise it may be optimized away.
691 IRB.CreateLoad(asan_mapping_offset, true);
693 if (ClMappingScale) {
694 GlobalValue *asan_mapping_scale =
695 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
696 ConstantInt::get(IntptrTy, MappingScale),
697 kAsanMappingScaleName);
698 // Read the global, otherwise it may be optimized away.
699 IRB.CreateLoad(asan_mapping_scale, true);
703 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
704 if (F->isDeclaration()) continue;
705 Res |= handleFunction(M, *F);
708 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
713 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
714 // For each NSObject descendant having a +load method, this method is invoked
715 // by the ObjC runtime before any of the static constructors is called.
716 // Therefore we need to instrument such methods with a call to __asan_init
717 // at the beginning in order to initialize our runtime before any access to
718 // the shadow memory.
719 // We cannot just ignore these methods, because they may call other
720 // instrumented functions.
721 if (F.getName().find(" load]") != std::string::npos) {
722 IRBuilder<> IRB(F.begin()->begin());
723 IRB.CreateCall(AsanInitFunction);
729 bool AddressSanitizer::handleFunction(Module &M, Function &F) {
730 if (BL->isIn(F)) return false;
731 if (&F == AsanCtorFunction) return false;
733 // If needed, insert __asan_init before checking for AddressSafety attr.
734 maybeInsertAsanInitAtFunctionEntry(F);
736 if (!F.hasFnAttr(Attribute::AddressSafety)) return false;
738 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
740 // We want to instrument every address only once per basic block
741 // (unless there are calls between uses).
742 SmallSet<Value*, 16> TempsToInstrument;
743 SmallVector<Instruction*, 16> ToInstrument;
744 SmallVector<Instruction*, 8> NoReturnCalls;
747 // Fill the set of memory operations to instrument.
748 for (Function::iterator FI = F.begin(), FE = F.end();
750 TempsToInstrument.clear();
751 int NumInsnsPerBB = 0;
752 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
754 if (LooksLikeCodeInBug11395(BI)) return false;
755 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
756 if (ClOpt && ClOptSameTemp) {
757 if (!TempsToInstrument.insert(Addr))
758 continue; // We've seen this temp in the current BB.
760 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
763 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
765 TempsToInstrument.clear();
766 if (CI->doesNotReturn()) {
767 NoReturnCalls.push_back(CI);
772 ToInstrument.push_back(BI);
774 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
779 AsanFunctionContext AFC;
782 int NumInstrumented = 0;
783 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
784 Instruction *Inst = ToInstrument[i];
785 if (ClDebugMin < 0 || ClDebugMax < 0 ||
786 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
787 if (isInterestingMemoryAccess(Inst, &IsWrite))
788 instrumentMop(AFC, Inst);
790 instrumentMemIntrinsic(AFC, cast<MemIntrinsic>(Inst));
797 bool ChangedStack = poisonStackInFunction(M, F);
799 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
800 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
801 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
802 Instruction *CI = NoReturnCalls[i];
804 IRB.CreateCall(M.getOrInsertFunction(kAsanHandleNoReturnName,
805 IRB.getVoidTy(), NULL));
808 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
811 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
812 if (ShadowRedzoneSize == 1) return PoisonByte;
813 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
814 if (ShadowRedzoneSize == 4)
815 return (PoisonByte << 24) + (PoisonByte << 16) +
816 (PoisonByte << 8) + (PoisonByte);
817 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
820 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
823 size_t ShadowGranularity,
825 for (size_t i = 0; i < RedzoneSize;
826 i+= ShadowGranularity, Shadow++) {
827 if (i + ShadowGranularity <= Size) {
828 *Shadow = 0; // fully addressable
829 } else if (i >= Size) {
830 *Shadow = Magic; // unaddressable
832 *Shadow = Size - i; // first Size-i bytes are addressable
837 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
839 Value *ShadowBase, bool DoPoison) {
840 size_t ShadowRZSize = RedzoneSize >> MappingScale;
841 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
842 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
843 Type *RZPtrTy = PointerType::get(RZTy, 0);
845 Value *PoisonLeft = ConstantInt::get(RZTy,
846 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
847 Value *PoisonMid = ConstantInt::get(RZTy,
848 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
849 Value *PoisonRight = ConstantInt::get(RZTy,
850 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
852 // poison the first red zone.
853 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
855 // poison all other red zones.
856 uint64_t Pos = RedzoneSize;
857 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
858 AllocaInst *AI = AllocaVec[i];
859 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
860 uint64_t AlignedSize = getAlignedAllocaSize(AI);
861 assert(AlignedSize - SizeInBytes < RedzoneSize);
866 assert(ShadowBase->getType() == IntptrTy);
867 if (SizeInBytes < AlignedSize) {
868 // Poison the partial redzone at right
870 ShadowBase, ConstantInt::get(IntptrTy,
871 (Pos >> MappingScale) - ShadowRZSize));
872 size_t AddressableBytes = RedzoneSize - (AlignedSize - SizeInBytes);
875 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
877 1ULL << MappingScale,
878 kAsanStackPartialRedzoneMagic);
880 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
881 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
884 // Poison the full redzone at right.
885 Ptr = IRB.CreateAdd(ShadowBase,
886 ConstantInt::get(IntptrTy, Pos >> MappingScale));
887 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
888 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
894 // Workaround for bug 11395: we don't want to instrument stack in functions
895 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
896 // FIXME: remove once the bug 11395 is fixed.
897 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
898 if (LongSize != 32) return false;
899 CallInst *CI = dyn_cast<CallInst>(I);
900 if (!CI || !CI->isInlineAsm()) return false;
901 if (CI->getNumArgOperands() <= 5) return false;
902 // We have inline assembly with quite a few arguments.
906 // Find all static Alloca instructions and put
907 // poisoned red zones around all of them.
908 // Then unpoison everything back before the function returns.
910 // Stack poisoning does not play well with exception handling.
911 // When an exception is thrown, we essentially bypass the code
912 // that unpoisones the stack. This is why the run-time library has
913 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
914 // stack in the interceptor. This however does not work inside the
915 // actual function which catches the exception. Most likely because the
916 // compiler hoists the load of the shadow value somewhere too high.
917 // This causes asan to report a non-existing bug on 453.povray.
918 // It sounds like an LLVM bug.
919 bool AddressSanitizer::poisonStackInFunction(Module &M, Function &F) {
920 if (!ClStack) return false;
921 SmallVector<AllocaInst*, 16> AllocaVec;
922 SmallVector<Instruction*, 8> RetVec;
923 uint64_t TotalSize = 0;
925 // Filter out Alloca instructions we want (and can) handle.
926 // Collect Ret instructions.
927 for (Function::iterator FI = F.begin(), FE = F.end();
929 BasicBlock &BB = *FI;
930 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
932 if (isa<ReturnInst>(BI)) {
933 RetVec.push_back(BI);
937 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
939 if (AI->isArrayAllocation()) continue;
940 if (!AI->isStaticAlloca()) continue;
941 if (!AI->getAllocatedType()->isSized()) continue;
942 if (AI->getAlignment() > RedzoneSize) continue;
943 AllocaVec.push_back(AI);
944 uint64_t AlignedSize = getAlignedAllocaSize(AI);
945 TotalSize += AlignedSize;
949 if (AllocaVec.empty()) return false;
951 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize;
953 bool DoStackMalloc = ClUseAfterReturn
954 && LocalStackSize <= kMaxStackMallocSize;
956 Instruction *InsBefore = AllocaVec[0];
957 IRBuilder<> IRB(InsBefore);
960 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
961 AllocaInst *MyAlloca =
962 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
963 MyAlloca->setAlignment(RedzoneSize);
964 assert(MyAlloca->isStaticAlloca());
965 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
966 Value *LocalStackBase = OrigStackBase;
969 Value *AsanStackMallocFunc = M.getOrInsertFunction(
970 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL);
971 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
972 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
975 // This string will be parsed by the run-time (DescribeStackAddress).
976 SmallString<2048> StackDescriptionStorage;
977 raw_svector_ostream StackDescription(StackDescriptionStorage);
978 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
980 uint64_t Pos = RedzoneSize;
981 // Replace Alloca instructions with base+offset.
982 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
983 AllocaInst *AI = AllocaVec[i];
984 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
985 StringRef Name = AI->getName();
986 StackDescription << Pos << " " << SizeInBytes << " "
987 << Name.size() << " " << Name << " ";
988 uint64_t AlignedSize = getAlignedAllocaSize(AI);
989 assert((AlignedSize % RedzoneSize) == 0);
990 AI->replaceAllUsesWith(
992 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
994 Pos += AlignedSize + RedzoneSize;
996 assert(Pos == LocalStackSize);
998 // Write the Magic value and the frame description constant to the redzone.
999 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1000 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1002 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1003 ConstantInt::get(IntptrTy, LongSize/8));
1004 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1005 Value *Description = IRB.CreatePointerCast(
1006 createPrivateGlobalForString(M, StackDescription.str()),
1008 IRB.CreateStore(Description, BasePlus1);
1010 // Poison the stack redzones at the entry.
1011 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1012 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1014 Value *AsanStackFreeFunc = NULL;
1015 if (DoStackMalloc) {
1016 AsanStackFreeFunc = M.getOrInsertFunction(
1017 kAsanStackFreeName, IRB.getVoidTy(),
1018 IntptrTy, IntptrTy, IntptrTy, NULL);
1021 // Unpoison the stack before all ret instructions.
1022 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1023 Instruction *Ret = RetVec[i];
1024 IRBuilder<> IRBRet(Ret);
1026 // Mark the current frame as retired.
1027 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1029 // Unpoison the stack.
1030 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1032 if (DoStackMalloc) {
1033 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1034 ConstantInt::get(IntptrTy, LocalStackSize),