Change the linkage of these global values to 'internal'.
[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 "llvm/Transforms/Instrumentation.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/OwningPtr.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/InstVisitor.h"
38 #include "llvm/Support/CallSite.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/DataTypes.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Endian.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/system_error.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Cloning.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Transforms/Utils/ModuleUtils.h"
49 #include "llvm/Transforms/Utils/SpecialCaseList.h"
50 #include <algorithm>
51 #include <string>
52
53 using namespace llvm;
54
55 static const uint64_t kDefaultShadowScale = 3;
56 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
57 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
58 static const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000;  // < 2G.
59 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
60 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
61
62 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
63 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
64 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
65
66 static const char *const kAsanModuleCtorName = "asan.module_ctor";
67 static const char *const kAsanModuleDtorName = "asan.module_dtor";
68 static const int         kAsanCtorAndCtorPriority = 1;
69 static const char *const kAsanReportErrorTemplate = "__asan_report_";
70 static const char *const kAsanReportLoadN = "__asan_report_load_n";
71 static const char *const kAsanReportStoreN = "__asan_report_store_n";
72 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
73 static const char *const kAsanUnregisterGlobalsName =
74     "__asan_unregister_globals";
75 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
76 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
77 static const char *const kAsanInitName = "__asan_init_v3";
78 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
79 static const char *const kAsanMappingOffsetName = "__asan_mapping_offset";
80 static const char *const kAsanMappingScaleName = "__asan_mapping_scale";
81 static const char *const kAsanStackMallocName = "__asan_stack_malloc";
82 static const char *const kAsanStackFreeName = "__asan_stack_free";
83 static const char *const kAsanGenPrefix = "__asan_gen_";
84 static const char *const kAsanPoisonStackMemoryName =
85     "__asan_poison_stack_memory";
86 static const char *const kAsanUnpoisonStackMemoryName =
87     "__asan_unpoison_stack_memory";
88
89 static const int kAsanStackLeftRedzoneMagic = 0xf1;
90 static const int kAsanStackMidRedzoneMagic = 0xf2;
91 static const int kAsanStackRightRedzoneMagic = 0xf3;
92 static const int kAsanStackPartialRedzoneMagic = 0xf4;
93
94 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
95 static const size_t kNumberOfAccessSizes = 5;
96
97 // Command-line flags.
98
99 // This flag may need to be replaced with -f[no-]asan-reads.
100 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
101        cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
102 static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
103        cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
104 static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
105        cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
106        cl::Hidden, cl::init(true));
107 static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
108        cl::desc("use instrumentation with slow path for all accesses"),
109        cl::Hidden, cl::init(false));
110 // This flag limits the number of instructions to be instrumented
111 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
112 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
113 // set it to 10000.
114 static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
115        cl::init(10000),
116        cl::desc("maximal number of instructions to instrument in any given BB"),
117        cl::Hidden);
118 // This flag may need to be replaced with -f[no]asan-stack.
119 static cl::opt<bool> ClStack("asan-stack",
120        cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
121 // This flag may need to be replaced with -f[no]asan-use-after-return.
122 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
123        cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
124 // This flag may need to be replaced with -f[no]asan-globals.
125 static cl::opt<bool> ClGlobals("asan-globals",
126        cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
127 static cl::opt<bool> ClInitializers("asan-initialization-order",
128        cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
129 static cl::opt<bool> ClMemIntrin("asan-memintrin",
130        cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
131 static cl::opt<bool> ClRealignStack("asan-realign-stack",
132        cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
133 static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
134        cl::desc("File containing the list of objects to ignore "
135                 "during instrumentation"), cl::Hidden);
136
137 // This is an experimental feature that will allow to choose between
138 // instrumented and non-instrumented code at link-time.
139 // If this option is on, just before instrumenting a function we create its
140 // clone; if the function is not changed by asan the clone is deleted.
141 // If we end up with a clone, we put the instrumented function into a section
142 // called "ASAN" and the uninstrumented function into a section called "NOASAN".
143 //
144 // This is still a prototype, we need to figure out a way to keep two copies of
145 // a function so that the linker can easily choose one of them.
146 static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
147        cl::desc("Keep uninstrumented copies of functions"),
148        cl::Hidden, cl::init(false));
149
150 // These flags allow to change the shadow mapping.
151 // The shadow mapping looks like
152 //    Shadow = (Mem >> scale) + (1 << offset_log)
153 static cl::opt<int> ClMappingScale("asan-mapping-scale",
154        cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
155 static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
156        cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
157 static cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
158        cl::desc("Use short immediate constant as the mapping offset for 64bit"),
159        cl::Hidden, cl::init(true));
160
161 // Optimization flags. Not user visible, used mostly for testing
162 // and benchmarking the tool.
163 static cl::opt<bool> ClOpt("asan-opt",
164        cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
165 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
166        cl::desc("Instrument the same temp just once"), cl::Hidden,
167        cl::init(true));
168 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
169        cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
170
171 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
172        cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
173        cl::Hidden, cl::init(false));
174
175 // Debug flags.
176 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
177                             cl::init(0));
178 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
179                                  cl::Hidden, cl::init(0));
180 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
181                                         cl::Hidden, cl::desc("Debug func"));
182 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
183                                cl::Hidden, cl::init(-1));
184 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
185                                cl::Hidden, cl::init(-1));
186
187 namespace {
188 /// A set of dynamically initialized globals extracted from metadata.
189 class SetOfDynamicallyInitializedGlobals {
190  public:
191   void Init(Module& M) {
192     // Clang generates metadata identifying all dynamically initialized globals.
193     NamedMDNode *DynamicGlobals =
194         M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
195     if (!DynamicGlobals)
196       return;
197     for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
198       MDNode *MDN = DynamicGlobals->getOperand(i);
199       assert(MDN->getNumOperands() == 1);
200       Value *VG = MDN->getOperand(0);
201       // The optimizer may optimize away a global entirely, in which case we
202       // cannot instrument access to it.
203       if (!VG)
204         continue;
205       DynInitGlobals.insert(cast<GlobalVariable>(VG));
206     }
207   }
208   bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
209  private:
210   SmallSet<GlobalValue*, 32> DynInitGlobals;
211 };
212
213 /// This struct defines the shadow mapping using the rule:
214 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
215 struct ShadowMapping {
216   int Scale;
217   uint64_t Offset;
218   bool OrShadowOffset;
219 };
220
221 static ShadowMapping getShadowMapping(const Module &M, int LongSize,
222                                       bool ZeroBaseShadow) {
223   llvm::Triple TargetTriple(M.getTargetTriple());
224   bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
225   bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
226   bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
227                  TargetTriple.getArch() == llvm::Triple::ppc64le;
228   bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
229   bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
230                   TargetTriple.getArch() == llvm::Triple::mipsel;
231
232   ShadowMapping Mapping;
233
234   // OR-ing shadow offset if more efficient (at least on x86),
235   // but on ppc64 we have to use add since the shadow offset is not neccesary
236   // 1/8-th of the address space.
237   Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
238
239   Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
240       (LongSize == 32 ?
241        (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
242        IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
243   if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
244     assert(LongSize == 64);
245     Mapping.Offset = kDefaultShort64bitShadowOffset;
246   }
247   if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
248     // Zero offset log is the special case.
249     Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
250   }
251
252   Mapping.Scale = kDefaultShadowScale;
253   if (ClMappingScale) {
254     Mapping.Scale = ClMappingScale;
255   }
256
257   return Mapping;
258 }
259
260 static size_t RedzoneSizeForScale(int MappingScale) {
261   // Redzone used for stack and globals is at least 32 bytes.
262   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
263   return std::max(32U, 1U << MappingScale);
264 }
265
266 /// AddressSanitizer: instrument the code in module to find memory bugs.
267 struct AddressSanitizer : public FunctionPass {
268   AddressSanitizer(bool CheckInitOrder = true,
269                    bool CheckUseAfterReturn = false,
270                    bool CheckLifetime = false,
271                    StringRef BlacklistFile = StringRef(),
272                    bool ZeroBaseShadow = false)
273       : FunctionPass(ID),
274         CheckInitOrder(CheckInitOrder || ClInitializers),
275         CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
276         CheckLifetime(CheckLifetime || ClCheckLifetime),
277         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
278                                             : BlacklistFile),
279         ZeroBaseShadow(ZeroBaseShadow) {}
280   virtual const char *getPassName() const {
281     return "AddressSanitizerFunctionPass";
282   }
283   void instrumentMop(Instruction *I);
284   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
285                          Value *Addr, uint32_t TypeSize, bool IsWrite,
286                          Value *SizeArgument);
287   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
288                            Value *ShadowValue, uint32_t TypeSize);
289   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
290                                  bool IsWrite, size_t AccessSizeIndex,
291                                  Value *SizeArgument);
292   bool instrumentMemIntrinsic(MemIntrinsic *MI);
293   void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
294                                    Value *Size,
295                                    Instruction *InsertBefore, bool IsWrite);
296   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
297   bool runOnFunction(Function &F);
298   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
299   void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
300   virtual bool doInitialization(Module &M);
301   static char ID;  // Pass identification, replacement for typeid
302
303  private:
304   void initializeCallbacks(Module &M);
305
306   bool ShouldInstrumentGlobal(GlobalVariable *G);
307   bool LooksLikeCodeInBug11395(Instruction *I);
308   void FindDynamicInitializers(Module &M);
309
310   bool CheckInitOrder;
311   bool CheckUseAfterReturn;
312   bool CheckLifetime;
313   SmallString<64> BlacklistFile;
314   bool ZeroBaseShadow;
315
316   LLVMContext *C;
317   DataLayout *TD;
318   int LongSize;
319   Type *IntptrTy;
320   ShadowMapping Mapping;
321   Function *AsanCtorFunction;
322   Function *AsanInitFunction;
323   Function *AsanHandleNoReturnFunc;
324   OwningPtr<SpecialCaseList> BL;
325   // This array is indexed by AccessIsWrite and log2(AccessSize).
326   Function *AsanErrorCallback[2][kNumberOfAccessSizes];
327   // This array is indexed by AccessIsWrite.
328   Function *AsanErrorCallbackSized[2];
329   InlineAsm *EmptyAsm;
330   SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
331
332   friend struct FunctionStackPoisoner;
333 };
334
335 class AddressSanitizerModule : public ModulePass {
336  public:
337   AddressSanitizerModule(bool CheckInitOrder = true,
338                          StringRef BlacklistFile = StringRef(),
339                          bool ZeroBaseShadow = false)
340       : ModulePass(ID),
341         CheckInitOrder(CheckInitOrder || ClInitializers),
342         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
343                                             : BlacklistFile),
344         ZeroBaseShadow(ZeroBaseShadow) {}
345   bool runOnModule(Module &M);
346   static char ID;  // Pass identification, replacement for typeid
347   virtual const char *getPassName() const {
348     return "AddressSanitizerModule";
349   }
350
351  private:
352   void initializeCallbacks(Module &M);
353
354   bool ShouldInstrumentGlobal(GlobalVariable *G);
355   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
356   size_t RedzoneSize() const {
357     return RedzoneSizeForScale(Mapping.Scale);
358   }
359
360   bool CheckInitOrder;
361   SmallString<64> BlacklistFile;
362   bool ZeroBaseShadow;
363
364   OwningPtr<SpecialCaseList> BL;
365   SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
366   Type *IntptrTy;
367   LLVMContext *C;
368   DataLayout *TD;
369   ShadowMapping Mapping;
370   Function *AsanPoisonGlobals;
371   Function *AsanUnpoisonGlobals;
372   Function *AsanRegisterGlobals;
373   Function *AsanUnregisterGlobals;
374 };
375
376 // Stack poisoning does not play well with exception handling.
377 // When an exception is thrown, we essentially bypass the code
378 // that unpoisones the stack. This is why the run-time library has
379 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
380 // stack in the interceptor. This however does not work inside the
381 // actual function which catches the exception. Most likely because the
382 // compiler hoists the load of the shadow value somewhere too high.
383 // This causes asan to report a non-existing bug on 453.povray.
384 // It sounds like an LLVM bug.
385 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
386   Function &F;
387   AddressSanitizer &ASan;
388   DIBuilder DIB;
389   LLVMContext *C;
390   Type *IntptrTy;
391   Type *IntptrPtrTy;
392   ShadowMapping Mapping;
393
394   SmallVector<AllocaInst*, 16> AllocaVec;
395   SmallVector<Instruction*, 8> RetVec;
396   uint64_t TotalStackSize;
397   unsigned StackAlignment;
398
399   Function *AsanStackMallocFunc, *AsanStackFreeFunc;
400   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
401
402   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
403   struct AllocaPoisonCall {
404     IntrinsicInst *InsBefore;
405     uint64_t Size;
406     bool DoPoison;
407   };
408   SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
409
410   // Maps Value to an AllocaInst from which the Value is originated.
411   typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
412   AllocaForValueMapTy AllocaForValue;
413
414   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
415       : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
416         IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
417         Mapping(ASan.Mapping),
418         TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
419
420   bool runOnFunction() {
421     if (!ClStack) return false;
422     // Collect alloca, ret, lifetime instructions etc.
423     for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
424          DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
425       BasicBlock *BB = *DI;
426       visit(*BB);
427     }
428     if (AllocaVec.empty()) return false;
429
430     initializeCallbacks(*F.getParent());
431
432     poisonStack();
433
434     if (ClDebugStack) {
435       DEBUG(dbgs() << F);
436     }
437     return true;
438   }
439
440   // Finds all static Alloca instructions and puts
441   // poisoned red zones around all of them.
442   // Then unpoison everything back before the function returns.
443   void poisonStack();
444
445   // ----------------------- Visitors.
446   /// \brief Collect all Ret instructions.
447   void visitReturnInst(ReturnInst &RI) {
448     RetVec.push_back(&RI);
449   }
450
451   /// \brief Collect Alloca instructions we want (and can) handle.
452   void visitAllocaInst(AllocaInst &AI) {
453     if (!isInterestingAlloca(AI)) return;
454
455     StackAlignment = std::max(StackAlignment, AI.getAlignment());
456     AllocaVec.push_back(&AI);
457     uint64_t AlignedSize = getAlignedAllocaSize(&AI);
458     TotalStackSize += AlignedSize;
459   }
460
461   /// \brief Collect lifetime intrinsic calls to check for use-after-scope
462   /// errors.
463   void visitIntrinsicInst(IntrinsicInst &II) {
464     if (!ASan.CheckLifetime) return;
465     Intrinsic::ID ID = II.getIntrinsicID();
466     if (ID != Intrinsic::lifetime_start &&
467         ID != Intrinsic::lifetime_end)
468       return;
469     // Found lifetime intrinsic, add ASan instrumentation if necessary.
470     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
471     // If size argument is undefined, don't do anything.
472     if (Size->isMinusOne()) return;
473     // Check that size doesn't saturate uint64_t and can
474     // be stored in IntptrTy.
475     const uint64_t SizeValue = Size->getValue().getLimitedValue();
476     if (SizeValue == ~0ULL ||
477         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
478       return;
479     // Find alloca instruction that corresponds to llvm.lifetime argument.
480     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
481     if (!AI) return;
482     bool DoPoison = (ID == Intrinsic::lifetime_end);
483     AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
484     AllocaPoisonCallVec.push_back(APC);
485   }
486
487   // ---------------------- Helpers.
488   void initializeCallbacks(Module &M);
489
490   // Check if we want (and can) handle this alloca.
491   bool isInterestingAlloca(AllocaInst &AI) {
492     return (!AI.isArrayAllocation() &&
493             AI.isStaticAlloca() &&
494             AI.getAlignment() <= RedzoneSize() &&
495             AI.getAllocatedType()->isSized());
496   }
497
498   size_t RedzoneSize() const {
499     return RedzoneSizeForScale(Mapping.Scale);
500   }
501   uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
502     Type *Ty = AI->getAllocatedType();
503     uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
504     return SizeInBytes;
505   }
506   uint64_t getAlignedSize(uint64_t SizeInBytes) {
507     size_t RZ = RedzoneSize();
508     return ((SizeInBytes + RZ - 1) / RZ) * RZ;
509   }
510   uint64_t getAlignedAllocaSize(AllocaInst *AI) {
511     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
512     return getAlignedSize(SizeInBytes);
513   }
514   /// Finds alloca where the value comes from.
515   AllocaInst *findAllocaForValue(Value *V);
516   void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
517                       Value *ShadowBase, bool DoPoison);
518   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
519 };
520
521 }  // namespace
522
523 char AddressSanitizer::ID = 0;
524 INITIALIZE_PASS(AddressSanitizer, "asan",
525     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
526     false, false)
527 FunctionPass *llvm::createAddressSanitizerFunctionPass(
528     bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
529     StringRef BlacklistFile, bool ZeroBaseShadow) {
530   return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
531                               CheckLifetime, BlacklistFile, ZeroBaseShadow);
532 }
533
534 char AddressSanitizerModule::ID = 0;
535 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
536     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
537     "ModulePass", false, false)
538 ModulePass *llvm::createAddressSanitizerModulePass(
539     bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
540   return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
541                                     ZeroBaseShadow);
542 }
543
544 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
545   size_t Res = countTrailingZeros(TypeSize / 8);
546   assert(Res < kNumberOfAccessSizes);
547   return Res;
548 }
549
550 // \brief Create a constant for Str so that we can pass it to the run-time lib.
551 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
552   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
553   GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
554                             GlobalValue::InternalLinkage, StrConst,
555                             kAsanGenPrefix);
556   GV->setUnnamedAddr(true);  // Ok to merge these.
557   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
558   return GV;
559 }
560
561 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
562   return G->getName().find(kAsanGenPrefix) == 0;
563 }
564
565 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
566   // Shadow >> scale
567   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
568   if (Mapping.Offset == 0)
569     return Shadow;
570   // (Shadow >> scale) | offset
571   if (Mapping.OrShadowOffset)
572     return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
573   else
574     return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
575 }
576
577 void AddressSanitizer::instrumentMemIntrinsicParam(
578     Instruction *OrigIns,
579     Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
580   IRBuilder<> IRB(InsertBefore);
581   if (Size->getType() != IntptrTy)
582     Size = IRB.CreateIntCast(Size, IntptrTy, false);
583   // Check the first byte.
584   instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
585   // Check the last byte.
586   IRB.SetInsertPoint(InsertBefore);
587   Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
588   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
589   Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
590   instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
591 }
592
593 // Instrument memset/memmove/memcpy
594 bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
595   Value *Dst = MI->getDest();
596   MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
597   Value *Src = MemTran ? MemTran->getSource() : 0;
598   Value *Length = MI->getLength();
599
600   Constant *ConstLength = dyn_cast<Constant>(Length);
601   Instruction *InsertBefore = MI;
602   if (ConstLength) {
603     if (ConstLength->isNullValue()) return false;
604   } else {
605     // The size is not a constant so it could be zero -- check at run-time.
606     IRBuilder<> IRB(InsertBefore);
607
608     Value *Cmp = IRB.CreateICmpNE(Length,
609                                   Constant::getNullValue(Length->getType()));
610     InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
611   }
612
613   instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
614   if (Src)
615     instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
616   return true;
617 }
618
619 // If I is an interesting memory access, return the PointerOperand
620 // and set IsWrite. Otherwise return NULL.
621 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
622   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
623     if (!ClInstrumentReads) return NULL;
624     *IsWrite = false;
625     return LI->getPointerOperand();
626   }
627   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
628     if (!ClInstrumentWrites) return NULL;
629     *IsWrite = true;
630     return SI->getPointerOperand();
631   }
632   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
633     if (!ClInstrumentAtomics) return NULL;
634     *IsWrite = true;
635     return RMW->getPointerOperand();
636   }
637   if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
638     if (!ClInstrumentAtomics) return NULL;
639     *IsWrite = true;
640     return XCHG->getPointerOperand();
641   }
642   return NULL;
643 }
644
645 void AddressSanitizer::instrumentMop(Instruction *I) {
646   bool IsWrite = false;
647   Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
648   assert(Addr);
649   if (ClOpt && ClOptGlobals) {
650     if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
651       // If initialization order checking is disabled, a simple access to a
652       // dynamically initialized global is always valid.
653       if (!CheckInitOrder)
654         return;
655       // If a global variable does not have dynamic initialization we don't
656       // have to instrument it.  However, if a global does not have initailizer
657       // at all, we assume it has dynamic initializer (in other TU).
658       if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
659         return;
660     }
661   }
662
663   Type *OrigPtrTy = Addr->getType();
664   Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
665
666   assert(OrigTy->isSized());
667   uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
668
669   assert((TypeSize % 8) == 0);
670
671   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
672   if (TypeSize == 8  || TypeSize == 16 ||
673       TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
674     return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
675   // Instrument unusual size (but still multiple of 8).
676   // We can not do it with a single check, so we do 1-byte check for the first
677   // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
678   // to report the actual access size.
679   IRBuilder<> IRB(I);
680   Value *LastByte =  IRB.CreateIntToPtr(
681       IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
682                     ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
683       OrigPtrTy);
684   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
685   instrumentAddress(I, I, Addr, 8, IsWrite, Size);
686   instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
687 }
688
689 // Validate the result of Module::getOrInsertFunction called for an interface
690 // function of AddressSanitizer. If the instrumented module defines a function
691 // with the same name, their prototypes must match, otherwise
692 // getOrInsertFunction returns a bitcast.
693 static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
694   if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
695   FuncOrBitcast->dump();
696   report_fatal_error("trying to redefine an AddressSanitizer "
697                      "interface function");
698 }
699
700 Instruction *AddressSanitizer::generateCrashCode(
701     Instruction *InsertBefore, Value *Addr,
702     bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
703   IRBuilder<> IRB(InsertBefore);
704   CallInst *Call = SizeArgument
705     ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
706     : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
707
708   // We don't do Call->setDoesNotReturn() because the BB already has
709   // UnreachableInst at the end.
710   // This EmptyAsm is required to avoid callback merge.
711   IRB.CreateCall(EmptyAsm);
712   return Call;
713 }
714
715 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
716                                             Value *ShadowValue,
717                                             uint32_t TypeSize) {
718   size_t Granularity = 1 << Mapping.Scale;
719   // Addr & (Granularity - 1)
720   Value *LastAccessedByte = IRB.CreateAnd(
721       AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
722   // (Addr & (Granularity - 1)) + size - 1
723   if (TypeSize / 8 > 1)
724     LastAccessedByte = IRB.CreateAdd(
725         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
726   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
727   LastAccessedByte = IRB.CreateIntCast(
728       LastAccessedByte, ShadowValue->getType(), false);
729   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
730   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
731 }
732
733 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
734                                          Instruction *InsertBefore,
735                                          Value *Addr, uint32_t TypeSize,
736                                          bool IsWrite, Value *SizeArgument) {
737   IRBuilder<> IRB(InsertBefore);
738   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
739
740   Type *ShadowTy  = IntegerType::get(
741       *C, std::max(8U, TypeSize >> Mapping.Scale));
742   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
743   Value *ShadowPtr = memToShadow(AddrLong, IRB);
744   Value *CmpVal = Constant::getNullValue(ShadowTy);
745   Value *ShadowValue = IRB.CreateLoad(
746       IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
747
748   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
749   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
750   size_t Granularity = 1 << Mapping.Scale;
751   TerminatorInst *CrashTerm = 0;
752
753   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
754     TerminatorInst *CheckTerm =
755         SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
756     assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
757     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
758     IRB.SetInsertPoint(CheckTerm);
759     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
760     BasicBlock *CrashBlock =
761         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
762     CrashTerm = new UnreachableInst(*C, CrashBlock);
763     BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
764     ReplaceInstWithInst(CheckTerm, NewTerm);
765   } else {
766     CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
767   }
768
769   Instruction *Crash = generateCrashCode(
770       CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
771   Crash->setDebugLoc(OrigIns->getDebugLoc());
772 }
773
774 void AddressSanitizerModule::createInitializerPoisonCalls(
775     Module &M, GlobalValue *ModuleName) {
776   // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
777   Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
778   // If that function is not present, this TU contains no globals, or they have
779   // all been optimized away
780   if (!GlobalInit)
781     return;
782
783   // Set up the arguments to our poison/unpoison functions.
784   IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
785
786   // Add a call to poison all external globals before the given function starts.
787   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
788   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
789
790   // Add calls to unpoison all globals before each return instruction.
791   for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
792       I != E; ++I) {
793     if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
794       CallInst::Create(AsanUnpoisonGlobals, "", RI);
795     }
796   }
797 }
798
799 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
800   Type *Ty = cast<PointerType>(G->getType())->getElementType();
801   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
802
803   if (BL->isIn(*G)) return false;
804   if (!Ty->isSized()) return false;
805   if (!G->hasInitializer()) return false;
806   if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
807   // Touch only those globals that will not be defined in other modules.
808   // Don't handle ODR type linkages since other modules may be built w/o asan.
809   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
810       G->getLinkage() != GlobalVariable::PrivateLinkage &&
811       G->getLinkage() != GlobalVariable::InternalLinkage)
812     return false;
813   // Two problems with thread-locals:
814   //   - The address of the main thread's copy can't be computed at link-time.
815   //   - Need to poison all copies, not just the main thread's one.
816   if (G->isThreadLocal())
817     return false;
818   // For now, just ignore this Alloca if the alignment is large.
819   if (G->getAlignment() > RedzoneSize()) return false;
820
821   // Ignore all the globals with the names starting with "\01L_OBJC_".
822   // Many of those are put into the .cstring section. The linker compresses
823   // that section by removing the spare \0s after the string terminator, so
824   // our redzones get broken.
825   if ((G->getName().find("\01L_OBJC_") == 0) ||
826       (G->getName().find("\01l_OBJC_") == 0)) {
827     DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
828     return false;
829   }
830
831   if (G->hasSection()) {
832     StringRef Section(G->getSection());
833     // Ignore the globals from the __OBJC section. The ObjC runtime assumes
834     // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
835     // them.
836     if ((Section.find("__OBJC,") == 0) ||
837         (Section.find("__DATA, __objc_") == 0)) {
838       DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
839       return false;
840     }
841     // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
842     // Constant CFString instances are compiled in the following way:
843     //  -- the string buffer is emitted into
844     //     __TEXT,__cstring,cstring_literals
845     //  -- the constant NSConstantString structure referencing that buffer
846     //     is placed into __DATA,__cfstring
847     // Therefore there's no point in placing redzones into __DATA,__cfstring.
848     // Moreover, it causes the linker to crash on OS X 10.7
849     if (Section.find("__DATA,__cfstring") == 0) {
850       DEBUG(dbgs() << "Ignoring CFString: " << *G);
851       return false;
852     }
853   }
854
855   return true;
856 }
857
858 void AddressSanitizerModule::initializeCallbacks(Module &M) {
859   IRBuilder<> IRB(*C);
860   // Declare our poisoning and unpoisoning functions.
861   AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
862       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
863   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
864   AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
865       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
866   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
867   // Declare functions that register/unregister globals.
868   AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
869       kAsanRegisterGlobalsName, IRB.getVoidTy(),
870       IntptrTy, IntptrTy, NULL));
871   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
872   AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
873       kAsanUnregisterGlobalsName,
874       IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
875   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
876 }
877
878 // This function replaces all global variables with new variables that have
879 // trailing redzones. It also creates a function that poisons
880 // redzones and inserts this function into llvm.global_ctors.
881 bool AddressSanitizerModule::runOnModule(Module &M) {
882   if (!ClGlobals) return false;
883   TD = getAnalysisIfAvailable<DataLayout>();
884   if (!TD)
885     return false;
886   BL.reset(new SpecialCaseList(BlacklistFile));
887   if (BL->isIn(M)) return false;
888   C = &(M.getContext());
889   int LongSize = TD->getPointerSizeInBits();
890   IntptrTy = Type::getIntNTy(*C, LongSize);
891   Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
892   initializeCallbacks(M);
893   DynamicallyInitializedGlobals.Init(M);
894
895   SmallVector<GlobalVariable *, 16> GlobalsToChange;
896
897   for (Module::GlobalListType::iterator G = M.global_begin(),
898        E = M.global_end(); G != E; ++G) {
899     if (ShouldInstrumentGlobal(G))
900       GlobalsToChange.push_back(G);
901   }
902
903   size_t n = GlobalsToChange.size();
904   if (n == 0) return false;
905
906   // A global is described by a structure
907   //   size_t beg;
908   //   size_t size;
909   //   size_t size_with_redzone;
910   //   const char *name;
911   //   const char *module_name;
912   //   size_t has_dynamic_init;
913   // We initialize an array of such structures and pass it to a run-time call.
914   StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
915                                                IntptrTy, IntptrTy,
916                                                IntptrTy, IntptrTy, NULL);
917   SmallVector<Constant *, 16> Initializers(n), DynamicInit;
918
919
920   Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
921   assert(CtorFunc);
922   IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
923
924   bool HasDynamicallyInitializedGlobals = false;
925
926   GlobalVariable *ModuleName = createPrivateGlobalForString(
927       M, M.getModuleIdentifier());
928   // We shouldn't merge same module names, as this string serves as unique
929   // module ID in runtime.
930   ModuleName->setUnnamedAddr(false);
931
932   for (size_t i = 0; i < n; i++) {
933     static const uint64_t kMaxGlobalRedzone = 1 << 18;
934     GlobalVariable *G = GlobalsToChange[i];
935     PointerType *PtrTy = cast<PointerType>(G->getType());
936     Type *Ty = PtrTy->getElementType();
937     uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
938     uint64_t MinRZ = RedzoneSize();
939     // MinRZ <= RZ <= kMaxGlobalRedzone
940     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
941     uint64_t RZ = std::max(MinRZ,
942                          std::min(kMaxGlobalRedzone,
943                                   (SizeInBytes / MinRZ / 4) * MinRZ));
944     uint64_t RightRedzoneSize = RZ;
945     // Round up to MinRZ
946     if (SizeInBytes % MinRZ)
947       RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
948     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
949     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
950     // Determine whether this global should be poisoned in initialization.
951     bool GlobalHasDynamicInitializer =
952         DynamicallyInitializedGlobals.Contains(G);
953     // Don't check initialization order if this global is blacklisted.
954     GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
955
956     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
957     Constant *NewInitializer = ConstantStruct::get(
958         NewTy, G->getInitializer(),
959         Constant::getNullValue(RightRedZoneTy), NULL);
960
961     GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
962
963     // Create a new global variable with enough space for a redzone.
964     GlobalValue::LinkageTypes Linkage = G->getLinkage();
965     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
966       Linkage = GlobalValue::InternalLinkage;
967     GlobalVariable *NewGlobal = new GlobalVariable(
968         M, NewTy, G->isConstant(), Linkage,
969         NewInitializer, "", G, G->getThreadLocalMode());
970     NewGlobal->copyAttributesFrom(G);
971     NewGlobal->setAlignment(MinRZ);
972
973     Value *Indices2[2];
974     Indices2[0] = IRB.getInt32(0);
975     Indices2[1] = IRB.getInt32(0);
976
977     G->replaceAllUsesWith(
978         ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
979     NewGlobal->takeName(G);
980     G->eraseFromParent();
981
982     Initializers[i] = ConstantStruct::get(
983         GlobalStructTy,
984         ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
985         ConstantInt::get(IntptrTy, SizeInBytes),
986         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
987         ConstantExpr::getPointerCast(Name, IntptrTy),
988         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
989         ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
990         NULL);
991
992     // Populate the first and last globals declared in this TU.
993     if (CheckInitOrder && GlobalHasDynamicInitializer)
994       HasDynamicallyInitializedGlobals = true;
995
996     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
997   }
998
999   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1000   GlobalVariable *AllGlobals = new GlobalVariable(
1001       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1002       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1003
1004   // Create calls for poisoning before initializers run and unpoisoning after.
1005   if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1006     createInitializerPoisonCalls(M, ModuleName);
1007   IRB.CreateCall2(AsanRegisterGlobals,
1008                   IRB.CreatePointerCast(AllGlobals, IntptrTy),
1009                   ConstantInt::get(IntptrTy, n));
1010
1011   // We also need to unregister globals at the end, e.g. when a shared library
1012   // gets closed.
1013   Function *AsanDtorFunction = Function::Create(
1014       FunctionType::get(Type::getVoidTy(*C), false),
1015       GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1016   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1017   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1018   IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1019                        IRB.CreatePointerCast(AllGlobals, IntptrTy),
1020                        ConstantInt::get(IntptrTy, n));
1021   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1022
1023   DEBUG(dbgs() << M);
1024   return true;
1025 }
1026
1027 void AddressSanitizer::initializeCallbacks(Module &M) {
1028   IRBuilder<> IRB(*C);
1029   // Create __asan_report* callbacks.
1030   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1031     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1032          AccessSizeIndex++) {
1033       // IsWrite and TypeSize are encoded in the function name.
1034       std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1035           (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1036       // If we are merging crash callbacks, they have two parameters.
1037       AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1038           checkInterfaceFunction(M.getOrInsertFunction(
1039               FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
1040     }
1041   }
1042   AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1043               kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1044   AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1045               kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1046
1047   AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1048       kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1049   // We insert an empty inline asm after __asan_report* to avoid callback merge.
1050   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1051                             StringRef(""), StringRef(""),
1052                             /*hasSideEffects=*/true);
1053 }
1054
1055 void AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
1056   // Tell the values of mapping offset and scale to the run-time.
1057   GlobalValue *asan_mapping_offset =
1058       new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1059                      ConstantInt::get(IntptrTy, Mapping.Offset),
1060                      kAsanMappingOffsetName);
1061   // Read the global, otherwise it may be optimized away.
1062   IRB.CreateLoad(asan_mapping_offset, true);
1063
1064   GlobalValue *asan_mapping_scale =
1065       new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
1066                          ConstantInt::get(IntptrTy, Mapping.Scale),
1067                          kAsanMappingScaleName);
1068   // Read the global, otherwise it may be optimized away.
1069   IRB.CreateLoad(asan_mapping_scale, true);
1070 }
1071
1072 // virtual
1073 bool AddressSanitizer::doInitialization(Module &M) {
1074   // Initialize the private fields. No one has accessed them before.
1075   TD = getAnalysisIfAvailable<DataLayout>();
1076
1077   if (!TD)
1078     return false;
1079   BL.reset(new SpecialCaseList(BlacklistFile));
1080   DynamicallyInitializedGlobals.Init(M);
1081
1082   C = &(M.getContext());
1083   LongSize = TD->getPointerSizeInBits();
1084   IntptrTy = Type::getIntNTy(*C, LongSize);
1085
1086   AsanCtorFunction = Function::Create(
1087       FunctionType::get(Type::getVoidTy(*C), false),
1088       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1089   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1090   // call __asan_init in the module ctor.
1091   IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1092   AsanInitFunction = checkInterfaceFunction(
1093       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1094   AsanInitFunction->setLinkage(Function::ExternalLinkage);
1095   IRB.CreateCall(AsanInitFunction);
1096
1097   Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
1098   emitShadowMapping(M, IRB);
1099
1100   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
1101   return true;
1102 }
1103
1104 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1105   // For each NSObject descendant having a +load method, this method is invoked
1106   // by the ObjC runtime before any of the static constructors is called.
1107   // Therefore we need to instrument such methods with a call to __asan_init
1108   // at the beginning in order to initialize our runtime before any access to
1109   // the shadow memory.
1110   // We cannot just ignore these methods, because they may call other
1111   // instrumented functions.
1112   if (F.getName().find(" load]") != std::string::npos) {
1113     IRBuilder<> IRB(F.begin()->begin());
1114     IRB.CreateCall(AsanInitFunction);
1115     return true;
1116   }
1117   return false;
1118 }
1119
1120 bool AddressSanitizer::runOnFunction(Function &F) {
1121   if (BL->isIn(F)) return false;
1122   if (&F == AsanCtorFunction) return false;
1123   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1124   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1125   initializeCallbacks(*F.getParent());
1126
1127   // If needed, insert __asan_init before checking for SanitizeAddress attr.
1128   maybeInsertAsanInitAtFunctionEntry(F);
1129
1130   if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1131     return false;
1132
1133   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1134     return false;
1135
1136   // We want to instrument every address only once per basic block (unless there
1137   // are calls between uses).
1138   SmallSet<Value*, 16> TempsToInstrument;
1139   SmallVector<Instruction*, 16> ToInstrument;
1140   SmallVector<Instruction*, 8> NoReturnCalls;
1141   int NumAllocas = 0;
1142   bool IsWrite;
1143
1144   // Fill the set of memory operations to instrument.
1145   for (Function::iterator FI = F.begin(), FE = F.end();
1146        FI != FE; ++FI) {
1147     TempsToInstrument.clear();
1148     int NumInsnsPerBB = 0;
1149     for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1150          BI != BE; ++BI) {
1151       if (LooksLikeCodeInBug11395(BI)) return false;
1152       if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1153         if (ClOpt && ClOptSameTemp) {
1154           if (!TempsToInstrument.insert(Addr))
1155             continue;  // We've seen this temp in the current BB.
1156         }
1157       } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1158         // ok, take it.
1159       } else {
1160         if (isa<AllocaInst>(BI))
1161           NumAllocas++;
1162         CallSite CS(BI);
1163         if (CS) {
1164           // A call inside BB.
1165           TempsToInstrument.clear();
1166           if (CS.doesNotReturn())
1167             NoReturnCalls.push_back(CS.getInstruction());
1168         }
1169         continue;
1170       }
1171       ToInstrument.push_back(BI);
1172       NumInsnsPerBB++;
1173       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1174         break;
1175     }
1176   }
1177
1178   Function *UninstrumentedDuplicate = 0;
1179   bool LikelyToInstrument =
1180       !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1181   if (ClKeepUninstrumented && LikelyToInstrument) {
1182     ValueToValueMapTy VMap;
1183     UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1184     UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1185     UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1186     F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1187   }
1188
1189   // Instrument.
1190   int NumInstrumented = 0;
1191   for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1192     Instruction *Inst = ToInstrument[i];
1193     if (ClDebugMin < 0 || ClDebugMax < 0 ||
1194         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1195       if (isInterestingMemoryAccess(Inst, &IsWrite))
1196         instrumentMop(Inst);
1197       else
1198         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1199     }
1200     NumInstrumented++;
1201   }
1202
1203   FunctionStackPoisoner FSP(F, *this);
1204   bool ChangedStack = FSP.runOnFunction();
1205
1206   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1207   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1208   for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1209     Instruction *CI = NoReturnCalls[i];
1210     IRBuilder<> IRB(CI);
1211     IRB.CreateCall(AsanHandleNoReturnFunc);
1212   }
1213
1214   bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1215   DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1216
1217   if (ClKeepUninstrumented) {
1218     if (!res) {
1219       // No instrumentation is done, no need for the duplicate.
1220       if (UninstrumentedDuplicate)
1221         UninstrumentedDuplicate->eraseFromParent();
1222     } else {
1223       // The function was instrumented. We must have the duplicate.
1224       assert(UninstrumentedDuplicate);
1225       UninstrumentedDuplicate->setSection("NOASAN");
1226       assert(!F.hasSection());
1227       F.setSection("ASAN");
1228     }
1229   }
1230
1231   return res;
1232 }
1233
1234 static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1235   if (ShadowRedzoneSize == 1) return PoisonByte;
1236   if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1237   if (ShadowRedzoneSize == 4)
1238     return (PoisonByte << 24) + (PoisonByte << 16) +
1239         (PoisonByte << 8) + (PoisonByte);
1240   llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
1241 }
1242
1243 static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1244                                             size_t Size,
1245                                             size_t RZSize,
1246                                             size_t ShadowGranularity,
1247                                             uint8_t Magic) {
1248   for (size_t i = 0; i < RZSize;
1249        i+= ShadowGranularity, Shadow++) {
1250     if (i + ShadowGranularity <= Size) {
1251       *Shadow = 0;  // fully addressable
1252     } else if (i >= Size) {
1253       *Shadow = Magic;  // unaddressable
1254     } else {
1255       *Shadow = Size - i;  // first Size-i bytes are addressable
1256     }
1257   }
1258 }
1259
1260 // Workaround for bug 11395: we don't want to instrument stack in functions
1261 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1262 // FIXME: remove once the bug 11395 is fixed.
1263 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1264   if (LongSize != 32) return false;
1265   CallInst *CI = dyn_cast<CallInst>(I);
1266   if (!CI || !CI->isInlineAsm()) return false;
1267   if (CI->getNumArgOperands() <= 5) return false;
1268   // We have inline assembly with quite a few arguments.
1269   return true;
1270 }
1271
1272 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1273   IRBuilder<> IRB(*C);
1274   AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
1275       kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
1276   AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
1277       kAsanStackFreeName, IRB.getVoidTy(),
1278       IntptrTy, IntptrTy, IntptrTy, NULL));
1279   AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1280       kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1281   AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1282       kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1283 }
1284
1285 void FunctionStackPoisoner::poisonRedZones(
1286   const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
1287   bool DoPoison) {
1288   size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
1289   assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1290   Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1291   Type *RZPtrTy = PointerType::get(RZTy, 0);
1292
1293   Value *PoisonLeft  = ConstantInt::get(RZTy,
1294     ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1295   Value *PoisonMid   = ConstantInt::get(RZTy,
1296     ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1297   Value *PoisonRight = ConstantInt::get(RZTy,
1298     ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1299
1300   // poison the first red zone.
1301   IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1302
1303   // poison all other red zones.
1304   uint64_t Pos = RedzoneSize();
1305   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1306     AllocaInst *AI = AllocaVec[i];
1307     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1308     uint64_t AlignedSize = getAlignedAllocaSize(AI);
1309     assert(AlignedSize - SizeInBytes < RedzoneSize());
1310     Value *Ptr = NULL;
1311
1312     Pos += AlignedSize;
1313
1314     assert(ShadowBase->getType() == IntptrTy);
1315     if (SizeInBytes < AlignedSize) {
1316       // Poison the partial redzone at right
1317       Ptr = IRB.CreateAdd(
1318           ShadowBase, ConstantInt::get(IntptrTy,
1319                                        (Pos >> Mapping.Scale) - ShadowRZSize));
1320       size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1321       uint32_t Poison = 0;
1322       if (DoPoison) {
1323         PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1324                                         RedzoneSize(),
1325                                         1ULL << Mapping.Scale,
1326                                         kAsanStackPartialRedzoneMagic);
1327         Poison =
1328             ASan.TD->isLittleEndian()
1329                 ? support::endian::byte_swap<uint32_t, support::little>(Poison)
1330                 : support::endian::byte_swap<uint32_t, support::big>(Poison);
1331       }
1332       Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1333       IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1334     }
1335
1336     // Poison the full redzone at right.
1337     Ptr = IRB.CreateAdd(ShadowBase,
1338                         ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
1339     bool LastAlloca = (i == AllocaVec.size() - 1);
1340     Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
1341     IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1342
1343     Pos += RedzoneSize();
1344   }
1345 }
1346
1347 void FunctionStackPoisoner::poisonStack() {
1348   uint64_t LocalStackSize = TotalStackSize +
1349                             (AllocaVec.size() + 1) * RedzoneSize();
1350
1351   bool DoStackMalloc = ASan.CheckUseAfterReturn
1352       && LocalStackSize <= kMaxStackMallocSize;
1353
1354   assert(AllocaVec.size() > 0);
1355   Instruction *InsBefore = AllocaVec[0];
1356   IRBuilder<> IRB(InsBefore);
1357
1358
1359   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1360   AllocaInst *MyAlloca =
1361       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1362   if (ClRealignStack && StackAlignment < RedzoneSize())
1363     StackAlignment = RedzoneSize();
1364   MyAlloca->setAlignment(StackAlignment);
1365   assert(MyAlloca->isStaticAlloca());
1366   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1367   Value *LocalStackBase = OrigStackBase;
1368
1369   if (DoStackMalloc) {
1370     LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1371         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1372   }
1373
1374   // This string will be parsed by the run-time (DescribeAddressIfStack).
1375   SmallString<2048> StackDescriptionStorage;
1376   raw_svector_ostream StackDescription(StackDescriptionStorage);
1377   StackDescription << AllocaVec.size() << " ";
1378
1379   // Insert poison calls for lifetime intrinsics for alloca.
1380   bool HavePoisonedAllocas = false;
1381   for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1382     const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
1383     IntrinsicInst *II = APC.InsBefore;
1384     AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1385     assert(AI);
1386     IRBuilder<> IRB(II);
1387     poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
1388     HavePoisonedAllocas |= APC.DoPoison;
1389   }
1390
1391   uint64_t Pos = RedzoneSize();
1392   // Replace Alloca instructions with base+offset.
1393   for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1394     AllocaInst *AI = AllocaVec[i];
1395     uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1396     StringRef Name = AI->getName();
1397     StackDescription << Pos << " " << SizeInBytes << " "
1398                      << Name.size() << " " << Name << " ";
1399     uint64_t AlignedSize = getAlignedAllocaSize(AI);
1400     assert((AlignedSize % RedzoneSize()) == 0);
1401     Value *NewAllocaPtr = IRB.CreateIntToPtr(
1402             IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1403             AI->getType());
1404     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1405     AI->replaceAllUsesWith(NewAllocaPtr);
1406     Pos += AlignedSize + RedzoneSize();
1407   }
1408   assert(Pos == LocalStackSize);
1409
1410   // The left-most redzone has enough space for at least 4 pointers.
1411   // Write the Magic value to redzone[0].
1412   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1413   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1414                   BasePlus0);
1415   // Write the frame description constant to redzone[1].
1416   Value *BasePlus1 = IRB.CreateIntToPtr(
1417     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1418     IntptrPtrTy);
1419   GlobalVariable *StackDescriptionGlobal =
1420       createPrivateGlobalForString(*F.getParent(), StackDescription.str());
1421   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1422                                              IntptrTy);
1423   IRB.CreateStore(Description, BasePlus1);
1424   // Write the PC to redzone[2].
1425   Value *BasePlus2 = IRB.CreateIntToPtr(
1426     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1427                                                    2 * ASan.LongSize/8)),
1428     IntptrPtrTy);
1429   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1430
1431   // Poison the stack redzones at the entry.
1432   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1433   poisonRedZones(AllocaVec, IRB, ShadowBase, true);
1434
1435   // Unpoison the stack before all ret instructions.
1436   for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1437     Instruction *Ret = RetVec[i];
1438     IRBuilder<> IRBRet(Ret);
1439     // Mark the current frame as retired.
1440     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1441                        BasePlus0);
1442     // Unpoison the stack.
1443     poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
1444     if (DoStackMalloc) {
1445       // In use-after-return mode, mark the whole stack frame unaddressable.
1446       IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1447                          ConstantInt::get(IntptrTy, LocalStackSize),
1448                          OrigStackBase);
1449     } else if (HavePoisonedAllocas) {
1450       // If we poisoned some allocas in llvm.lifetime analysis,
1451       // unpoison whole stack frame now.
1452       assert(LocalStackBase == OrigStackBase);
1453       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1454     }
1455   }
1456
1457   // We are done. Remove the old unused alloca instructions.
1458   for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1459     AllocaVec[i]->eraseFromParent();
1460 }
1461
1462 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1463                                          IRBuilder<> IRB, bool DoPoison) {
1464   // For now just insert the call to ASan runtime.
1465   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1466   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1467   IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1468                            : AsanUnpoisonStackMemoryFunc,
1469                   AddrArg, SizeArg);
1470 }
1471
1472 // Handling llvm.lifetime intrinsics for a given %alloca:
1473 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1474 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1475 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1476 //     could be poisoned by previous llvm.lifetime.end instruction, as the
1477 //     variable may go in and out of scope several times, e.g. in loops).
1478 // (3) if we poisoned at least one %alloca in a function,
1479 //     unpoison the whole stack frame at function exit.
1480
1481 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1482   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1483     // We're intested only in allocas we can handle.
1484     return isInterestingAlloca(*AI) ? AI : 0;
1485   // See if we've already calculated (or started to calculate) alloca for a
1486   // given value.
1487   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1488   if (I != AllocaForValue.end())
1489     return I->second;
1490   // Store 0 while we're calculating alloca for value V to avoid
1491   // infinite recursion if the value references itself.
1492   AllocaForValue[V] = 0;
1493   AllocaInst *Res = 0;
1494   if (CastInst *CI = dyn_cast<CastInst>(V))
1495     Res = findAllocaForValue(CI->getOperand(0));
1496   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1497     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1498       Value *IncValue = PN->getIncomingValue(i);
1499       // Allow self-referencing phi-nodes.
1500       if (IncValue == PN) continue;
1501       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1502       // AI for incoming values should exist and should all be equal.
1503       if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1504         return 0;
1505       Res = IncValueAI;
1506     }
1507   }
1508   if (Res != 0)
1509     AllocaForValue[V] = Res;
1510   return Res;
1511 }