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