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 "llvm/Transforms/Instrumentation.h"
19 #include "BlackList.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/DataLayout.h"
28 #include "llvm/Function.h"
29 #include "llvm/IRBuilder.h"
30 #include "llvm/InlineAsm.h"
31 #include "llvm/IntrinsicInst.h"
32 #include "llvm/LLVMContext.h"
33 #include "llvm/Module.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/DataTypes.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Support/system_error.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/ModuleUtils.h"
42 #include "llvm/Type.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 *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
64 static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
65 static const char *kAsanInitName = "__asan_init";
66 static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
67 static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
68 static const char *kAsanMappingScaleName = "__asan_mapping_scale";
69 static const char *kAsanStackMallocName = "__asan_stack_malloc";
70 static const char *kAsanStackFreeName = "__asan_stack_free";
71 static const char *kAsanGenPrefix = "__asan_gen_";
73 static const int kAsanStackLeftRedzoneMagic = 0xf1;
74 static const int kAsanStackMidRedzoneMagic = 0xf2;
75 static const int kAsanStackRightRedzoneMagic = 0xf3;
76 static const int kAsanStackPartialRedzoneMagic = 0xf4;
78 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
79 static const size_t kNumberOfAccessSizes = 5;
81 // Command-line flags.
83 // This flag may need to be replaced with -f[no-]asan-reads.
84 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
85 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
86 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
87 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
88 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
89 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
90 cl::Hidden, cl::init(true));
91 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
92 cl::desc("use instrumentation with slow path for all accesses"),
93 cl::Hidden, cl::init(false));
94 // This flag limits the number of instructions to be instrumented
95 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
96 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
98 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
100 cl::desc("maximal number of instructions to instrument in any given BB"),
102 // This flag may need to be replaced with -f[no]asan-stack.
103 static cl::opt<bool> ClStack("asan-stack",
104 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
105 // This flag may need to be replaced with -f[no]asan-use-after-return.
106 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
107 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
108 // This flag may need to be replaced with -f[no]asan-globals.
109 static cl::opt<bool> ClGlobals("asan-globals",
110 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
111 static cl::opt<bool> ClInitializers("asan-initialization-order",
112 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
113 static cl::opt<bool> ClMemIntrin("asan-memintrin",
114 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
115 static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
116 cl::desc("File containing the list of objects to ignore "
117 "during instrumentation"), cl::Hidden);
119 // These flags allow to change the shadow mapping.
120 // The shadow mapping looks like
121 // Shadow = (Mem >> scale) + (1 << offset_log)
122 static cl::opt<int> ClMappingScale("asan-mapping-scale",
123 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
124 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
125 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
127 // Optimization flags. Not user visible, used mostly for testing
128 // and benchmarking the tool.
129 static cl::opt<bool> ClOpt("asan-opt",
130 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
131 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
132 cl::desc("Instrument the same temp just once"), cl::Hidden,
134 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
135 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
137 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
138 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
139 cl::Hidden, cl::init(false));
142 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
144 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
145 cl::Hidden, cl::init(0));
146 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
147 cl::Hidden, cl::desc("Debug func"));
148 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
149 cl::Hidden, cl::init(-1));
150 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
151 cl::Hidden, cl::init(-1));
154 /// A set of dynamically initialized globals extracted from metadata.
155 class SetOfDynamicallyInitializedGlobals {
157 void Init(Module& M) {
158 // Clang generates metadata identifying all dynamically initialized globals.
159 NamedMDNode *DynamicGlobals =
160 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
163 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
164 MDNode *MDN = DynamicGlobals->getOperand(i);
165 assert(MDN->getNumOperands() == 1);
166 Value *VG = MDN->getOperand(0);
167 // The optimizer may optimize away a global entirely, in which case we
168 // cannot instrument access to it.
171 DynInitGlobals.insert(cast<GlobalVariable>(VG));
174 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
176 SmallSet<GlobalValue*, 32> DynInitGlobals;
179 static int MappingScale() {
180 return ClMappingScale ? ClMappingScale : kDefaultShadowScale;
183 static size_t RedzoneSize() {
184 // Redzone used for stack and globals is at least 32 bytes.
185 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
186 return std::max(32U, 1U << MappingScale());
189 /// AddressSanitizer: instrument the code in module to find memory bugs.
190 struct AddressSanitizer : public FunctionPass {
191 AddressSanitizer(bool CheckInitOrder = false,
192 bool CheckUseAfterReturn = false,
193 bool CheckLifetime = false,
194 StringRef BlacklistFile = StringRef())
196 CheckInitOrder(CheckInitOrder || ClInitializers),
197 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
198 CheckLifetime(CheckLifetime || ClCheckLifetime),
199 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
201 virtual const char *getPassName() const {
202 return "AddressSanitizerFunctionPass";
204 void instrumentMop(Instruction *I);
205 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
206 Value *Addr, uint32_t TypeSize, bool IsWrite);
207 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
208 Value *ShadowValue, uint32_t TypeSize);
209 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
210 bool IsWrite, size_t AccessSizeIndex);
211 bool instrumentMemIntrinsic(MemIntrinsic *MI);
212 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
214 Instruction *InsertBefore, bool IsWrite);
215 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
216 bool runOnFunction(Function &F);
217 void createInitializerPoisonCalls(Module &M,
218 Value *FirstAddr, Value *LastAddr);
219 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
220 bool poisonStackInFunction(Function &F);
221 virtual bool doInitialization(Module &M);
222 static char ID; // Pass identification, replacement for typeid
225 void initializeCallbacks(Module &M);
226 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
227 Type *Ty = AI->getAllocatedType();
228 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
231 uint64_t getAlignedSize(uint64_t SizeInBytes) {
232 size_t RZ = RedzoneSize();
233 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
235 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
236 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
237 return getAlignedSize(SizeInBytes);
240 bool ShouldInstrumentGlobal(GlobalVariable *G);
241 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
242 Value *ShadowBase, bool DoPoison);
243 bool LooksLikeCodeInBug11395(Instruction *I);
244 void FindDynamicInitializers(Module &M);
247 bool CheckUseAfterReturn;
251 uint64_t MappingOffset;
255 Function *AsanCtorFunction;
256 Function *AsanInitFunction;
257 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
258 Function *AsanHandleNoReturnFunc;
259 SmallString<64> BlacklistFile;
260 OwningPtr<BlackList> BL;
261 // This array is indexed by AccessIsWrite and log2(AccessSize).
262 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
264 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
267 class AddressSanitizerModule : public ModulePass {
269 AddressSanitizerModule(bool CheckInitOrder = false,
270 StringRef BlacklistFile = StringRef())
272 CheckInitOrder(CheckInitOrder || ClInitializers),
273 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
275 bool runOnModule(Module &M);
276 static char ID; // Pass identification, replacement for typeid
277 virtual const char *getPassName() const {
278 return "AddressSanitizerModule";
281 bool ShouldInstrumentGlobal(GlobalVariable *G);
282 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
286 SmallString<64> BlacklistFile;
287 OwningPtr<BlackList> BL;
288 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
296 char AddressSanitizer::ID = 0;
297 INITIALIZE_PASS(AddressSanitizer, "asan",
298 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
300 FunctionPass *llvm::createAddressSanitizerFunctionPass(
301 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
302 StringRef BlacklistFile) {
303 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
304 CheckLifetime, BlacklistFile);
307 char AddressSanitizerModule::ID = 0;
308 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
309 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
310 "ModulePass", false, false)
311 ModulePass *llvm::createAddressSanitizerModulePass(
312 bool CheckInitOrder, StringRef BlacklistFile) {
313 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
316 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
317 size_t Res = CountTrailingZeros_32(TypeSize / 8);
318 assert(Res < kNumberOfAccessSizes);
322 // Create a constant for Str so that we can pass it to the run-time lib.
323 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
324 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
325 return new GlobalVariable(M, StrConst->getType(), true,
326 GlobalValue::PrivateLinkage, StrConst,
330 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
331 return G->getName().find(kAsanGenPrefix) == 0;
334 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
336 Shadow = IRB.CreateLShr(Shadow, MappingScale());
337 if (MappingOffset == 0)
339 // (Shadow >> scale) | offset
340 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
344 void AddressSanitizer::instrumentMemIntrinsicParam(
345 Instruction *OrigIns,
346 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
347 // Check the first byte.
349 IRBuilder<> IRB(InsertBefore);
350 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
352 // Check the last byte.
354 IRBuilder<> IRB(InsertBefore);
355 Value *SizeMinusOne = IRB.CreateSub(
356 Size, ConstantInt::get(Size->getType(), 1));
357 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
358 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
359 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
360 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
364 // Instrument memset/memmove/memcpy
365 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
366 Value *Dst = MI->getDest();
367 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
368 Value *Src = MemTran ? MemTran->getSource() : 0;
369 Value *Length = MI->getLength();
371 Constant *ConstLength = dyn_cast<Constant>(Length);
372 Instruction *InsertBefore = MI;
374 if (ConstLength->isNullValue()) return false;
376 // The size is not a constant so it could be zero -- check at run-time.
377 IRBuilder<> IRB(InsertBefore);
379 Value *Cmp = IRB.CreateICmpNE(Length,
380 Constant::getNullValue(Length->getType()));
381 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
384 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
386 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
390 // If I is an interesting memory access, return the PointerOperand
391 // and set IsWrite. Otherwise return NULL.
392 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
393 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
394 if (!ClInstrumentReads) return NULL;
396 return LI->getPointerOperand();
398 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
399 if (!ClInstrumentWrites) return NULL;
401 return SI->getPointerOperand();
403 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
404 if (!ClInstrumentAtomics) return NULL;
406 return RMW->getPointerOperand();
408 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
409 if (!ClInstrumentAtomics) return NULL;
411 return XCHG->getPointerOperand();
416 void AddressSanitizer::instrumentMop(Instruction *I) {
417 bool IsWrite = false;
418 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
420 if (ClOpt && ClOptGlobals) {
421 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
422 // If initialization order checking is disabled, a simple access to a
423 // dynamically initialized global is always valid.
426 // If a global variable does not have dynamic initialization we don't
427 // have to instrument it. However, if a global does not have initailizer
428 // at all, we assume it has dynamic initializer (in other TU).
429 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
434 Type *OrigPtrTy = Addr->getType();
435 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
437 assert(OrigTy->isSized());
438 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
440 if (TypeSize != 8 && TypeSize != 16 &&
441 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
442 // Ignore all unusual sizes.
447 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
450 // Validate the result of Module::getOrInsertFunction called for an interface
451 // function of AddressSanitizer. If the instrumented module defines a function
452 // with the same name, their prototypes must match, otherwise
453 // getOrInsertFunction returns a bitcast.
454 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
455 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
456 FuncOrBitcast->dump();
457 report_fatal_error("trying to redefine an AddressSanitizer "
458 "interface function");
461 Instruction *AddressSanitizer::generateCrashCode(
462 Instruction *InsertBefore, Value *Addr,
463 bool IsWrite, size_t AccessSizeIndex) {
464 IRBuilder<> IRB(InsertBefore);
465 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
467 // We don't do Call->setDoesNotReturn() because the BB already has
468 // UnreachableInst at the end.
469 // This EmptyAsm is required to avoid callback merge.
470 IRB.CreateCall(EmptyAsm);
474 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
477 size_t Granularity = 1 << MappingScale();
478 // Addr & (Granularity - 1)
479 Value *LastAccessedByte = IRB.CreateAnd(
480 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
481 // (Addr & (Granularity - 1)) + size - 1
482 if (TypeSize / 8 > 1)
483 LastAccessedByte = IRB.CreateAdd(
484 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
485 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
486 LastAccessedByte = IRB.CreateIntCast(
487 LastAccessedByte, ShadowValue->getType(), false);
488 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
489 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
492 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
493 IRBuilder<> &IRB, Value *Addr,
494 uint32_t TypeSize, bool IsWrite) {
495 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
497 Type *ShadowTy = IntegerType::get(
498 *C, std::max(8U, TypeSize >> MappingScale()));
499 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
500 Value *ShadowPtr = memToShadow(AddrLong, IRB);
501 Value *CmpVal = Constant::getNullValue(ShadowTy);
502 Value *ShadowValue = IRB.CreateLoad(
503 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
505 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
506 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
507 size_t Granularity = 1 << MappingScale();
508 TerminatorInst *CrashTerm = 0;
510 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
511 TerminatorInst *CheckTerm =
512 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
513 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
514 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
515 IRB.SetInsertPoint(CheckTerm);
516 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
517 BasicBlock *CrashBlock =
518 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
519 CrashTerm = new UnreachableInst(*C, CrashBlock);
520 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
521 ReplaceInstWithInst(CheckTerm, NewTerm);
523 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
527 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
528 Crash->setDebugLoc(OrigIns->getDebugLoc());
531 void AddressSanitizerModule::createInitializerPoisonCalls(
532 Module &M, Value *FirstAddr, Value *LastAddr) {
533 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
534 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
535 // If that function is not present, this TU contains no globals, or they have
536 // all been optimized away
540 // Set up the arguments to our poison/unpoison functions.
541 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
543 // Declare our poisoning and unpoisoning functions.
544 Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
545 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
546 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
547 Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
548 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
549 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
551 // Add a call to poison all external globals before the given function starts.
552 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
554 // Add calls to unpoison all globals before each return instruction.
555 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
557 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
558 CallInst::Create(AsanUnpoisonGlobals, "", RI);
563 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
564 Type *Ty = cast<PointerType>(G->getType())->getElementType();
565 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
567 if (BL->isIn(*G)) return false;
568 if (!Ty->isSized()) return false;
569 if (!G->hasInitializer()) return false;
570 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
571 // Touch only those globals that will not be defined in other modules.
572 // Don't handle ODR type linkages since other modules may be built w/o asan.
573 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
574 G->getLinkage() != GlobalVariable::PrivateLinkage &&
575 G->getLinkage() != GlobalVariable::InternalLinkage)
577 // Two problems with thread-locals:
578 // - The address of the main thread's copy can't be computed at link-time.
579 // - Need to poison all copies, not just the main thread's one.
580 if (G->isThreadLocal())
582 // For now, just ignore this Alloca if the alignment is large.
583 if (G->getAlignment() > RedzoneSize()) return false;
585 // Ignore all the globals with the names starting with "\01L_OBJC_".
586 // Many of those are put into the .cstring section. The linker compresses
587 // that section by removing the spare \0s after the string terminator, so
588 // our redzones get broken.
589 if ((G->getName().find("\01L_OBJC_") == 0) ||
590 (G->getName().find("\01l_OBJC_") == 0)) {
591 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
595 if (G->hasSection()) {
596 StringRef Section(G->getSection());
597 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
598 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
600 if ((Section.find("__OBJC,") == 0) ||
601 (Section.find("__DATA, __objc_") == 0)) {
602 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
605 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
606 // Constant CFString instances are compiled in the following way:
607 // -- the string buffer is emitted into
608 // __TEXT,__cstring,cstring_literals
609 // -- the constant NSConstantString structure referencing that buffer
610 // is placed into __DATA,__cfstring
611 // Therefore there's no point in placing redzones into __DATA,__cfstring.
612 // Moreover, it causes the linker to crash on OS X 10.7
613 if (Section.find("__DATA,__cfstring") == 0) {
614 DEBUG(dbgs() << "Ignoring CFString: " << *G);
622 // This function replaces all global variables with new variables that have
623 // trailing redzones. It also creates a function that poisons
624 // redzones and inserts this function into llvm.global_ctors.
625 bool AddressSanitizerModule::runOnModule(Module &M) {
626 if (!ClGlobals) return false;
627 TD = getAnalysisIfAvailable<DataLayout>();
630 BL.reset(new BlackList(BlacklistFile));
631 if (BL->isIn(M)) return false;
632 DynamicallyInitializedGlobals.Init(M);
633 C = &(M.getContext());
634 IntptrTy = Type::getIntNTy(*C, TD->getPointerSizeInBits());
636 SmallVector<GlobalVariable *, 16> GlobalsToChange;
638 for (Module::GlobalListType::iterator G = M.global_begin(),
639 E = M.global_end(); G != E; ++G) {
640 if (ShouldInstrumentGlobal(G))
641 GlobalsToChange.push_back(G);
644 size_t n = GlobalsToChange.size();
645 if (n == 0) return false;
647 // A global is described by a structure
650 // size_t size_with_redzone;
652 // size_t has_dynamic_init;
653 // We initialize an array of such structures and pass it to a run-time call.
654 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
657 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
660 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
662 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
664 // The addresses of the first and last dynamically initialized globals in
665 // this TU. Used in initialization order checking.
666 Value *FirstDynamic = 0, *LastDynamic = 0;
668 for (size_t i = 0; i < n; i++) {
669 GlobalVariable *G = GlobalsToChange[i];
670 PointerType *PtrTy = cast<PointerType>(G->getType());
671 Type *Ty = PtrTy->getElementType();
672 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
673 size_t RZ = RedzoneSize();
674 uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
675 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
676 // Determine whether this global should be poisoned in initialization.
677 bool GlobalHasDynamicInitializer =
678 DynamicallyInitializedGlobals.Contains(G);
679 // Don't check initialization order if this global is blacklisted.
680 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
682 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
683 Constant *NewInitializer = ConstantStruct::get(
684 NewTy, G->getInitializer(),
685 Constant::getNullValue(RightRedZoneTy), NULL);
687 SmallString<2048> DescriptionOfGlobal = G->getName();
688 DescriptionOfGlobal += " (";
689 DescriptionOfGlobal += M.getModuleIdentifier();
690 DescriptionOfGlobal += ")";
691 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
693 // Create a new global variable with enough space for a redzone.
694 GlobalVariable *NewGlobal = new GlobalVariable(
695 M, NewTy, G->isConstant(), G->getLinkage(),
696 NewInitializer, "", G, G->getThreadLocalMode());
697 NewGlobal->copyAttributesFrom(G);
698 NewGlobal->setAlignment(RZ);
701 Indices2[0] = IRB.getInt32(0);
702 Indices2[1] = IRB.getInt32(0);
704 G->replaceAllUsesWith(
705 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
706 NewGlobal->takeName(G);
707 G->eraseFromParent();
709 Initializers[i] = ConstantStruct::get(
711 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
712 ConstantInt::get(IntptrTy, SizeInBytes),
713 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
714 ConstantExpr::getPointerCast(Name, IntptrTy),
715 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
718 // Populate the first and last globals declared in this TU.
719 if (CheckInitOrder && GlobalHasDynamicInitializer) {
720 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
721 if (FirstDynamic == 0)
722 FirstDynamic = LastDynamic;
725 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
728 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
729 GlobalVariable *AllGlobals = new GlobalVariable(
730 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
731 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
733 // Create calls for poisoning before initializers run and unpoisoning after.
734 if (CheckInitOrder && FirstDynamic && LastDynamic)
735 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
737 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
738 kAsanRegisterGlobalsName, IRB.getVoidTy(),
739 IntptrTy, IntptrTy, NULL));
740 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
742 IRB.CreateCall2(AsanRegisterGlobals,
743 IRB.CreatePointerCast(AllGlobals, IntptrTy),
744 ConstantInt::get(IntptrTy, n));
746 // We also need to unregister globals at the end, e.g. when a shared library
748 Function *AsanDtorFunction = Function::Create(
749 FunctionType::get(Type::getVoidTy(*C), false),
750 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
751 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
752 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
753 Function *AsanUnregisterGlobals =
754 checkInterfaceFunction(M.getOrInsertFunction(
755 kAsanUnregisterGlobalsName,
756 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
757 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
759 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
760 IRB.CreatePointerCast(AllGlobals, IntptrTy),
761 ConstantInt::get(IntptrTy, n));
762 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
768 void AddressSanitizer::initializeCallbacks(Module &M) {
770 // Create __asan_report* callbacks.
771 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
772 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
774 // IsWrite and TypeSize are encoded in the function name.
775 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
776 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
777 // If we are merging crash callbacks, they have two parameters.
778 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
779 checkInterfaceFunction(M.getOrInsertFunction(
780 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
784 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
785 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
786 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
787 kAsanStackFreeName, IRB.getVoidTy(),
788 IntptrTy, IntptrTy, IntptrTy, NULL));
789 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
790 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
792 // We insert an empty inline asm after __asan_report* to avoid callback merge.
793 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
794 StringRef(""), StringRef(""),
795 /*hasSideEffects=*/true);
799 bool AddressSanitizer::doInitialization(Module &M) {
800 // Initialize the private fields. No one has accessed them before.
801 TD = getAnalysisIfAvailable<DataLayout>();
805 BL.reset(new BlackList(BlacklistFile));
806 DynamicallyInitializedGlobals.Init(M);
808 C = &(M.getContext());
809 LongSize = TD->getPointerSizeInBits();
810 IntptrTy = Type::getIntNTy(*C, LongSize);
811 IntptrPtrTy = PointerType::get(IntptrTy, 0);
813 AsanCtorFunction = Function::Create(
814 FunctionType::get(Type::getVoidTy(*C), false),
815 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
816 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
817 // call __asan_init in the module ctor.
818 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
819 AsanInitFunction = checkInterfaceFunction(
820 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
821 AsanInitFunction->setLinkage(Function::ExternalLinkage);
822 IRB.CreateCall(AsanInitFunction);
824 llvm::Triple targetTriple(M.getTargetTriple());
825 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
827 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
828 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
829 if (ClMappingOffsetLog >= 0) {
830 if (ClMappingOffsetLog == 0) {
834 MappingOffset = 1ULL << ClMappingOffsetLog;
839 if (ClMappingOffsetLog >= 0) {
840 // Tell the run-time the current values of mapping offset and scale.
841 GlobalValue *asan_mapping_offset =
842 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
843 ConstantInt::get(IntptrTy, MappingOffset),
844 kAsanMappingOffsetName);
845 // Read the global, otherwise it may be optimized away.
846 IRB.CreateLoad(asan_mapping_offset, true);
848 if (ClMappingScale) {
849 GlobalValue *asan_mapping_scale =
850 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
851 ConstantInt::get(IntptrTy, MappingScale()),
852 kAsanMappingScaleName);
853 // Read the global, otherwise it may be optimized away.
854 IRB.CreateLoad(asan_mapping_scale, true);
857 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
862 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
863 // For each NSObject descendant having a +load method, this method is invoked
864 // by the ObjC runtime before any of the static constructors is called.
865 // Therefore we need to instrument such methods with a call to __asan_init
866 // at the beginning in order to initialize our runtime before any access to
867 // the shadow memory.
868 // We cannot just ignore these methods, because they may call other
869 // instrumented functions.
870 if (F.getName().find(" load]") != std::string::npos) {
871 IRBuilder<> IRB(F.begin()->begin());
872 IRB.CreateCall(AsanInitFunction);
878 bool AddressSanitizer::runOnFunction(Function &F) {
879 if (BL->isIn(F)) return false;
880 if (&F == AsanCtorFunction) return false;
881 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
882 initializeCallbacks(*F.getParent());
884 // If needed, insert __asan_init before checking for AddressSafety attr.
885 maybeInsertAsanInitAtFunctionEntry(F);
887 if (!F.getFnAttributes().hasAttribute(Attributes::AddressSafety))
890 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
893 // We want to instrument every address only once per basic block (unless there
894 // are calls between uses).
895 SmallSet<Value*, 16> TempsToInstrument;
896 SmallVector<Instruction*, 16> ToInstrument;
897 SmallVector<Instruction*, 8> NoReturnCalls;
900 // Fill the set of memory operations to instrument.
901 for (Function::iterator FI = F.begin(), FE = F.end();
903 TempsToInstrument.clear();
904 int NumInsnsPerBB = 0;
905 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
907 if (LooksLikeCodeInBug11395(BI)) return false;
908 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
909 if (ClOpt && ClOptSameTemp) {
910 if (!TempsToInstrument.insert(Addr))
911 continue; // We've seen this temp in the current BB.
913 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
916 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
918 TempsToInstrument.clear();
919 if (CI->doesNotReturn()) {
920 NoReturnCalls.push_back(CI);
925 ToInstrument.push_back(BI);
927 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
933 int NumInstrumented = 0;
934 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
935 Instruction *Inst = ToInstrument[i];
936 if (ClDebugMin < 0 || ClDebugMax < 0 ||
937 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
938 if (isInterestingMemoryAccess(Inst, &IsWrite))
941 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
946 bool ChangedStack = poisonStackInFunction(F);
948 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
949 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
950 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
951 Instruction *CI = NoReturnCalls[i];
953 IRB.CreateCall(AsanHandleNoReturnFunc);
955 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
957 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
960 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
961 if (ShadowRedzoneSize == 1) return PoisonByte;
962 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
963 if (ShadowRedzoneSize == 4)
964 return (PoisonByte << 24) + (PoisonByte << 16) +
965 (PoisonByte << 8) + (PoisonByte);
966 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
969 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
972 size_t ShadowGranularity,
974 for (size_t i = 0; i < RZSize;
975 i+= ShadowGranularity, Shadow++) {
976 if (i + ShadowGranularity <= Size) {
977 *Shadow = 0; // fully addressable
978 } else if (i >= Size) {
979 *Shadow = Magic; // unaddressable
981 *Shadow = Size - i; // first Size-i bytes are addressable
986 void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
988 Value *ShadowBase, bool DoPoison) {
989 size_t ShadowRZSize = RedzoneSize() >> MappingScale();
990 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
991 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
992 Type *RZPtrTy = PointerType::get(RZTy, 0);
994 Value *PoisonLeft = ConstantInt::get(RZTy,
995 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
996 Value *PoisonMid = ConstantInt::get(RZTy,
997 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
998 Value *PoisonRight = ConstantInt::get(RZTy,
999 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1001 // poison the first red zone.
1002 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1004 // poison all other red zones.
1005 uint64_t Pos = RedzoneSize();
1006 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1007 AllocaInst *AI = AllocaVec[i];
1008 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1009 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1010 assert(AlignedSize - SizeInBytes < RedzoneSize());
1015 assert(ShadowBase->getType() == IntptrTy);
1016 if (SizeInBytes < AlignedSize) {
1017 // Poison the partial redzone at right
1018 Ptr = IRB.CreateAdd(
1019 ShadowBase, ConstantInt::get(IntptrTy,
1020 (Pos >> MappingScale()) - ShadowRZSize));
1021 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1022 uint32_t Poison = 0;
1024 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1026 1ULL << MappingScale(),
1027 kAsanStackPartialRedzoneMagic);
1029 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1030 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1033 // Poison the full redzone at right.
1034 Ptr = IRB.CreateAdd(ShadowBase,
1035 ConstantInt::get(IntptrTy, Pos >> MappingScale()));
1036 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
1037 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1039 Pos += RedzoneSize();
1043 // Workaround for bug 11395: we don't want to instrument stack in functions
1044 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1045 // FIXME: remove once the bug 11395 is fixed.
1046 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1047 if (LongSize != 32) return false;
1048 CallInst *CI = dyn_cast<CallInst>(I);
1049 if (!CI || !CI->isInlineAsm()) return false;
1050 if (CI->getNumArgOperands() <= 5) return false;
1051 // We have inline assembly with quite a few arguments.
1055 // Find all static Alloca instructions and put
1056 // poisoned red zones around all of them.
1057 // Then unpoison everything back before the function returns.
1059 // Stack poisoning does not play well with exception handling.
1060 // When an exception is thrown, we essentially bypass the code
1061 // that unpoisones the stack. This is why the run-time library has
1062 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1063 // stack in the interceptor. This however does not work inside the
1064 // actual function which catches the exception. Most likely because the
1065 // compiler hoists the load of the shadow value somewhere too high.
1066 // This causes asan to report a non-existing bug on 453.povray.
1067 // It sounds like an LLVM bug.
1068 bool AddressSanitizer::poisonStackInFunction(Function &F) {
1069 if (!ClStack) return false;
1070 SmallVector<AllocaInst*, 16> AllocaVec;
1071 SmallVector<Instruction*, 8> RetVec;
1072 uint64_t TotalSize = 0;
1074 // Filter out Alloca instructions we want (and can) handle.
1075 // Collect Ret instructions.
1076 for (Function::iterator FI = F.begin(), FE = F.end();
1078 BasicBlock &BB = *FI;
1079 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1081 if (isa<ReturnInst>(BI)) {
1082 RetVec.push_back(BI);
1086 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1088 if (AI->isArrayAllocation()) continue;
1089 if (!AI->isStaticAlloca()) continue;
1090 if (!AI->getAllocatedType()->isSized()) continue;
1091 if (AI->getAlignment() > RedzoneSize()) continue;
1092 AllocaVec.push_back(AI);
1093 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1094 TotalSize += AlignedSize;
1098 if (AllocaVec.empty()) return false;
1100 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize();
1102 bool DoStackMalloc = CheckUseAfterReturn
1103 && LocalStackSize <= kMaxStackMallocSize;
1105 Instruction *InsBefore = AllocaVec[0];
1106 IRBuilder<> IRB(InsBefore);
1109 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1110 AllocaInst *MyAlloca =
1111 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1112 MyAlloca->setAlignment(RedzoneSize());
1113 assert(MyAlloca->isStaticAlloca());
1114 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1115 Value *LocalStackBase = OrigStackBase;
1117 if (DoStackMalloc) {
1118 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1119 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1122 // This string will be parsed by the run-time (DescribeStackAddress).
1123 SmallString<2048> StackDescriptionStorage;
1124 raw_svector_ostream StackDescription(StackDescriptionStorage);
1125 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1127 uint64_t Pos = RedzoneSize();
1128 // Replace Alloca instructions with base+offset.
1129 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1130 AllocaInst *AI = AllocaVec[i];
1131 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1132 StringRef Name = AI->getName();
1133 StackDescription << Pos << " " << SizeInBytes << " "
1134 << Name.size() << " " << Name << " ";
1135 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1136 assert((AlignedSize % RedzoneSize()) == 0);
1137 AI->replaceAllUsesWith(
1139 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1141 Pos += AlignedSize + RedzoneSize();
1143 assert(Pos == LocalStackSize);
1145 // Write the Magic value and the frame description constant to the redzone.
1146 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1147 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1149 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1150 ConstantInt::get(IntptrTy, LongSize/8));
1151 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
1152 GlobalVariable *StackDescriptionGlobal =
1153 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
1154 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
1155 IRB.CreateStore(Description, BasePlus1);
1157 // Poison the stack redzones at the entry.
1158 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1159 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1161 // Unpoison the stack before all ret instructions.
1162 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1163 Instruction *Ret = RetVec[i];
1164 IRBuilder<> IRBRet(Ret);
1166 // Mark the current frame as retired.
1167 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1169 // Unpoison the stack.
1170 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1172 if (DoStackMalloc) {
1173 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1174 ConstantInt::get(IntptrTy, LocalStackSize),
1179 // We are done. Remove the old unused alloca instructions.
1180 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1181 AllocaVec[i]->eraseFromParent();