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