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