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