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