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