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