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