e42839c9c6b78b8f8ce96fb588a14fc3545bb4a8
[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/Utils/ASanStackFrameLayout.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Cloning.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/ModuleUtils.h"
48 #include <algorithm>
49 #include <string>
50 #include <system_error>
51
52 using namespace llvm;
53
54 #define DEBUG_TYPE "asan"
55
56 static const uint64_t kDefaultShadowScale = 3;
57 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
58 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
59 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
60 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000;  // < 2G.
61 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
62 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
63 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
64 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
65
66 static const size_t kMinStackMallocSize = 1 << 6;  // 64B
67 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
68 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
69 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
70
71 static const char *const kAsanModuleCtorName = "asan.module_ctor";
72 static const char *const kAsanModuleDtorName = "asan.module_dtor";
73 static const int         kAsanCtorAndDtorPriority = 1;
74 static const char *const kAsanReportErrorTemplate = "__asan_report_";
75 static const char *const kAsanReportLoadN = "__asan_report_load_n";
76 static const char *const kAsanReportStoreN = "__asan_report_store_n";
77 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
78 static const char *const kAsanUnregisterGlobalsName =
79     "__asan_unregister_globals";
80 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
81 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
82 static const char *const kAsanInitName = "__asan_init_v4";
83 static const char *const kAsanCovModuleInitName = "__sanitizer_cov_module_init";
84 static const char *const kAsanCovName = "__sanitizer_cov";
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<int> ClCoverage("asan-coverage",
137        cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks"),
138        cl::Hidden, cl::init(false));
139 static cl::opt<int> ClCoverageBlockThreshold("asan-coverage-block-threshold",
140        cl::desc("Add coverage instrumentation only to the entry block if there "
141                 "are more than this number of blocks."),
142        cl::Hidden, cl::init(1500));
143 static cl::opt<bool> ClInitializers("asan-initialization-order",
144        cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true));
145 static cl::opt<bool> ClInvalidPointerPairs("asan-detect-invalid-pointer-pair",
146        cl::desc("Instrument <, <=, >, >=, - with pointer operands"),
147        cl::Hidden, cl::init(false));
148 static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
149        cl::desc("Realign stack to the value of this flag (power of two)"),
150        cl::Hidden, cl::init(32));
151 static cl::opt<int> ClInstrumentationWithCallsThreshold(
152     "asan-instrumentation-with-call-threshold",
153        cl::desc("If the function being instrumented contains more than "
154                 "this number of memory accesses, use callbacks instead of "
155                 "inline checks (-1 means never use callbacks)."),
156        cl::Hidden, cl::init(7000));
157 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
158        "asan-memory-access-callback-prefix",
159        cl::desc("Prefix for memory access callbacks"), cl::Hidden,
160        cl::init("__asan_"));
161
162 // This is an experimental feature that will allow to choose between
163 // instrumented and non-instrumented code at link-time.
164 // If this option is on, just before instrumenting a function we create its
165 // clone; if the function is not changed by asan the clone is deleted.
166 // If we end up with a clone, we put the instrumented function into a section
167 // called "ASAN" and the uninstrumented function into a section called "NOASAN".
168 //
169 // This is still a prototype, we need to figure out a way to keep two copies of
170 // a function so that the linker can easily choose one of them.
171 static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
172        cl::desc("Keep uninstrumented copies of functions"),
173        cl::Hidden, cl::init(false));
174
175 // These flags allow to change the shadow mapping.
176 // The shadow mapping looks like
177 //    Shadow = (Mem >> scale) + (1 << offset_log)
178 static cl::opt<int> ClMappingScale("asan-mapping-scale",
179        cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
180
181 // Optimization flags. Not user visible, used mostly for testing
182 // and benchmarking the tool.
183 static cl::opt<bool> ClOpt("asan-opt",
184        cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
185 static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
186        cl::desc("Instrument the same temp just once"), cl::Hidden,
187        cl::init(true));
188 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
189        cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
190
191 static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
192        cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
193        cl::Hidden, cl::init(false));
194
195 // Debug flags.
196 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
197                             cl::init(0));
198 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
199                                  cl::Hidden, cl::init(0));
200 static cl::opt<std::string> ClDebugFunc("asan-debug-func",
201                                         cl::Hidden, cl::desc("Debug func"));
202 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
203                                cl::Hidden, cl::init(-1));
204 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
205                                cl::Hidden, cl::init(-1));
206
207 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
208 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
209 STATISTIC(NumOptimizedAccessesToGlobalArray,
210           "Number of optimized accesses to global arrays");
211 STATISTIC(NumOptimizedAccessesToGlobalVar,
212           "Number of optimized accesses to global vars");
213
214 namespace {
215 /// Frontend-provided metadata for global variables.
216 class GlobalsMetadata {
217  public:
218   struct Entry {
219     Entry()
220         : SourceLoc(nullptr), Name(nullptr), IsDynInit(false),
221           IsBlacklisted(false) {}
222     GlobalVariable *SourceLoc;
223     GlobalVariable *Name;
224     bool IsDynInit;
225     bool IsBlacklisted;
226   };
227
228   GlobalsMetadata() : inited_(false) {}
229
230   void init(Module& M) {
231     assert(!inited_);
232     inited_ = true;
233     NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
234     if (!Globals)
235       return;
236     for (auto MDN : Globals->operands()) {
237       // Metadata node contains the global and the fields of "Entry".
238       assert(MDN->getNumOperands() == 5);
239       Value *V = MDN->getOperand(0);
240       // The optimizer may optimize away a global entirely.
241       if (!V)
242         continue;
243       GlobalVariable *GV = cast<GlobalVariable>(V);
244       // We can already have an entry for GV if it was merged with another
245       // global.
246       Entry &E = Entries[GV];
247       if (Value *Loc = MDN->getOperand(1)) {
248         GlobalVariable *GVLoc = cast<GlobalVariable>(Loc);
249         E.SourceLoc = GVLoc;
250         addSourceLocationGlobal(GVLoc);
251       }
252       if (Value *Name = MDN->getOperand(2)) {
253         GlobalVariable *GVName = cast<GlobalVariable>(Name);
254         E.Name = GVName;
255         InstrumentationGlobals.insert(GVName);
256       }
257       ConstantInt *IsDynInit = cast<ConstantInt>(MDN->getOperand(3));
258       E.IsDynInit |= IsDynInit->isOne();
259       ConstantInt *IsBlacklisted = cast<ConstantInt>(MDN->getOperand(4));
260       E.IsBlacklisted |= IsBlacklisted->isOne();
261     }
262   }
263
264   /// Returns metadata entry for a given global.
265   Entry get(GlobalVariable *G) const {
266     auto Pos = Entries.find(G);
267     return (Pos != Entries.end()) ? Pos->second : Entry();
268   }
269
270   /// Check if the global was generated by the instrumentation
271   /// (we don't want to instrument it again in this case).
272   bool isInstrumentationGlobal(GlobalVariable *G) const {
273     return InstrumentationGlobals.count(G);
274   }
275
276  private:
277   bool inited_;
278   DenseMap<GlobalVariable*, Entry> Entries;
279   // Globals generated by the frontend instrumentation.
280   DenseSet<GlobalVariable*> InstrumentationGlobals;
281
282   void addSourceLocationGlobal(GlobalVariable *SourceLocGV) {
283     // Source location global is a struct with layout:
284     // {
285     //    filename,
286     //    i32 line_number,
287     //    i32 column_number,
288     // }
289     InstrumentationGlobals.insert(SourceLocGV);
290     ConstantStruct *Contents =
291         cast<ConstantStruct>(SourceLocGV->getInitializer());
292     GlobalVariable *FilenameGV = cast<GlobalVariable>(Contents->getOperand(0));
293     InstrumentationGlobals.insert(FilenameGV);
294   }
295 };
296
297 /// This struct defines the shadow mapping using the rule:
298 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
299 struct ShadowMapping {
300   int Scale;
301   uint64_t Offset;
302   bool OrShadowOffset;
303 };
304
305 static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
306   llvm::Triple TargetTriple(M.getTargetTriple());
307   bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
308   bool IsIOS = TargetTriple.getOS() == llvm::Triple::IOS;
309   bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
310   bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
311   bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
312                  TargetTriple.getArch() == llvm::Triple::ppc64le;
313   bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
314   bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
315                   TargetTriple.getArch() == llvm::Triple::mipsel;
316
317   ShadowMapping Mapping;
318
319   if (LongSize == 32) {
320     if (IsAndroid)
321       Mapping.Offset = 0;
322     else if (IsMIPS32)
323       Mapping.Offset = kMIPS32_ShadowOffset32;
324     else if (IsFreeBSD)
325       Mapping.Offset = kFreeBSD_ShadowOffset32;
326     else if (IsIOS)
327       Mapping.Offset = kIOSShadowOffset32;
328     else
329       Mapping.Offset = kDefaultShadowOffset32;
330   } else {  // LongSize == 64
331     if (IsPPC64)
332       Mapping.Offset = kPPC64_ShadowOffset64;
333     else if (IsFreeBSD)
334       Mapping.Offset = kFreeBSD_ShadowOffset64;
335     else if (IsLinux && IsX86_64)
336       Mapping.Offset = kSmallX86_64ShadowOffset;
337     else
338       Mapping.Offset = kDefaultShadowOffset64;
339   }
340
341   Mapping.Scale = kDefaultShadowScale;
342   if (ClMappingScale) {
343     Mapping.Scale = ClMappingScale;
344   }
345
346   // OR-ing shadow offset if more efficient (at least on x86) if the offset
347   // is a power of two, but on ppc64 we have to use add since the shadow
348   // offset is not necessary 1/8-th of the address space.
349   Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
350
351   return Mapping;
352 }
353
354 static size_t RedzoneSizeForScale(int MappingScale) {
355   // Redzone used for stack and globals is at least 32 bytes.
356   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
357   return std::max(32U, 1U << MappingScale);
358 }
359
360 /// AddressSanitizer: instrument the code in module to find memory bugs.
361 struct AddressSanitizer : public FunctionPass {
362   AddressSanitizer() : FunctionPass(ID) {}
363   const char *getPassName() const override {
364     return "AddressSanitizerFunctionPass";
365   }
366   void instrumentMop(Instruction *I, bool UseCalls);
367   void instrumentPointerComparisonOrSubtraction(Instruction *I);
368   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
369                          Value *Addr, uint32_t TypeSize, bool IsWrite,
370                          Value *SizeArgument, bool UseCalls);
371   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
372                            Value *ShadowValue, uint32_t TypeSize);
373   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
374                                  bool IsWrite, size_t AccessSizeIndex,
375                                  Value *SizeArgument);
376   void instrumentMemIntrinsic(MemIntrinsic *MI);
377   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
378   bool runOnFunction(Function &F) override;
379   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
380   bool doInitialization(Module &M) override;
381   static char ID;  // Pass identification, replacement for typeid
382
383  private:
384   void initializeCallbacks(Module &M);
385
386   bool LooksLikeCodeInBug11395(Instruction *I);
387   bool GlobalIsLinkerInitialized(GlobalVariable *G);
388   bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
389   void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
390
391   LLVMContext *C;
392   const DataLayout *DL;
393   int LongSize;
394   Type *IntptrTy;
395   ShadowMapping Mapping;
396   Function *AsanCtorFunction;
397   Function *AsanInitFunction;
398   Function *AsanHandleNoReturnFunc;
399   Function *AsanCovFunction;
400   Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
401   // This array is indexed by AccessIsWrite and log2(AccessSize).
402   Function *AsanErrorCallback[2][kNumberOfAccessSizes];
403   Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
404   // This array is indexed by AccessIsWrite.
405   Function *AsanErrorCallbackSized[2],
406            *AsanMemoryAccessCallbackSized[2];
407   Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
408   InlineAsm *EmptyAsm;
409   GlobalsMetadata GlobalsMD;
410
411   friend struct FunctionStackPoisoner;
412 };
413
414 class AddressSanitizerModule : public ModulePass {
415  public:
416   AddressSanitizerModule() : ModulePass(ID) {}
417   bool runOnModule(Module &M) override;
418   static char ID;  // Pass identification, replacement for typeid
419   const char *getPassName() const override {
420     return "AddressSanitizerModule";
421   }
422
423  private:
424   void initializeCallbacks(Module &M);
425
426   bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
427   bool ShouldInstrumentGlobal(GlobalVariable *G);
428   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
429   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
430   size_t MinRedzoneSizeForGlobal() const {
431     return RedzoneSizeForScale(Mapping.Scale);
432   }
433
434   GlobalsMetadata GlobalsMD;
435   Type *IntptrTy;
436   LLVMContext *C;
437   const DataLayout *DL;
438   ShadowMapping Mapping;
439   Function *AsanPoisonGlobals;
440   Function *AsanUnpoisonGlobals;
441   Function *AsanRegisterGlobals;
442   Function *AsanUnregisterGlobals;
443   Function *AsanCovModuleInit;
444 };
445
446 // Stack poisoning does not play well with exception handling.
447 // When an exception is thrown, we essentially bypass the code
448 // that unpoisones the stack. This is why the run-time library has
449 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
450 // stack in the interceptor. This however does not work inside the
451 // actual function which catches the exception. Most likely because the
452 // compiler hoists the load of the shadow value somewhere too high.
453 // This causes asan to report a non-existing bug on 453.povray.
454 // It sounds like an LLVM bug.
455 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
456   Function &F;
457   AddressSanitizer &ASan;
458   DIBuilder DIB;
459   LLVMContext *C;
460   Type *IntptrTy;
461   Type *IntptrPtrTy;
462   ShadowMapping Mapping;
463
464   SmallVector<AllocaInst*, 16> AllocaVec;
465   SmallVector<Instruction*, 8> RetVec;
466   unsigned StackAlignment;
467
468   Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
469            *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
470   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
471
472   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
473   struct AllocaPoisonCall {
474     IntrinsicInst *InsBefore;
475     AllocaInst *AI;
476     uint64_t Size;
477     bool DoPoison;
478   };
479   SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
480
481   // Maps Value to an AllocaInst from which the Value is originated.
482   typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
483   AllocaForValueMapTy AllocaForValue;
484
485   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
486       : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
487         IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
488         Mapping(ASan.Mapping),
489         StackAlignment(1 << Mapping.Scale) {}
490
491   bool runOnFunction() {
492     if (!ClStack) return false;
493     // Collect alloca, ret, lifetime instructions etc.
494     for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
495       visit(*BB);
496
497     if (AllocaVec.empty()) return false;
498
499     initializeCallbacks(*F.getParent());
500
501     poisonStack();
502
503     if (ClDebugStack) {
504       DEBUG(dbgs() << F);
505     }
506     return true;
507   }
508
509   // Finds all static Alloca instructions and puts
510   // poisoned red zones around all of them.
511   // Then unpoison everything back before the function returns.
512   void poisonStack();
513
514   // ----------------------- Visitors.
515   /// \brief Collect all Ret instructions.
516   void visitReturnInst(ReturnInst &RI) {
517     RetVec.push_back(&RI);
518   }
519
520   /// \brief Collect Alloca instructions we want (and can) handle.
521   void visitAllocaInst(AllocaInst &AI) {
522     if (!isInterestingAlloca(AI)) return;
523
524     StackAlignment = std::max(StackAlignment, AI.getAlignment());
525     AllocaVec.push_back(&AI);
526   }
527
528   /// \brief Collect lifetime intrinsic calls to check for use-after-scope
529   /// errors.
530   void visitIntrinsicInst(IntrinsicInst &II) {
531     if (!ClCheckLifetime) return;
532     Intrinsic::ID ID = II.getIntrinsicID();
533     if (ID != Intrinsic::lifetime_start &&
534         ID != Intrinsic::lifetime_end)
535       return;
536     // Found lifetime intrinsic, add ASan instrumentation if necessary.
537     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
538     // If size argument is undefined, don't do anything.
539     if (Size->isMinusOne()) return;
540     // Check that size doesn't saturate uint64_t and can
541     // be stored in IntptrTy.
542     const uint64_t SizeValue = Size->getValue().getLimitedValue();
543     if (SizeValue == ~0ULL ||
544         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
545       return;
546     // Find alloca instruction that corresponds to llvm.lifetime argument.
547     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
548     if (!AI) return;
549     bool DoPoison = (ID == Intrinsic::lifetime_end);
550     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
551     AllocaPoisonCallVec.push_back(APC);
552   }
553
554   // ---------------------- Helpers.
555   void initializeCallbacks(Module &M);
556
557   // Check if we want (and can) handle this alloca.
558   bool isInterestingAlloca(AllocaInst &AI) const {
559     return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
560             AI.getAllocatedType()->isSized() &&
561             // alloca() may be called with 0 size, ignore it.
562             getAllocaSizeInBytes(&AI) > 0);
563   }
564
565   uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
566     Type *Ty = AI->getAllocatedType();
567     uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
568     return SizeInBytes;
569   }
570   /// Finds alloca where the value comes from.
571   AllocaInst *findAllocaForValue(Value *V);
572   void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
573                       Value *ShadowBase, bool DoPoison);
574   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
575
576   void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
577                                           int Size);
578 };
579
580 }  // namespace
581
582 char AddressSanitizer::ID = 0;
583 INITIALIZE_PASS(AddressSanitizer, "asan",
584     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
585     false, false)
586 FunctionPass *llvm::createAddressSanitizerFunctionPass() {
587   return new AddressSanitizer();
588 }
589
590 char AddressSanitizerModule::ID = 0;
591 INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
592     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
593     "ModulePass", false, false)
594 ModulePass *llvm::createAddressSanitizerModulePass() {
595   return new AddressSanitizerModule();
596 }
597
598 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
599   size_t Res = countTrailingZeros(TypeSize / 8);
600   assert(Res < kNumberOfAccessSizes);
601   return Res;
602 }
603
604 // \brief Create a constant for Str so that we can pass it to the run-time lib.
605 static GlobalVariable *createPrivateGlobalForString(
606     Module &M, StringRef Str, bool AllowMerging) {
607   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
608   // We use private linkage for module-local strings. If they can be merged
609   // with another one, we set the unnamed_addr attribute.
610   GlobalVariable *GV =
611       new GlobalVariable(M, StrConst->getType(), true,
612                          GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
613   if (AllowMerging)
614     GV->setUnnamedAddr(true);
615   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
616   return GV;
617 }
618
619 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
620   return G->getName().find(kAsanGenPrefix) == 0;
621 }
622
623 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
624   // Shadow >> scale
625   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
626   if (Mapping.Offset == 0)
627     return Shadow;
628   // (Shadow >> scale) | offset
629   if (Mapping.OrShadowOffset)
630     return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
631   else
632     return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
633 }
634
635 // Instrument memset/memmove/memcpy
636 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
637   IRBuilder<> IRB(MI);
638   if (isa<MemTransferInst>(MI)) {
639     IRB.CreateCall3(
640         isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
641         IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
642         IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
643         IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
644   } else if (isa<MemSetInst>(MI)) {
645     IRB.CreateCall3(
646         AsanMemset,
647         IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
648         IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
649         IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
650   }
651   MI->eraseFromParent();
652 }
653
654 // If I is an interesting memory access, return the PointerOperand
655 // and set IsWrite/Alignment. Otherwise return NULL.
656 static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
657                                         unsigned *Alignment) {
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     TerminatorInst *CheckTerm =
862         SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
863     assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
864     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
865     IRB.SetInsertPoint(CheckTerm);
866     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
867     BasicBlock *CrashBlock =
868         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
869     CrashTerm = new UnreachableInst(*C, CrashBlock);
870     BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
871     ReplaceInstWithInst(CheckTerm, NewTerm);
872   } else {
873     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
874   }
875
876   Instruction *Crash = generateCrashCode(
877       CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
878   Crash->setDebugLoc(OrigIns->getDebugLoc());
879 }
880
881 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
882                                                   GlobalValue *ModuleName) {
883   // Set up the arguments to our poison/unpoison functions.
884   IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
885
886   // Add a call to poison all external globals before the given function starts.
887   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
888   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
889
890   // Add calls to unpoison all globals before each return instruction.
891   for (auto &BB : GlobalInit.getBasicBlockList())
892     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
893       CallInst::Create(AsanUnpoisonGlobals, "", RI);
894 }
895
896 void AddressSanitizerModule::createInitializerPoisonCalls(
897     Module &M, GlobalValue *ModuleName) {
898   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
899
900   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
901   for (Use &OP : CA->operands()) {
902     if (isa<ConstantAggregateZero>(OP))
903       continue;
904     ConstantStruct *CS = cast<ConstantStruct>(OP);
905
906     // Must have a function or null ptr.
907     // (CS->getOperand(0) is the init priority.)
908     if (Function* F = dyn_cast<Function>(CS->getOperand(1))) {
909       if (F->getName() != kAsanModuleCtorName)
910         poisonOneInitializer(*F, ModuleName);
911     }
912   }
913 }
914
915 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
916   Type *Ty = cast<PointerType>(G->getType())->getElementType();
917   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
918
919   if (GlobalsMD.get(G).IsBlacklisted) return false;
920   if (GlobalsMD.isInstrumentationGlobal(G)) return false;
921   if (!Ty->isSized()) return false;
922   if (!G->hasInitializer()) return false;
923   if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
924   // Touch only those globals that will not be defined in other modules.
925   // Don't handle ODR linkage types and COMDATs since other modules may be built
926   // without ASan.
927   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
928       G->getLinkage() != GlobalVariable::PrivateLinkage &&
929       G->getLinkage() != GlobalVariable::InternalLinkage)
930     return false;
931   if (G->hasComdat())
932     return false;
933   // Two problems with thread-locals:
934   //   - The address of the main thread's copy can't be computed at link-time.
935   //   - Need to poison all copies, not just the main thread's one.
936   if (G->isThreadLocal())
937     return false;
938   // For now, just ignore this Global if the alignment is large.
939   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
940
941   // Ignore all the globals with the names starting with "\01L_OBJC_".
942   // Many of those are put into the .cstring section. The linker compresses
943   // that section by removing the spare \0s after the string terminator, so
944   // our redzones get broken.
945   if ((G->getName().find("\01L_OBJC_") == 0) ||
946       (G->getName().find("\01l_OBJC_") == 0)) {
947     DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G << "\n");
948     return false;
949   }
950
951   if (G->hasSection()) {
952     StringRef Section(G->getSection());
953     // Ignore the globals from the __OBJC section. The ObjC runtime assumes
954     // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
955     // them.
956     if (Section.startswith("__OBJC,") ||
957         Section.startswith("__DATA, __objc_")) {
958       DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
959       return false;
960     }
961     // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
962     // Constant CFString instances are compiled in the following way:
963     //  -- the string buffer is emitted into
964     //     __TEXT,__cstring,cstring_literals
965     //  -- the constant NSConstantString structure referencing that buffer
966     //     is placed into __DATA,__cfstring
967     // Therefore there's no point in placing redzones into __DATA,__cfstring.
968     // Moreover, it causes the linker to crash on OS X 10.7
969     if (Section.startswith("__DATA,__cfstring")) {
970       DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
971       return false;
972     }
973     // The linker merges the contents of cstring_literals and removes the
974     // trailing zeroes.
975     if (Section.startswith("__TEXT,__cstring,cstring_literals")) {
976       DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
977       return false;
978     }
979
980     // Callbacks put into the CRT initializer/terminator sections
981     // should not be instrumented.
982     // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
983     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
984     if (Section.startswith(".CRT")) {
985       DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
986       return false;
987     }
988
989     // Globals from llvm.metadata aren't emitted, do not instrument them.
990     if (Section == "llvm.metadata") return false;
991   }
992
993   return true;
994 }
995
996 void AddressSanitizerModule::initializeCallbacks(Module &M) {
997   IRBuilder<> IRB(*C);
998   // Declare our poisoning and unpoisoning functions.
999   AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1000       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
1001   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1002   AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1003       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
1004   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1005   // Declare functions that register/unregister globals.
1006   AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1007       kAsanRegisterGlobalsName, IRB.getVoidTy(),
1008       IntptrTy, IntptrTy, NULL));
1009   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1010   AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
1011       kAsanUnregisterGlobalsName,
1012       IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1013   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1014   AsanCovModuleInit = checkInterfaceFunction(M.getOrInsertFunction(
1015       kAsanCovModuleInitName,
1016       IRB.getVoidTy(), IntptrTy, NULL));
1017   AsanCovModuleInit->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 unless it was provided by
1063     // the metadata.
1064     GlobalVariable *Name =
1065         MD.Name ? MD.Name : createPrivateGlobalForString(M, G->getName(),
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     Initializers[i] = ConstantStruct::get(
1109         GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1110         ConstantInt::get(IntptrTy, SizeInBytes),
1111         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1112         ConstantExpr::getPointerCast(Name, IntptrTy),
1113         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1114         ConstantInt::get(IntptrTy, MD.IsDynInit),
1115         MD.SourceLoc ? ConstantExpr::getPointerCast(MD.SourceLoc, IntptrTy)
1116                      : ConstantInt::get(IntptrTy, 0),
1117         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 (ClCoverage > 0) {
1171     Function *CovFunc = M.getFunction(kAsanCovName);
1172     int nCov = CovFunc ? CovFunc->getNumUses() : 0;
1173     IRB.CreateCall(AsanCovModuleInit, ConstantInt::get(IntptrTy, nCov));
1174     Changed = true;
1175   }
1176
1177   if (ClGlobals)
1178     Changed |= InstrumentGlobals(IRB, M);
1179
1180   return Changed;
1181 }
1182
1183 void AddressSanitizer::initializeCallbacks(Module &M) {
1184   IRBuilder<> IRB(*C);
1185   // Create __asan_report* callbacks.
1186   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1187     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1188          AccessSizeIndex++) {
1189       // IsWrite and TypeSize are encoded in the function name.
1190       std::string Suffix =
1191           (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
1192       AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1193           checkInterfaceFunction(
1194               M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
1195                                     IRB.getVoidTy(), IntptrTy, NULL));
1196       AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1197           checkInterfaceFunction(
1198               M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
1199                                     IRB.getVoidTy(), IntptrTy, NULL));
1200     }
1201   }
1202   AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1203               kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1204   AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1205               kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1206
1207   AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1208       M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
1209                             IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1210   AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1211       M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
1212                             IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1213
1214   AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1215       ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1216       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1217   AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1218       ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1219       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, NULL));
1220   AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1221       ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1222       IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, NULL));
1223
1224   AsanHandleNoReturnFunc = checkInterfaceFunction(
1225       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1226   AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
1227       kAsanCovName, IRB.getVoidTy(), NULL));
1228   AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
1229       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1230   AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
1231       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1232   // We insert an empty inline asm after __asan_report* to avoid callback merge.
1233   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1234                             StringRef(""), StringRef(""),
1235                             /*hasSideEffects=*/true);
1236 }
1237
1238 // virtual
1239 bool AddressSanitizer::doInitialization(Module &M) {
1240   // Initialize the private fields. No one has accessed them before.
1241   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1242   if (!DLP)
1243     report_fatal_error("data layout missing");
1244   DL = &DLP->getDataLayout();
1245
1246   GlobalsMD.init(M);
1247
1248   C = &(M.getContext());
1249   LongSize = DL->getPointerSizeInBits();
1250   IntptrTy = Type::getIntNTy(*C, LongSize);
1251
1252   AsanCtorFunction = Function::Create(
1253       FunctionType::get(Type::getVoidTy(*C), false),
1254       GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1255   BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1256   // call __asan_init in the module ctor.
1257   IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1258   AsanInitFunction = checkInterfaceFunction(
1259       M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1260   AsanInitFunction->setLinkage(Function::ExternalLinkage);
1261   IRB.CreateCall(AsanInitFunction);
1262
1263   Mapping = getShadowMapping(M, LongSize);
1264
1265   appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1266   return true;
1267 }
1268
1269 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1270   // For each NSObject descendant having a +load method, this method is invoked
1271   // by the ObjC runtime before any of the static constructors is called.
1272   // Therefore we need to instrument such methods with a call to __asan_init
1273   // at the beginning in order to initialize our runtime before any access to
1274   // the shadow memory.
1275   // We cannot just ignore these methods, because they may call other
1276   // instrumented functions.
1277   if (F.getName().find(" load]") != std::string::npos) {
1278     IRBuilder<> IRB(F.begin()->begin());
1279     IRB.CreateCall(AsanInitFunction);
1280     return true;
1281   }
1282   return false;
1283 }
1284
1285 void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
1286   BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
1287   // Skip static allocas at the top of the entry block so they don't become
1288   // dynamic when we split the block.  If we used our optimized stack layout,
1289   // then there will only be one alloca and it will come first.
1290   for (; IP != BE; ++IP) {
1291     AllocaInst *AI = dyn_cast<AllocaInst>(IP);
1292     if (!AI || !AI->isStaticAlloca())
1293       break;
1294   }
1295
1296   DebugLoc EntryLoc = IP->getDebugLoc().getFnDebugLoc(*C);
1297   IRBuilder<> IRB(IP);
1298   IRB.SetCurrentDebugLocation(EntryLoc);
1299   Type *Int8Ty = IRB.getInt8Ty();
1300   GlobalVariable *Guard = new GlobalVariable(
1301       *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
1302       Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1303   LoadInst *Load = IRB.CreateLoad(Guard);
1304   Load->setAtomic(Monotonic);
1305   Load->setAlignment(1);
1306   Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
1307   Instruction *Ins = SplitBlockAndInsertIfThen(
1308       Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
1309   IRB.SetInsertPoint(Ins);
1310   IRB.SetCurrentDebugLocation(EntryLoc);
1311   // We pass &F to __sanitizer_cov. We could avoid this and rely on
1312   // GET_CALLER_PC, but having the PC of the first instruction is just nice.
1313   IRB.CreateCall(AsanCovFunction);
1314   StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1315   Store->setAtomic(Monotonic);
1316   Store->setAlignment(1);
1317 }
1318
1319 // Poor man's coverage that works with ASan.
1320 // We create a Guard boolean variable with the same linkage
1321 // as the function and inject this code into the entry block (-asan-coverage=1)
1322 // or all blocks (-asan-coverage=2):
1323 // if (*Guard) {
1324 //    __sanitizer_cov(&F);
1325 //    *Guard = 1;
1326 // }
1327 // The accesses to Guard are atomic. The rest of the logic is
1328 // in __sanitizer_cov (it's fine to call it more than once).
1329 //
1330 // This coverage implementation provides very limited data:
1331 // it only tells if a given function (block) was ever executed.
1332 // No counters, no per-edge data.
1333 // But for many use cases this is what we need and the added slowdown
1334 // is negligible. This simple implementation will probably be obsoleted
1335 // by the upcoming Clang-based coverage implementation.
1336 // By having it here and now we hope to
1337 //  a) get the functionality to users earlier and
1338 //  b) collect usage statistics to help improve Clang coverage design.
1339 bool AddressSanitizer::InjectCoverage(Function &F,
1340                                       const ArrayRef<BasicBlock *> AllBlocks) {
1341   if (!ClCoverage) return false;
1342
1343   if (ClCoverage == 1 ||
1344       (unsigned)ClCoverageBlockThreshold < AllBlocks.size()) {
1345     InjectCoverageAtBlock(F, F.getEntryBlock());
1346   } else {
1347     for (auto BB : AllBlocks)
1348       InjectCoverageAtBlock(F, *BB);
1349   }
1350   return true;
1351 }
1352
1353 bool AddressSanitizer::runOnFunction(Function &F) {
1354   if (&F == AsanCtorFunction) return false;
1355   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1356   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1357   initializeCallbacks(*F.getParent());
1358
1359   // If needed, insert __asan_init before checking for SanitizeAddress attr.
1360   maybeInsertAsanInitAtFunctionEntry(F);
1361
1362   if (!F.hasFnAttribute(Attribute::SanitizeAddress))
1363     return false;
1364
1365   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1366     return false;
1367
1368   // We want to instrument every address only once per basic block (unless there
1369   // are calls between uses).
1370   SmallSet<Value*, 16> TempsToInstrument;
1371   SmallVector<Instruction*, 16> ToInstrument;
1372   SmallVector<Instruction*, 8> NoReturnCalls;
1373   SmallVector<BasicBlock*, 16> AllBlocks;
1374   SmallVector<Instruction*, 16> PointerComparisonsOrSubtracts;
1375   int NumAllocas = 0;
1376   bool IsWrite;
1377   unsigned Alignment;
1378
1379   // Fill the set of memory operations to instrument.
1380   for (auto &BB : F) {
1381     AllBlocks.push_back(&BB);
1382     TempsToInstrument.clear();
1383     int NumInsnsPerBB = 0;
1384     for (auto &Inst : BB) {
1385       if (LooksLikeCodeInBug11395(&Inst)) return false;
1386       if (Value *Addr =
1387               isInterestingMemoryAccess(&Inst, &IsWrite, &Alignment)) {
1388         if (ClOpt && ClOptSameTemp) {
1389           if (!TempsToInstrument.insert(Addr))
1390             continue;  // We've seen this temp in the current BB.
1391         }
1392       } else if (ClInvalidPointerPairs &&
1393                  isInterestingPointerComparisonOrSubtraction(&Inst)) {
1394         PointerComparisonsOrSubtracts.push_back(&Inst);
1395         continue;
1396       } else if (isa<MemIntrinsic>(Inst)) {
1397         // ok, take it.
1398       } else {
1399         if (isa<AllocaInst>(Inst))
1400           NumAllocas++;
1401         CallSite CS(&Inst);
1402         if (CS) {
1403           // A call inside BB.
1404           TempsToInstrument.clear();
1405           if (CS.doesNotReturn())
1406             NoReturnCalls.push_back(CS.getInstruction());
1407         }
1408         continue;
1409       }
1410       ToInstrument.push_back(&Inst);
1411       NumInsnsPerBB++;
1412       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1413         break;
1414     }
1415   }
1416
1417   Function *UninstrumentedDuplicate = nullptr;
1418   bool LikelyToInstrument =
1419       !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1420   if (ClKeepUninstrumented && LikelyToInstrument) {
1421     ValueToValueMapTy VMap;
1422     UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1423     UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1424     UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1425     F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1426   }
1427
1428   bool UseCalls = false;
1429   if (ClInstrumentationWithCallsThreshold >= 0 &&
1430       ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1431     UseCalls = true;
1432
1433   // Instrument.
1434   int NumInstrumented = 0;
1435   for (auto Inst : ToInstrument) {
1436     if (ClDebugMin < 0 || ClDebugMax < 0 ||
1437         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1438       if (isInterestingMemoryAccess(Inst, &IsWrite, &Alignment))
1439         instrumentMop(Inst, UseCalls);
1440       else
1441         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1442     }
1443     NumInstrumented++;
1444   }
1445
1446   FunctionStackPoisoner FSP(F, *this);
1447   bool ChangedStack = FSP.runOnFunction();
1448
1449   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1450   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1451   for (auto CI : NoReturnCalls) {
1452     IRBuilder<> IRB(CI);
1453     IRB.CreateCall(AsanHandleNoReturnFunc);
1454   }
1455
1456   for (auto Inst : PointerComparisonsOrSubtracts) {
1457     instrumentPointerComparisonOrSubtraction(Inst);
1458     NumInstrumented++;
1459   }
1460
1461   bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1462
1463   if (InjectCoverage(F, AllBlocks))
1464     res = true;
1465
1466   DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1467
1468   if (ClKeepUninstrumented) {
1469     if (!res) {
1470       // No instrumentation is done, no need for the duplicate.
1471       if (UninstrumentedDuplicate)
1472         UninstrumentedDuplicate->eraseFromParent();
1473     } else {
1474       // The function was instrumented. We must have the duplicate.
1475       assert(UninstrumentedDuplicate);
1476       UninstrumentedDuplicate->setSection("NOASAN");
1477       assert(!F.hasSection());
1478       F.setSection("ASAN");
1479     }
1480   }
1481
1482   return res;
1483 }
1484
1485 // Workaround for bug 11395: we don't want to instrument stack in functions
1486 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1487 // FIXME: remove once the bug 11395 is fixed.
1488 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1489   if (LongSize != 32) return false;
1490   CallInst *CI = dyn_cast<CallInst>(I);
1491   if (!CI || !CI->isInlineAsm()) return false;
1492   if (CI->getNumArgOperands() <= 5) return false;
1493   // We have inline assembly with quite a few arguments.
1494   return true;
1495 }
1496
1497 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1498   IRBuilder<> IRB(*C);
1499   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1500     std::string Suffix = itostr(i);
1501     AsanStackMallocFunc[i] = checkInterfaceFunction(
1502         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1503                               IntptrTy, IntptrTy, NULL));
1504     AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1505         kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1506         IntptrTy, IntptrTy, NULL));
1507   }
1508   AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1509       kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1510   AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1511       kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1512 }
1513
1514 void
1515 FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
1516                                       IRBuilder<> &IRB, Value *ShadowBase,
1517                                       bool DoPoison) {
1518   size_t n = ShadowBytes.size();
1519   size_t i = 0;
1520   // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1521   // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1522   // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1523   for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1524        LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1525     for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1526       uint64_t Val = 0;
1527       for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1528         if (ASan.DL->isLittleEndian())
1529           Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1530         else
1531           Val = (Val << 8) | ShadowBytes[i + j];
1532       }
1533       if (!Val) continue;
1534       Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1535       Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1536       Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1537       IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1538     }
1539   }
1540 }
1541
1542 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1543 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1544 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1545   assert(LocalStackSize <= kMaxStackMallocSize);
1546   uint64_t MaxSize = kMinStackMallocSize;
1547   for (int i = 0; ; i++, MaxSize *= 2)
1548     if (LocalStackSize <= MaxSize)
1549       return i;
1550   llvm_unreachable("impossible LocalStackSize");
1551 }
1552
1553 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1554 // We can not use MemSet intrinsic because it may end up calling the actual
1555 // memset. Size is a multiple of 8.
1556 // Currently this generates 8-byte stores on x86_64; it may be better to
1557 // generate wider stores.
1558 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1559     IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1560   assert(!(Size % 8));
1561   assert(kAsanStackAfterReturnMagic == 0xf5);
1562   for (int i = 0; i < Size; i += 8) {
1563     Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1564     IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1565                     IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1566   }
1567 }
1568
1569 static DebugLoc getFunctionEntryDebugLocation(Function &F) {
1570   for (const auto &Inst : F.getEntryBlock())
1571     if (!isa<AllocaInst>(Inst))
1572       return Inst.getDebugLoc();
1573   return DebugLoc();
1574 }
1575
1576 void FunctionStackPoisoner::poisonStack() {
1577   int StackMallocIdx = -1;
1578   DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
1579
1580   assert(AllocaVec.size() > 0);
1581   Instruction *InsBefore = AllocaVec[0];
1582   IRBuilder<> IRB(InsBefore);
1583   IRB.SetCurrentDebugLocation(EntryDebugLocation);
1584
1585   SmallVector<ASanStackVariableDescription, 16> SVD;
1586   SVD.reserve(AllocaVec.size());
1587   for (AllocaInst *AI : AllocaVec) {
1588     ASanStackVariableDescription D = { AI->getName().data(),
1589                                    getAllocaSizeInBytes(AI),
1590                                    AI->getAlignment(), AI, 0};
1591     SVD.push_back(D);
1592   }
1593   // Minimal header size (left redzone) is 4 pointers,
1594   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1595   size_t MinHeaderSize = ASan.LongSize / 2;
1596   ASanStackFrameLayout L;
1597   ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1598   DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1599   uint64_t LocalStackSize = L.FrameSize;
1600   bool DoStackMalloc =
1601       ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
1602
1603   Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1604   AllocaInst *MyAlloca =
1605       new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
1606   MyAlloca->setDebugLoc(EntryDebugLocation);
1607   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1608   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1609   MyAlloca->setAlignment(FrameAlignment);
1610   assert(MyAlloca->isStaticAlloca());
1611   Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1612   Value *LocalStackBase = OrigStackBase;
1613
1614   if (DoStackMalloc) {
1615     // LocalStackBase = OrigStackBase
1616     // if (__asan_option_detect_stack_use_after_return)
1617     //   LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1618     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1619     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1620     Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1621         kAsanOptionDetectUAR, IRB.getInt32Ty());
1622     Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1623                                   Constant::getNullValue(IRB.getInt32Ty()));
1624     Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
1625     BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1626     IRBuilder<> IRBIf(Term);
1627     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1628     LocalStackBase = IRBIf.CreateCall2(
1629         AsanStackMallocFunc[StackMallocIdx],
1630         ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1631     BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1632     IRB.SetInsertPoint(InsBefore);
1633     IRB.SetCurrentDebugLocation(EntryDebugLocation);
1634     PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1635     Phi->addIncoming(OrigStackBase, CmpBlock);
1636     Phi->addIncoming(LocalStackBase, SetBlock);
1637     LocalStackBase = Phi;
1638   }
1639
1640   // Insert poison calls for lifetime intrinsics for alloca.
1641   bool HavePoisonedAllocas = false;
1642   for (const auto &APC : AllocaPoisonCallVec) {
1643     assert(APC.InsBefore);
1644     assert(APC.AI);
1645     IRBuilder<> IRB(APC.InsBefore);
1646     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1647     HavePoisonedAllocas |= APC.DoPoison;
1648   }
1649
1650   // Replace Alloca instructions with base+offset.
1651   for (const auto &Desc : SVD) {
1652     AllocaInst *AI = Desc.AI;
1653     Value *NewAllocaPtr = IRB.CreateIntToPtr(
1654         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1655         AI->getType());
1656     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1657     AI->replaceAllUsesWith(NewAllocaPtr);
1658   }
1659
1660   // The left-most redzone has enough space for at least 4 pointers.
1661   // Write the Magic value to redzone[0].
1662   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1663   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1664                   BasePlus0);
1665   // Write the frame description constant to redzone[1].
1666   Value *BasePlus1 = IRB.CreateIntToPtr(
1667     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1668     IntptrPtrTy);
1669   GlobalVariable *StackDescriptionGlobal =
1670       createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1671                                    /*AllowMerging*/true);
1672   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1673                                              IntptrTy);
1674   IRB.CreateStore(Description, BasePlus1);
1675   // Write the PC to redzone[2].
1676   Value *BasePlus2 = IRB.CreateIntToPtr(
1677     IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1678                                                    2 * ASan.LongSize/8)),
1679     IntptrPtrTy);
1680   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1681
1682   // Poison the stack redzones at the entry.
1683   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1684   poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1685
1686   // (Un)poison the stack before all ret instructions.
1687   for (auto Ret : RetVec) {
1688     IRBuilder<> IRBRet(Ret);
1689     // Mark the current frame as retired.
1690     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1691                        BasePlus0);
1692     if (DoStackMalloc) {
1693       assert(StackMallocIdx >= 0);
1694       // if LocalStackBase != OrigStackBase:
1695       //     // In use-after-return mode, poison the whole stack frame.
1696       //     if StackMallocIdx <= 4
1697       //         // For small sizes inline the whole thing:
1698       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1699       //         **SavedFlagPtr(LocalStackBase) = 0
1700       //     else
1701       //         __asan_stack_free_N(LocalStackBase, OrigStackBase)
1702       // else
1703       //     <This is not a fake stack; unpoison the redzones>
1704       Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1705       TerminatorInst *ThenTerm, *ElseTerm;
1706       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1707
1708       IRBuilder<> IRBPoison(ThenTerm);
1709       if (StackMallocIdx <= 4) {
1710         int ClassSize = kMinStackMallocSize << StackMallocIdx;
1711         SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1712                                            ClassSize >> Mapping.Scale);
1713         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1714             LocalStackBase,
1715             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1716         Value *SavedFlagPtr = IRBPoison.CreateLoad(
1717             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1718         IRBPoison.CreateStore(
1719             Constant::getNullValue(IRBPoison.getInt8Ty()),
1720             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1721       } else {
1722         // For larger frames call __asan_stack_free_*.
1723         IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1724                               ConstantInt::get(IntptrTy, LocalStackSize),
1725                               OrigStackBase);
1726       }
1727
1728       IRBuilder<> IRBElse(ElseTerm);
1729       poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1730     } else if (HavePoisonedAllocas) {
1731       // If we poisoned some allocas in llvm.lifetime analysis,
1732       // unpoison whole stack frame now.
1733       assert(LocalStackBase == OrigStackBase);
1734       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1735     } else {
1736       poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1737     }
1738   }
1739
1740   // We are done. Remove the old unused alloca instructions.
1741   for (auto AI : AllocaVec)
1742     AI->eraseFromParent();
1743 }
1744
1745 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1746                                          IRBuilder<> &IRB, bool DoPoison) {
1747   // For now just insert the call to ASan runtime.
1748   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1749   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1750   IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1751                            : AsanUnpoisonStackMemoryFunc,
1752                   AddrArg, SizeArg);
1753 }
1754
1755 // Handling llvm.lifetime intrinsics for a given %alloca:
1756 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1757 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1758 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1759 //     could be poisoned by previous llvm.lifetime.end instruction, as the
1760 //     variable may go in and out of scope several times, e.g. in loops).
1761 // (3) if we poisoned at least one %alloca in a function,
1762 //     unpoison the whole stack frame at function exit.
1763
1764 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1765   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1766     // We're intested only in allocas we can handle.
1767     return isInterestingAlloca(*AI) ? AI : nullptr;
1768   // See if we've already calculated (or started to calculate) alloca for a
1769   // given value.
1770   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1771   if (I != AllocaForValue.end())
1772     return I->second;
1773   // Store 0 while we're calculating alloca for value V to avoid
1774   // infinite recursion if the value references itself.
1775   AllocaForValue[V] = nullptr;
1776   AllocaInst *Res = nullptr;
1777   if (CastInst *CI = dyn_cast<CastInst>(V))
1778     Res = findAllocaForValue(CI->getOperand(0));
1779   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1780     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1781       Value *IncValue = PN->getIncomingValue(i);
1782       // Allow self-referencing phi-nodes.
1783       if (IncValue == PN) continue;
1784       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1785       // AI for incoming values should exist and should all be equal.
1786       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1787         return nullptr;
1788       Res = IncValueAI;
1789     }
1790   }
1791   if (Res)
1792     AllocaForValue[V] = Res;
1793   return Res;
1794 }