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