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