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