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