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