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