Revert 242726, it broke ASan on OS X.
[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/Analysis/MemoryBuiltins.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/DIBuilder.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/InlineAsm.h"
37 #include "llvm/IR/InstVisitor.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/LLVMContext.h"
40 #include "llvm/IR/MDBuilder.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/MC/MCSectionMachO.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/DataTypes.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/Endian.h"
48 #include "llvm/Support/SwapByteOrder.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Transforms/Scalar.h"
51 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
52 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
53 #include "llvm/Transforms/Utils/Cloning.h"
54 #include "llvm/Transforms/Utils/Local.h"
55 #include "llvm/Transforms/Utils/ModuleUtils.h"
56 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
57 #include <algorithm>
58 #include <string>
59 #include <system_error>
60
61 using namespace llvm;
62
63 #define DEBUG_TYPE "asan"
64
65 static const uint64_t kDefaultShadowScale = 3;
66 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
67 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
68 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
69 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000;  // < 2G.
70 static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
71 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
72 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
73 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
74 static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
75 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
76 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
77 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
78
79 static const size_t kMinStackMallocSize = 1 << 6;   // 64B
80 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
81 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
82 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
83
84 static const char *const kAsanModuleCtorName = "asan.module_ctor";
85 static const char *const kAsanModuleDtorName = "asan.module_dtor";
86 static const uint64_t kAsanCtorAndDtorPriority = 1;
87 static const char *const kAsanReportErrorTemplate = "__asan_report_";
88 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
89 static const char *const kAsanUnregisterGlobalsName =
90     "__asan_unregister_globals";
91 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
92 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
93 static const char *const kAsanInitName = "__asan_init_v5";
94 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
95 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
96 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
97 static const int kMaxAsanStackMallocSizeClass = 10;
98 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
99 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
100 static const char *const kAsanGenPrefix = "__asan_gen_";
101 static const char *const kSanCovGenPrefix = "__sancov_gen_";
102 static const char *const kAsanPoisonStackMemoryName =
103     "__asan_poison_stack_memory";
104 static const char *const kAsanUnpoisonStackMemoryName =
105     "__asan_unpoison_stack_memory";
106
107 static const char *const kAsanOptionDetectUAR =
108     "__asan_option_detect_stack_use_after_return";
109
110 static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
111 static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
112
113 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
114 static const size_t kNumberOfAccessSizes = 5;
115
116 static const unsigned kAllocaRzSize = 32;
117
118 // Command-line flags.
119 static cl::opt<bool> ClEnableKasan(
120     "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
121     cl::Hidden, cl::init(false));
122
123 // This flag may need to be replaced with -f[no-]asan-reads.
124 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
125                                        cl::desc("instrument read instructions"),
126                                        cl::Hidden, cl::init(true));
127 static cl::opt<bool> ClInstrumentWrites(
128     "asan-instrument-writes", cl::desc("instrument write instructions"),
129     cl::Hidden, cl::init(true));
130 static cl::opt<bool> ClInstrumentAtomics(
131     "asan-instrument-atomics",
132     cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
133     cl::init(true));
134 static cl::opt<bool> ClAlwaysSlowPath(
135     "asan-always-slow-path",
136     cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
137     cl::init(false));
138 // This flag limits the number of instructions to be instrumented
139 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
140 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
141 // set it to 10000.
142 static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
143     "asan-max-ins-per-bb", cl::init(10000),
144     cl::desc("maximal number of instructions to instrument in any given BB"),
145     cl::Hidden);
146 // This flag may need to be replaced with -f[no]asan-stack.
147 static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
148                              cl::Hidden, cl::init(true));
149 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
150                                       cl::desc("Check return-after-free"),
151                                       cl::Hidden, cl::init(true));
152 // This flag may need to be replaced with -f[no]asan-globals.
153 static cl::opt<bool> ClGlobals("asan-globals",
154                                cl::desc("Handle global objects"), cl::Hidden,
155                                cl::init(true));
156 static cl::opt<bool> ClInitializers("asan-initialization-order",
157                                     cl::desc("Handle C++ initializer order"),
158                                     cl::Hidden, cl::init(true));
159 static cl::opt<bool> ClInvalidPointerPairs(
160     "asan-detect-invalid-pointer-pair",
161     cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
162     cl::init(false));
163 static cl::opt<unsigned> ClRealignStack(
164     "asan-realign-stack",
165     cl::desc("Realign stack to the value of this flag (power of two)"),
166     cl::Hidden, cl::init(32));
167 static cl::opt<int> ClInstrumentationWithCallsThreshold(
168     "asan-instrumentation-with-call-threshold",
169     cl::desc(
170         "If the function being instrumented contains more than "
171         "this number of memory accesses, use callbacks instead of "
172         "inline checks (-1 means never use callbacks)."),
173     cl::Hidden, cl::init(7000));
174 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
175     "asan-memory-access-callback-prefix",
176     cl::desc("Prefix for memory access callbacks"), cl::Hidden,
177     cl::init("__asan_"));
178 static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
179                                          cl::desc("instrument dynamic allocas"),
180                                          cl::Hidden, cl::init(false));
181 static cl::opt<bool> ClSkipPromotableAllocas(
182     "asan-skip-promotable-allocas",
183     cl::desc("Do not instrument promotable allocas"), cl::Hidden,
184     cl::init(true));
185
186 // These flags allow to change the shadow mapping.
187 // The shadow mapping looks like
188 //    Shadow = (Mem >> scale) + (1 << offset_log)
189 static cl::opt<int> ClMappingScale("asan-mapping-scale",
190                                    cl::desc("scale of asan shadow mapping"),
191                                    cl::Hidden, cl::init(0));
192
193 // Optimization flags. Not user visible, used mostly for testing
194 // and benchmarking the tool.
195 static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
196                            cl::Hidden, cl::init(true));
197 static cl::opt<bool> ClOptSameTemp(
198     "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
199     cl::Hidden, cl::init(true));
200 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
201                                   cl::desc("Don't instrument scalar globals"),
202                                   cl::Hidden, cl::init(true));
203 static cl::opt<bool> ClOptStack(
204     "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
205     cl::Hidden, cl::init(false));
206
207 static cl::opt<bool> ClCheckLifetime(
208     "asan-check-lifetime",
209     cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
210     cl::init(false));
211
212 static cl::opt<bool> ClDynamicAllocaStack(
213     "asan-stack-dynamic-alloca",
214     cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
215     cl::init(true));
216
217 static cl::opt<uint32_t> ClForceExperiment(
218     "asan-force-experiment",
219     cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
220     cl::init(0));
221
222 // Debug flags.
223 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
224                             cl::init(0));
225 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
226                                  cl::Hidden, cl::init(0));
227 static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
228                                         cl::desc("Debug func"));
229 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
230                                cl::Hidden, cl::init(-1));
231 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
232                                cl::Hidden, cl::init(-1));
233
234 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
235 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
236 STATISTIC(NumOptimizedAccessesToGlobalVar,
237           "Number of optimized accesses to global vars");
238 STATISTIC(NumOptimizedAccessesToStackVar,
239           "Number of optimized accesses to stack vars");
240
241 namespace {
242 /// Frontend-provided metadata for source location.
243 struct LocationMetadata {
244   StringRef Filename;
245   int LineNo;
246   int ColumnNo;
247
248   LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
249
250   bool empty() const { return Filename.empty(); }
251
252   void parse(MDNode *MDN) {
253     assert(MDN->getNumOperands() == 3);
254     MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
255     Filename = DIFilename->getString();
256     LineNo =
257         mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
258     ColumnNo =
259         mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
260   }
261 };
262
263 /// Frontend-provided metadata for global variables.
264 class GlobalsMetadata {
265  public:
266   struct Entry {
267     Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
268     LocationMetadata SourceLoc;
269     StringRef Name;
270     bool IsDynInit;
271     bool IsBlacklisted;
272   };
273
274   GlobalsMetadata() : inited_(false) {}
275
276   void init(Module &M) {
277     assert(!inited_);
278     inited_ = true;
279     NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
280     if (!Globals) return;
281     for (auto MDN : Globals->operands()) {
282       // Metadata node contains the global and the fields of "Entry".
283       assert(MDN->getNumOperands() == 5);
284       auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
285       // The optimizer may optimize away a global entirely.
286       if (!GV) continue;
287       // We can already have an entry for GV if it was merged with another
288       // global.
289       Entry &E = Entries[GV];
290       if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
291         E.SourceLoc.parse(Loc);
292       if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
293         E.Name = Name->getString();
294       ConstantInt *IsDynInit =
295           mdconst::extract<ConstantInt>(MDN->getOperand(3));
296       E.IsDynInit |= IsDynInit->isOne();
297       ConstantInt *IsBlacklisted =
298           mdconst::extract<ConstantInt>(MDN->getOperand(4));
299       E.IsBlacklisted |= IsBlacklisted->isOne();
300     }
301   }
302
303   /// Returns metadata entry for a given global.
304   Entry get(GlobalVariable *G) const {
305     auto Pos = Entries.find(G);
306     return (Pos != Entries.end()) ? Pos->second : Entry();
307   }
308
309  private:
310   bool inited_;
311   DenseMap<GlobalVariable *, Entry> Entries;
312 };
313
314 /// This struct defines the shadow mapping using the rule:
315 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
316 struct ShadowMapping {
317   int Scale;
318   uint64_t Offset;
319   bool OrShadowOffset;
320 };
321
322 static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
323                                       bool IsKasan) {
324   bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
325   bool IsIOS = TargetTriple.isiOS();
326   bool IsFreeBSD = TargetTriple.isOSFreeBSD();
327   bool IsLinux = TargetTriple.isOSLinux();
328   bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
329                  TargetTriple.getArch() == llvm::Triple::ppc64le;
330   bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
331   bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
332                   TargetTriple.getArch() == llvm::Triple::mipsel;
333   bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
334                   TargetTriple.getArch() == llvm::Triple::mips64el;
335   bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
336   bool IsWindows = TargetTriple.isOSWindows();
337
338   ShadowMapping Mapping;
339
340   if (IsAndroid) {
341     // Android is always PIE, which means that the beginning of the address
342     // space is always available.
343     Mapping.Offset = 0;
344   } else if (LongSize == 32) {
345     if (IsMIPS32)
346       Mapping.Offset = kMIPS32_ShadowOffset32;
347     else if (IsFreeBSD)
348       Mapping.Offset = kFreeBSD_ShadowOffset32;
349     else if (IsIOS)
350       Mapping.Offset = kIOSShadowOffset32;
351     else if (IsWindows)
352       Mapping.Offset = kWindowsShadowOffset32;
353     else
354       Mapping.Offset = kDefaultShadowOffset32;
355   } else {  // LongSize == 64
356     if (IsPPC64)
357       Mapping.Offset = kPPC64_ShadowOffset64;
358     else if (IsFreeBSD)
359       Mapping.Offset = kFreeBSD_ShadowOffset64;
360     else if (IsLinux && IsX86_64) {
361       if (IsKasan)
362         Mapping.Offset = kLinuxKasan_ShadowOffset64;
363       else
364         Mapping.Offset = kSmallX86_64ShadowOffset;
365     } else if (IsMIPS64)
366       Mapping.Offset = kMIPS64_ShadowOffset64;
367     else if (IsAArch64)
368       Mapping.Offset = kAArch64_ShadowOffset64;
369     else
370       Mapping.Offset = kDefaultShadowOffset64;
371   }
372
373   Mapping.Scale = kDefaultShadowScale;
374   if (ClMappingScale) {
375     Mapping.Scale = ClMappingScale;
376   }
377
378   // OR-ing shadow offset if more efficient (at least on x86) if the offset
379   // is a power of two, but on ppc64 we have to use add since the shadow
380   // offset is not necessary 1/8-th of the address space.
381   Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
382
383   return Mapping;
384 }
385
386 static size_t RedzoneSizeForScale(int MappingScale) {
387   // Redzone used for stack and globals is at least 32 bytes.
388   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
389   return std::max(32U, 1U << MappingScale);
390 }
391
392 /// AddressSanitizer: instrument the code in module to find memory bugs.
393 struct AddressSanitizer : public FunctionPass {
394   explicit AddressSanitizer(bool CompileKernel = false)
395       : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan) {
396     initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
397   }
398   const char *getPassName() const override {
399     return "AddressSanitizerFunctionPass";
400   }
401   void getAnalysisUsage(AnalysisUsage &AU) const override {
402     AU.addRequired<DominatorTreeWrapperPass>();
403     AU.addRequired<TargetLibraryInfoWrapperPass>();
404   }
405   uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
406     Type *Ty = AI->getAllocatedType();
407     uint64_t SizeInBytes =
408         AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
409     return SizeInBytes;
410   }
411   /// Check if we want (and can) handle this alloca.
412   bool isInterestingAlloca(AllocaInst &AI);
413
414   // Check if we have dynamic alloca.
415   bool isDynamicAlloca(AllocaInst &AI) const {
416     return AI.isArrayAllocation() || !AI.isStaticAlloca();
417   }
418
419   /// If it is an interesting memory access, return the PointerOperand
420   /// and set IsWrite/Alignment. Otherwise return nullptr.
421   Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
422                                    uint64_t *TypeSize, unsigned *Alignment);
423   void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
424                      bool UseCalls, const DataLayout &DL);
425   void instrumentPointerComparisonOrSubtraction(Instruction *I);
426   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
427                          Value *Addr, uint32_t TypeSize, bool IsWrite,
428                          Value *SizeArgument, bool UseCalls, uint32_t Exp);
429   void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
430                                         uint32_t TypeSize, bool IsWrite,
431                                         Value *SizeArgument, bool UseCalls,
432                                         uint32_t Exp);
433   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
434                            Value *ShadowValue, uint32_t TypeSize);
435   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
436                                  bool IsWrite, size_t AccessSizeIndex,
437                                  Value *SizeArgument, uint32_t Exp);
438   void instrumentMemIntrinsic(MemIntrinsic *MI);
439   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
440   bool runOnFunction(Function &F) override;
441   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
442   bool doInitialization(Module &M) override;
443   static char ID;  // Pass identification, replacement for typeid
444
445   DominatorTree &getDominatorTree() const { return *DT; }
446
447  private:
448   void initializeCallbacks(Module &M);
449
450   bool LooksLikeCodeInBug11395(Instruction *I);
451   bool GlobalIsLinkerInitialized(GlobalVariable *G);
452   bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
453                     uint64_t TypeSize) const;
454
455   LLVMContext *C;
456   Triple TargetTriple;
457   int LongSize;
458   bool CompileKernel;
459   Type *IntptrTy;
460   ShadowMapping Mapping;
461   DominatorTree *DT;
462   Function *AsanCtorFunction = nullptr;
463   Function *AsanInitFunction = nullptr;
464   Function *AsanHandleNoReturnFunc;
465   Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
466   // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
467   Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
468   Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
469   // This array is indexed by AccessIsWrite and Experiment.
470   Function *AsanErrorCallbackSized[2][2];
471   Function *AsanMemoryAccessCallbackSized[2][2];
472   Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
473   InlineAsm *EmptyAsm;
474   GlobalsMetadata GlobalsMD;
475   DenseMap<AllocaInst *, bool> ProcessedAllocas;
476
477   friend struct FunctionStackPoisoner;
478 };
479
480 class AddressSanitizerModule : public ModulePass {
481  public:
482   explicit AddressSanitizerModule(bool CompileKernel = false)
483       : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan) {}
484   bool runOnModule(Module &M) override;
485   static char ID;  // Pass identification, replacement for typeid
486   const char *getPassName() const override { return "AddressSanitizerModule"; }
487
488  private:
489   void initializeCallbacks(Module &M);
490
491   bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
492   bool ShouldInstrumentGlobal(GlobalVariable *G);
493   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
494   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
495   size_t MinRedzoneSizeForGlobal() const {
496     return RedzoneSizeForScale(Mapping.Scale);
497   }
498
499   GlobalsMetadata GlobalsMD;
500   bool CompileKernel;
501   Type *IntptrTy;
502   LLVMContext *C;
503   Triple TargetTriple;
504   ShadowMapping Mapping;
505   Function *AsanPoisonGlobals;
506   Function *AsanUnpoisonGlobals;
507   Function *AsanRegisterGlobals;
508   Function *AsanUnregisterGlobals;
509 };
510
511 // Stack poisoning does not play well with exception handling.
512 // When an exception is thrown, we essentially bypass the code
513 // that unpoisones the stack. This is why the run-time library has
514 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
515 // stack in the interceptor. This however does not work inside the
516 // actual function which catches the exception. Most likely because the
517 // compiler hoists the load of the shadow value somewhere too high.
518 // This causes asan to report a non-existing bug on 453.povray.
519 // It sounds like an LLVM bug.
520 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
521   Function &F;
522   AddressSanitizer &ASan;
523   DIBuilder DIB;
524   LLVMContext *C;
525   Type *IntptrTy;
526   Type *IntptrPtrTy;
527   ShadowMapping Mapping;
528
529   SmallVector<AllocaInst *, 16> AllocaVec;
530   SmallVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
531   SmallVector<Instruction *, 8> RetVec;
532   unsigned StackAlignment;
533
534   Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
535       *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
536   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
537   Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
538
539   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
540   struct AllocaPoisonCall {
541     IntrinsicInst *InsBefore;
542     AllocaInst *AI;
543     uint64_t Size;
544     bool DoPoison;
545   };
546   SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
547
548   SmallVector<AllocaInst *, 1> DynamicAllocaVec;
549   SmallVector<IntrinsicInst *, 1> StackRestoreVec;
550   AllocaInst *DynamicAllocaLayout = nullptr;
551
552   // Maps Value to an AllocaInst from which the Value is originated.
553   typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
554   AllocaForValueMapTy AllocaForValue;
555
556   bool HasNonEmptyInlineAsm;
557   std::unique_ptr<CallInst> EmptyInlineAsm;
558
559   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
560       : F(F),
561         ASan(ASan),
562         DIB(*F.getParent(), /*AllowUnresolved*/ false),
563         C(ASan.C),
564         IntptrTy(ASan.IntptrTy),
565         IntptrPtrTy(PointerType::get(IntptrTy, 0)),
566         Mapping(ASan.Mapping),
567         StackAlignment(1 << Mapping.Scale),
568         HasNonEmptyInlineAsm(false),
569         EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
570
571   bool runOnFunction() {
572     if (!ClStack) return false;
573     // Collect alloca, ret, lifetime instructions etc.
574     for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
575
576     if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
577
578     initializeCallbacks(*F.getParent());
579
580     poisonStack();
581
582     if (ClDebugStack) {
583       DEBUG(dbgs() << F);
584     }
585     return true;
586   }
587
588   // Finds all Alloca instructions and puts
589   // poisoned red zones around all of them.
590   // Then unpoison everything back before the function returns.
591   void poisonStack();
592
593   void createDynamicAllocasInitStorage();
594
595   // ----------------------- Visitors.
596   /// \brief Collect all Ret instructions.
597   void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
598
599   void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
600                                         Value *SavedStack) {
601     IRBuilder<> IRB(InstBefore);
602     IRB.CreateCall(AsanAllocasUnpoisonFunc,
603                    {IRB.CreateLoad(DynamicAllocaLayout),
604                     IRB.CreatePtrToInt(SavedStack, IntptrTy)});
605   }
606
607   // Unpoison dynamic allocas redzones.
608   void unpoisonDynamicAllocas() {
609     for (auto &Ret : RetVec)
610       unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
611
612     for (auto &StackRestoreInst : StackRestoreVec)
613       unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
614                                        StackRestoreInst->getOperand(0));
615   }
616
617   // Deploy and poison redzones around dynamic alloca call. To do this, we
618   // should replace this call with another one with changed parameters and
619   // replace all its uses with new address, so
620   //   addr = alloca type, old_size, align
621   // is replaced by
622   //   new_size = (old_size + additional_size) * sizeof(type)
623   //   tmp = alloca i8, new_size, max(align, 32)
624   //   addr = tmp + 32 (first 32 bytes are for the left redzone).
625   // Additional_size is added to make new memory allocation contain not only
626   // requested memory, but also left, partial and right redzones.
627   void handleDynamicAllocaCall(AllocaInst *AI);
628
629   /// \brief Collect Alloca instructions we want (and can) handle.
630   void visitAllocaInst(AllocaInst &AI) {
631     if (!ASan.isInterestingAlloca(AI)) {
632       if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.push_back(&AI);
633       return;
634     }
635
636     StackAlignment = std::max(StackAlignment, AI.getAlignment());
637     if (ASan.isDynamicAlloca(AI))
638       DynamicAllocaVec.push_back(&AI);
639     else
640       AllocaVec.push_back(&AI);
641   }
642
643   /// \brief Collect lifetime intrinsic calls to check for use-after-scope
644   /// errors.
645   void visitIntrinsicInst(IntrinsicInst &II) {
646     Intrinsic::ID ID = II.getIntrinsicID();
647     if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
648     if (!ClCheckLifetime) return;
649     if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
650       return;
651     // Found lifetime intrinsic, add ASan instrumentation if necessary.
652     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
653     // If size argument is undefined, don't do anything.
654     if (Size->isMinusOne()) return;
655     // Check that size doesn't saturate uint64_t and can
656     // be stored in IntptrTy.
657     const uint64_t SizeValue = Size->getValue().getLimitedValue();
658     if (SizeValue == ~0ULL ||
659         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
660       return;
661     // Find alloca instruction that corresponds to llvm.lifetime argument.
662     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
663     if (!AI) return;
664     bool DoPoison = (ID == Intrinsic::lifetime_end);
665     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
666     AllocaPoisonCallVec.push_back(APC);
667   }
668
669   void visitCallInst(CallInst &CI) {
670     HasNonEmptyInlineAsm |=
671         CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
672   }
673
674   // ---------------------- Helpers.
675   void initializeCallbacks(Module &M);
676
677   bool doesDominateAllExits(const Instruction *I) const {
678     for (auto Ret : RetVec) {
679       if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
680     }
681     return true;
682   }
683
684   /// Finds alloca where the value comes from.
685   AllocaInst *findAllocaForValue(Value *V);
686   void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
687                       Value *ShadowBase, bool DoPoison);
688   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
689
690   void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
691                                           int Size);
692   Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
693                                bool Dynamic);
694   PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
695                      Instruction *ThenTerm, Value *ValueIfFalse);
696 };
697
698 }  // namespace
699
700 char AddressSanitizer::ID = 0;
701 INITIALIZE_PASS_BEGIN(
702     AddressSanitizer, "asan",
703     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
704     false)
705 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
706 INITIALIZE_PASS_END(
707     AddressSanitizer, "asan",
708     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
709     false)
710 FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel) {
711   return new AddressSanitizer(CompileKernel);
712 }
713
714 char AddressSanitizerModule::ID = 0;
715 INITIALIZE_PASS(
716     AddressSanitizerModule, "asan-module",
717     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
718     "ModulePass",
719     false, false)
720 ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel) {
721   return new AddressSanitizerModule(CompileKernel);
722 }
723
724 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
725   size_t Res = countTrailingZeros(TypeSize / 8);
726   assert(Res < kNumberOfAccessSizes);
727   return Res;
728 }
729
730 // \brief Create a constant for Str so that we can pass it to the run-time lib.
731 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
732                                                     bool AllowMerging) {
733   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
734   // We use private linkage for module-local strings. If they can be merged
735   // with another one, we set the unnamed_addr attribute.
736   GlobalVariable *GV =
737       new GlobalVariable(M, StrConst->getType(), true,
738                          GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
739   if (AllowMerging) GV->setUnnamedAddr(true);
740   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
741   return GV;
742 }
743
744 /// \brief Create a global describing a source location.
745 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
746                                                        LocationMetadata MD) {
747   Constant *LocData[] = {
748       createPrivateGlobalForString(M, MD.Filename, true),
749       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
750       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
751   };
752   auto LocStruct = ConstantStruct::getAnon(LocData);
753   auto GV = new GlobalVariable(M, LocStruct->getType(), true,
754                                GlobalValue::PrivateLinkage, LocStruct,
755                                kAsanGenPrefix);
756   GV->setUnnamedAddr(true);
757   return GV;
758 }
759
760 static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
761   return G->getName().find(kAsanGenPrefix) == 0 ||
762          G->getName().find(kSanCovGenPrefix) == 0;
763 }
764
765 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
766   // Shadow >> scale
767   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
768   if (Mapping.Offset == 0) return Shadow;
769   // (Shadow >> scale) | offset
770   if (Mapping.OrShadowOffset)
771     return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
772   else
773     return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
774 }
775
776 // Instrument memset/memmove/memcpy
777 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
778   IRBuilder<> IRB(MI);
779   if (isa<MemTransferInst>(MI)) {
780     IRB.CreateCall(
781         isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
782         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
783          IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
784          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
785   } else if (isa<MemSetInst>(MI)) {
786     IRB.CreateCall(
787         AsanMemset,
788         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
789          IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
790          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
791   }
792   MI->eraseFromParent();
793 }
794
795 /// Check if we want (and can) handle this alloca.
796 bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
797   auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
798
799   if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
800     return PreviouslySeenAllocaInfo->getSecond();
801
802   bool IsInteresting =
803       (AI.getAllocatedType()->isSized() &&
804        // alloca() may be called with 0 size, ignore it.
805        getAllocaSizeInBytes(&AI) > 0 &&
806        // We are only interested in allocas not promotable to registers.
807        // Promotable allocas are common under -O0.
808        (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI) ||
809         isDynamicAlloca(AI)));
810
811   ProcessedAllocas[&AI] = IsInteresting;
812   return IsInteresting;
813 }
814
815 /// If I is an interesting memory access, return the PointerOperand
816 /// and set IsWrite/Alignment. Otherwise return nullptr.
817 Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
818                                                    bool *IsWrite,
819                                                    uint64_t *TypeSize,
820                                                    unsigned *Alignment) {
821   // Skip memory accesses inserted by another instrumentation.
822   if (I->getMetadata("nosanitize")) return nullptr;
823
824   Value *PtrOperand = nullptr;
825   const DataLayout &DL = I->getModule()->getDataLayout();
826   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
827     if (!ClInstrumentReads) return nullptr;
828     *IsWrite = false;
829     *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
830     *Alignment = LI->getAlignment();
831     PtrOperand = LI->getPointerOperand();
832   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
833     if (!ClInstrumentWrites) return nullptr;
834     *IsWrite = true;
835     *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
836     *Alignment = SI->getAlignment();
837     PtrOperand = SI->getPointerOperand();
838   } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
839     if (!ClInstrumentAtomics) return nullptr;
840     *IsWrite = true;
841     *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
842     *Alignment = 0;
843     PtrOperand = RMW->getPointerOperand();
844   } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
845     if (!ClInstrumentAtomics) return nullptr;
846     *IsWrite = true;
847     *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
848     *Alignment = 0;
849     PtrOperand = XCHG->getPointerOperand();
850   }
851
852   // Treat memory accesses to promotable allocas as non-interesting since they
853   // will not cause memory violations. This greatly speeds up the instrumented
854   // executable at -O0.
855   if (ClSkipPromotableAllocas)
856     if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
857       return isInterestingAlloca(*AI) ? AI : nullptr;
858
859   return PtrOperand;
860 }
861
862 static bool isPointerOperand(Value *V) {
863   return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
864 }
865
866 // This is a rough heuristic; it may cause both false positives and
867 // false negatives. The proper implementation requires cooperation with
868 // the frontend.
869 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
870   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
871     if (!Cmp->isRelational()) return false;
872   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
873     if (BO->getOpcode() != Instruction::Sub) return false;
874   } else {
875     return false;
876   }
877   if (!isPointerOperand(I->getOperand(0)) ||
878       !isPointerOperand(I->getOperand(1)))
879     return false;
880   return true;
881 }
882
883 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
884   // If a global variable does not have dynamic initialization we don't
885   // have to instrument it.  However, if a global does not have initializer
886   // at all, we assume it has dynamic initializer (in other TU).
887   return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
888 }
889
890 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
891     Instruction *I) {
892   IRBuilder<> IRB(I);
893   Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
894   Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
895   for (int i = 0; i < 2; i++) {
896     if (Param[i]->getType()->isPointerTy())
897       Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
898   }
899   IRB.CreateCall(F, Param);
900 }
901
902 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
903                                      Instruction *I, bool UseCalls,
904                                      const DataLayout &DL) {
905   bool IsWrite = false;
906   unsigned Alignment = 0;
907   uint64_t TypeSize = 0;
908   Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
909   assert(Addr);
910
911   // Optimization experiments.
912   // The experiments can be used to evaluate potential optimizations that remove
913   // instrumentation (assess false negatives). Instead of completely removing
914   // some instrumentation, you set Exp to a non-zero value (mask of optimization
915   // experiments that want to remove instrumentation of this instruction).
916   // If Exp is non-zero, this pass will emit special calls into runtime
917   // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
918   // make runtime terminate the program in a special way (with a different
919   // exit status). Then you run the new compiler on a buggy corpus, collect
920   // the special terminations (ideally, you don't see them at all -- no false
921   // negatives) and make the decision on the optimization.
922   uint32_t Exp = ClForceExperiment;
923
924   if (ClOpt && ClOptGlobals) {
925     // If initialization order checking is disabled, a simple access to a
926     // dynamically initialized global is always valid.
927     GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
928     if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
929         isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
930       NumOptimizedAccessesToGlobalVar++;
931       return;
932     }
933   }
934
935   if (ClOpt && ClOptStack) {
936     // A direct inbounds access to a stack variable is always valid.
937     if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
938         isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
939       NumOptimizedAccessesToStackVar++;
940       return;
941     }
942   }
943
944   if (IsWrite)
945     NumInstrumentedWrites++;
946   else
947     NumInstrumentedReads++;
948
949   unsigned Granularity = 1 << Mapping.Scale;
950   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
951   // if the data is properly aligned.
952   if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
953        TypeSize == 128) &&
954       (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
955     return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
956                              Exp);
957   instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
958                                    UseCalls, Exp);
959 }
960
961 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
962                                                  Value *Addr, bool IsWrite,
963                                                  size_t AccessSizeIndex,
964                                                  Value *SizeArgument,
965                                                  uint32_t Exp) {
966   IRBuilder<> IRB(InsertBefore);
967   Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
968   CallInst *Call = nullptr;
969   if (SizeArgument) {
970     if (Exp == 0)
971       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
972                             {Addr, SizeArgument});
973     else
974       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
975                             {Addr, SizeArgument, ExpVal});
976   } else {
977     if (Exp == 0)
978       Call =
979           IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
980     else
981       Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
982                             {Addr, ExpVal});
983   }
984
985   // We don't do Call->setDoesNotReturn() because the BB already has
986   // UnreachableInst at the end.
987   // This EmptyAsm is required to avoid callback merge.
988   IRB.CreateCall(EmptyAsm, {});
989   return Call;
990 }
991
992 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
993                                            Value *ShadowValue,
994                                            uint32_t TypeSize) {
995   size_t Granularity = 1 << Mapping.Scale;
996   // Addr & (Granularity - 1)
997   Value *LastAccessedByte =
998       IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
999   // (Addr & (Granularity - 1)) + size - 1
1000   if (TypeSize / 8 > 1)
1001     LastAccessedByte = IRB.CreateAdd(
1002         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1003   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1004   LastAccessedByte =
1005       IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1006   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1007   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1008 }
1009
1010 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1011                                          Instruction *InsertBefore, Value *Addr,
1012                                          uint32_t TypeSize, bool IsWrite,
1013                                          Value *SizeArgument, bool UseCalls,
1014                                          uint32_t Exp) {
1015   IRBuilder<> IRB(InsertBefore);
1016   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1017   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1018
1019   if (UseCalls) {
1020     if (Exp == 0)
1021       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1022                      AddrLong);
1023     else
1024       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1025                      {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1026     return;
1027   }
1028
1029   Type *ShadowTy =
1030       IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1031   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1032   Value *ShadowPtr = memToShadow(AddrLong, IRB);
1033   Value *CmpVal = Constant::getNullValue(ShadowTy);
1034   Value *ShadowValue =
1035       IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1036
1037   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1038   size_t Granularity = 1 << Mapping.Scale;
1039   TerminatorInst *CrashTerm = nullptr;
1040
1041   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1042     // We use branch weights for the slow path check, to indicate that the slow
1043     // path is rarely taken. This seems to be the case for SPEC benchmarks.
1044     TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1045         Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1046     assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1047     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1048     IRB.SetInsertPoint(CheckTerm);
1049     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1050     BasicBlock *CrashBlock =
1051         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1052     CrashTerm = new UnreachableInst(*C, CrashBlock);
1053     BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1054     ReplaceInstWithInst(CheckTerm, NewTerm);
1055   } else {
1056     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
1057   }
1058
1059   Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1060                                          AccessSizeIndex, SizeArgument, Exp);
1061   Crash->setDebugLoc(OrigIns->getDebugLoc());
1062 }
1063
1064 // Instrument unusual size or unusual alignment.
1065 // We can not do it with a single check, so we do 1-byte check for the first
1066 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1067 // to report the actual access size.
1068 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1069     Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1070     Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1071   IRBuilder<> IRB(I);
1072   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1073   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1074   if (UseCalls) {
1075     if (Exp == 0)
1076       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1077                      {AddrLong, Size});
1078     else
1079       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1080                      {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1081   } else {
1082     Value *LastByte = IRB.CreateIntToPtr(
1083         IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1084         Addr->getType());
1085     instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1086     instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1087   }
1088 }
1089
1090 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1091                                                   GlobalValue *ModuleName) {
1092   // Set up the arguments to our poison/unpoison functions.
1093   IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
1094
1095   // Add a call to poison all external globals before the given function starts.
1096   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1097   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1098
1099   // Add calls to unpoison all globals before each return instruction.
1100   for (auto &BB : GlobalInit.getBasicBlockList())
1101     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1102       CallInst::Create(AsanUnpoisonGlobals, "", RI);
1103 }
1104
1105 void AddressSanitizerModule::createInitializerPoisonCalls(
1106     Module &M, GlobalValue *ModuleName) {
1107   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1108
1109   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1110   for (Use &OP : CA->operands()) {
1111     if (isa<ConstantAggregateZero>(OP)) continue;
1112     ConstantStruct *CS = cast<ConstantStruct>(OP);
1113
1114     // Must have a function or null ptr.
1115     if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1116       if (F->getName() == kAsanModuleCtorName) continue;
1117       ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1118       // Don't instrument CTORs that will run before asan.module_ctor.
1119       if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1120       poisonOneInitializer(*F, ModuleName);
1121     }
1122   }
1123 }
1124
1125 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1126   Type *Ty = cast<PointerType>(G->getType())->getElementType();
1127   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1128
1129   if (GlobalsMD.get(G).IsBlacklisted) return false;
1130   if (!Ty->isSized()) return false;
1131   if (!G->hasInitializer()) return false;
1132   if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
1133   // Touch only those globals that will not be defined in other modules.
1134   // Don't handle ODR linkage types and COMDATs since other modules may be built
1135   // without ASan.
1136   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1137       G->getLinkage() != GlobalVariable::PrivateLinkage &&
1138       G->getLinkage() != GlobalVariable::InternalLinkage)
1139     return false;
1140   if (G->hasComdat()) return false;
1141   // Two problems with thread-locals:
1142   //   - The address of the main thread's copy can't be computed at link-time.
1143   //   - Need to poison all copies, not just the main thread's one.
1144   if (G->isThreadLocal()) return false;
1145   // For now, just ignore this Global if the alignment is large.
1146   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1147
1148   if (G->hasSection()) {
1149     StringRef Section(G->getSection());
1150
1151     // Globals from llvm.metadata aren't emitted, do not instrument them.
1152     if (Section == "llvm.metadata") return false;
1153     // Do not instrument globals from special LLVM sections.
1154     if (Section.find("__llvm") != StringRef::npos) return false;
1155
1156     // Callbacks put into the CRT initializer/terminator sections
1157     // should not be instrumented.
1158     // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1159     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1160     if (Section.startswith(".CRT")) {
1161       DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1162       return false;
1163     }
1164
1165     if (TargetTriple.isOSBinFormatMachO()) {
1166       StringRef ParsedSegment, ParsedSection;
1167       unsigned TAA = 0, StubSize = 0;
1168       bool TAAParsed;
1169       std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1170           Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1171       if (!ErrorCode.empty()) {
1172         assert(false && "Invalid section specifier.");
1173         return false;
1174       }
1175
1176       // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1177       // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1178       // them.
1179       if (ParsedSegment == "__OBJC" ||
1180           (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1181         DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1182         return false;
1183       }
1184       // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1185       // Constant CFString instances are compiled in the following way:
1186       //  -- the string buffer is emitted into
1187       //     __TEXT,__cstring,cstring_literals
1188       //  -- the constant NSConstantString structure referencing that buffer
1189       //     is placed into __DATA,__cfstring
1190       // Therefore there's no point in placing redzones into __DATA,__cfstring.
1191       // Moreover, it causes the linker to crash on OS X 10.7
1192       if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1193         DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1194         return false;
1195       }
1196       // The linker merges the contents of cstring_literals and removes the
1197       // trailing zeroes.
1198       if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1199         DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1200         return false;
1201       }
1202     }
1203   }
1204
1205   return true;
1206 }
1207
1208 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1209   IRBuilder<> IRB(*C);
1210   // Declare our poisoning and unpoisoning functions.
1211   AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1212       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1213   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1214   AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1215       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1216   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1217   // Declare functions that register/unregister globals.
1218   AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1219       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1220   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1221   AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1222       M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1223                             IntptrTy, IntptrTy, nullptr));
1224   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1225 }
1226
1227 // This function replaces all global variables with new variables that have
1228 // trailing redzones. It also creates a function that poisons
1229 // redzones and inserts this function into llvm.global_ctors.
1230 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1231   GlobalsMD.init(M);
1232
1233   SmallVector<GlobalVariable *, 16> GlobalsToChange;
1234
1235   for (auto &G : M.globals()) {
1236     if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
1237   }
1238
1239   size_t n = GlobalsToChange.size();
1240   if (n == 0) return false;
1241
1242   // A global is described by a structure
1243   //   size_t beg;
1244   //   size_t size;
1245   //   size_t size_with_redzone;
1246   //   const char *name;
1247   //   const char *module_name;
1248   //   size_t has_dynamic_init;
1249   //   void *source_location;
1250   // We initialize an array of such structures and pass it to a run-time call.
1251   StructType *GlobalStructTy =
1252       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1253                       IntptrTy, IntptrTy, nullptr);
1254   SmallVector<Constant *, 16> Initializers(n);
1255
1256   bool HasDynamicallyInitializedGlobals = false;
1257
1258   // We shouldn't merge same module names, as this string serves as unique
1259   // module ID in runtime.
1260   GlobalVariable *ModuleName = createPrivateGlobalForString(
1261       M, M.getModuleIdentifier(), /*AllowMerging*/ false);
1262
1263   auto &DL = M.getDataLayout();
1264   for (size_t i = 0; i < n; i++) {
1265     static const uint64_t kMaxGlobalRedzone = 1 << 18;
1266     GlobalVariable *G = GlobalsToChange[i];
1267
1268     auto MD = GlobalsMD.get(G);
1269     // Create string holding the global name (use global name from metadata
1270     // if it's available, otherwise just write the name of global variable).
1271     GlobalVariable *Name = createPrivateGlobalForString(
1272         M, MD.Name.empty() ? G->getName() : MD.Name,
1273         /*AllowMerging*/ true);
1274
1275     PointerType *PtrTy = cast<PointerType>(G->getType());
1276     Type *Ty = PtrTy->getElementType();
1277     uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1278     uint64_t MinRZ = MinRedzoneSizeForGlobal();
1279     // MinRZ <= RZ <= kMaxGlobalRedzone
1280     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1281     uint64_t RZ = std::max(
1282         MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1283     uint64_t RightRedzoneSize = RZ;
1284     // Round up to MinRZ
1285     if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1286     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1287     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1288
1289     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1290     Constant *NewInitializer =
1291         ConstantStruct::get(NewTy, G->getInitializer(),
1292                             Constant::getNullValue(RightRedZoneTy), nullptr);
1293
1294     // Create a new global variable with enough space for a redzone.
1295     GlobalValue::LinkageTypes Linkage = G->getLinkage();
1296     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1297       Linkage = GlobalValue::InternalLinkage;
1298     GlobalVariable *NewGlobal =
1299         new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1300                            "", G, G->getThreadLocalMode());
1301     NewGlobal->copyAttributesFrom(G);
1302     NewGlobal->setAlignment(MinRZ);
1303
1304     Value *Indices2[2];
1305     Indices2[0] = IRB.getInt32(0);
1306     Indices2[1] = IRB.getInt32(0);
1307
1308     G->replaceAllUsesWith(
1309         ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
1310     NewGlobal->takeName(G);
1311     G->eraseFromParent();
1312
1313     Constant *SourceLoc;
1314     if (!MD.SourceLoc.empty()) {
1315       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1316       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1317     } else {
1318       SourceLoc = ConstantInt::get(IntptrTy, 0);
1319     }
1320
1321     Initializers[i] = ConstantStruct::get(
1322         GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1323         ConstantInt::get(IntptrTy, SizeInBytes),
1324         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1325         ConstantExpr::getPointerCast(Name, IntptrTy),
1326         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1327         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
1328
1329     if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
1330
1331     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1332   }
1333
1334   ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1335   GlobalVariable *AllGlobals = new GlobalVariable(
1336       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1337       ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1338
1339   // Create calls for poisoning before initializers run and unpoisoning after.
1340   if (HasDynamicallyInitializedGlobals)
1341     createInitializerPoisonCalls(M, ModuleName);
1342   IRB.CreateCall(AsanRegisterGlobals,
1343                  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1344                   ConstantInt::get(IntptrTy, n)});
1345
1346   // We also need to unregister globals at the end, e.g. when a shared library
1347   // gets closed.
1348   Function *AsanDtorFunction =
1349       Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1350                        GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1351   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1352   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1353   IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1354                       {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1355                        ConstantInt::get(IntptrTy, n)});
1356   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1357
1358   DEBUG(dbgs() << M);
1359   return true;
1360 }
1361
1362 bool AddressSanitizerModule::runOnModule(Module &M) {
1363   C = &(M.getContext());
1364   int LongSize = M.getDataLayout().getPointerSizeInBits();
1365   IntptrTy = Type::getIntNTy(*C, LongSize);
1366   TargetTriple = Triple(M.getTargetTriple());
1367   Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1368   initializeCallbacks(M);
1369
1370   bool Changed = false;
1371
1372   // TODO(glider): temporarily disabled globals instrumentation for KASan.
1373   if (ClGlobals && !CompileKernel) {
1374     Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1375     assert(CtorFunc);
1376     IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1377     Changed |= InstrumentGlobals(IRB, M);
1378   }
1379
1380   return Changed;
1381 }
1382
1383 void AddressSanitizer::initializeCallbacks(Module &M) {
1384   IRBuilder<> IRB(*C);
1385   // Create __asan_report* callbacks.
1386   // IsWrite, TypeSize and Exp are encoded in the function name.
1387   for (int Exp = 0; Exp < 2; Exp++) {
1388     for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1389       const std::string TypeStr = AccessIsWrite ? "store" : "load";
1390       const std::string ExpStr = Exp ? "exp_" : "";
1391       const std::string SuffixStr = CompileKernel ? "N" : "_n";
1392       const std::string EndingStr = CompileKernel ? "_noabort" : "";
1393       const Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1394       // TODO(glider): for KASan builds add _noabort to error reporting
1395       // functions and make them actually noabort (remove the UnreachableInst).
1396       AsanErrorCallbackSized[AccessIsWrite][Exp] =
1397           checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1398               kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr,
1399               IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1400       AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
1401           checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1402               ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
1403               IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1404       for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1405            AccessSizeIndex++) {
1406         const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1407         AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1408             checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1409                 kAsanReportErrorTemplate + ExpStr + Suffix,
1410                 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1411         AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1412             checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1413                 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1414                 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1415       }
1416     }
1417   }
1418
1419   const std::string MemIntrinCallbackPrefix =
1420       CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
1421   AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1422       MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1423       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1424   AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1425       MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1426       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1427   AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1428       MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1429       IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1430
1431   AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
1432       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1433
1434   AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1435       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1436   AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1437       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1438   // We insert an empty inline asm after __asan_report* to avoid callback merge.
1439   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1440                             StringRef(""), StringRef(""),
1441                             /*hasSideEffects=*/true);
1442 }
1443
1444 // virtual
1445 bool AddressSanitizer::doInitialization(Module &M) {
1446   // Initialize the private fields. No one has accessed them before.
1447
1448   GlobalsMD.init(M);
1449
1450   C = &(M.getContext());
1451   LongSize = M.getDataLayout().getPointerSizeInBits();
1452   IntptrTy = Type::getIntNTy(*C, LongSize);
1453   TargetTriple = Triple(M.getTargetTriple());
1454
1455   if (!CompileKernel) {
1456     std::tie(AsanCtorFunction, AsanInitFunction) =
1457         createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName, kAsanInitName,
1458                                             /*InitArgTypes=*/{},
1459                                             /*InitArgs=*/{});
1460     appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1461   }
1462   Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1463   return true;
1464 }
1465
1466 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1467   // For each NSObject descendant having a +load method, this method is invoked
1468   // by the ObjC runtime before any of the static constructors is called.
1469   // Therefore we need to instrument such methods with a call to __asan_init
1470   // at the beginning in order to initialize our runtime before any access to
1471   // the shadow memory.
1472   // We cannot just ignore these methods, because they may call other
1473   // instrumented functions.
1474   if (F.getName().find(" load]") != std::string::npos) {
1475     IRBuilder<> IRB(F.begin()->begin());
1476     IRB.CreateCall(AsanInitFunction, {});
1477     return true;
1478   }
1479   return false;
1480 }
1481
1482 bool AddressSanitizer::runOnFunction(Function &F) {
1483   if (&F == AsanCtorFunction) return false;
1484   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1485   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1486   initializeCallbacks(*F.getParent());
1487
1488   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1489
1490   // If needed, insert __asan_init before checking for SanitizeAddress attr.
1491   maybeInsertAsanInitAtFunctionEntry(F);
1492
1493   if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
1494
1495   if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
1496
1497   // We want to instrument every address only once per basic block (unless there
1498   // are calls between uses).
1499   SmallSet<Value *, 16> TempsToInstrument;
1500   SmallVector<Instruction *, 16> ToInstrument;
1501   SmallVector<Instruction *, 8> NoReturnCalls;
1502   SmallVector<BasicBlock *, 16> AllBlocks;
1503   SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
1504   int NumAllocas = 0;
1505   bool IsWrite;
1506   unsigned Alignment;
1507   uint64_t TypeSize;
1508
1509   // Fill the set of memory operations to instrument.
1510   for (auto &BB : F) {
1511     AllBlocks.push_back(&BB);
1512     TempsToInstrument.clear();
1513     int NumInsnsPerBB = 0;
1514     for (auto &Inst : BB) {
1515       if (LooksLikeCodeInBug11395(&Inst)) return false;
1516       if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1517                                                   &Alignment)) {
1518         if (ClOpt && ClOptSameTemp) {
1519           if (!TempsToInstrument.insert(Addr).second)
1520             continue;  // We've seen this temp in the current BB.
1521         }
1522       } else if (ClInvalidPointerPairs &&
1523                  isInterestingPointerComparisonOrSubtraction(&Inst)) {
1524         PointerComparisonsOrSubtracts.push_back(&Inst);
1525         continue;
1526       } else if (isa<MemIntrinsic>(Inst)) {
1527         // ok, take it.
1528       } else {
1529         if (isa<AllocaInst>(Inst)) NumAllocas++;
1530         CallSite CS(&Inst);
1531         if (CS) {
1532           // A call inside BB.
1533           TempsToInstrument.clear();
1534           if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
1535         }
1536         continue;
1537       }
1538       ToInstrument.push_back(&Inst);
1539       NumInsnsPerBB++;
1540       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
1541     }
1542   }
1543
1544   bool UseCalls =
1545       CompileKernel ||
1546       (ClInstrumentationWithCallsThreshold >= 0 &&
1547        ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
1548   const TargetLibraryInfo *TLI =
1549       &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1550   const DataLayout &DL = F.getParent()->getDataLayout();
1551   ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1552                                      /*RoundToAlign=*/true);
1553
1554   // Instrument.
1555   int NumInstrumented = 0;
1556   for (auto Inst : ToInstrument) {
1557     if (ClDebugMin < 0 || ClDebugMax < 0 ||
1558         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1559       if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
1560         instrumentMop(ObjSizeVis, Inst, UseCalls,
1561                       F.getParent()->getDataLayout());
1562       else
1563         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1564     }
1565     NumInstrumented++;
1566   }
1567
1568   FunctionStackPoisoner FSP(F, *this);
1569   bool ChangedStack = FSP.runOnFunction();
1570
1571   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1572   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1573   for (auto CI : NoReturnCalls) {
1574     IRBuilder<> IRB(CI);
1575     IRB.CreateCall(AsanHandleNoReturnFunc, {});
1576   }
1577
1578   for (auto Inst : PointerComparisonsOrSubtracts) {
1579     instrumentPointerComparisonOrSubtraction(Inst);
1580     NumInstrumented++;
1581   }
1582
1583   bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1584
1585   DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1586
1587   return res;
1588 }
1589
1590 // Workaround for bug 11395: we don't want to instrument stack in functions
1591 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1592 // FIXME: remove once the bug 11395 is fixed.
1593 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1594   if (LongSize != 32) return false;
1595   CallInst *CI = dyn_cast<CallInst>(I);
1596   if (!CI || !CI->isInlineAsm()) return false;
1597   if (CI->getNumArgOperands() <= 5) return false;
1598   // We have inline assembly with quite a few arguments.
1599   return true;
1600 }
1601
1602 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1603   IRBuilder<> IRB(*C);
1604   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1605     std::string Suffix = itostr(i);
1606     AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1607         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1608                               IntptrTy, nullptr));
1609     AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
1610         M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1611                               IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1612   }
1613   AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1614       M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1615                             IntptrTy, IntptrTy, nullptr));
1616   AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1617       M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1618                             IntptrTy, IntptrTy, nullptr));
1619   AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1620       kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1621   AsanAllocasUnpoisonFunc =
1622       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1623           kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1624 }
1625
1626 void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1627                                            IRBuilder<> &IRB, Value *ShadowBase,
1628                                            bool DoPoison) {
1629   size_t n = ShadowBytes.size();
1630   size_t i = 0;
1631   // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1632   // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1633   // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1634   for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1635        LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1636     for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1637       uint64_t Val = 0;
1638       for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
1639         if (F.getParent()->getDataLayout().isLittleEndian())
1640           Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1641         else
1642           Val = (Val << 8) | ShadowBytes[i + j];
1643       }
1644       if (!Val) continue;
1645       Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1646       Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1647       Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1648       IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
1649     }
1650   }
1651 }
1652
1653 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
1654 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1655 static int StackMallocSizeClass(uint64_t LocalStackSize) {
1656   assert(LocalStackSize <= kMaxStackMallocSize);
1657   uint64_t MaxSize = kMinStackMallocSize;
1658   for (int i = 0;; i++, MaxSize *= 2)
1659     if (LocalStackSize <= MaxSize) return i;
1660   llvm_unreachable("impossible LocalStackSize");
1661 }
1662
1663 // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1664 // We can not use MemSet intrinsic because it may end up calling the actual
1665 // memset. Size is a multiple of 8.
1666 // Currently this generates 8-byte stores on x86_64; it may be better to
1667 // generate wider stores.
1668 void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1669     IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1670   assert(!(Size % 8));
1671
1672   // kAsanStackAfterReturnMagic is 0xf5.
1673   const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
1674
1675   for (int i = 0; i < Size; i += 8) {
1676     Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1677     IRB.CreateStore(
1678         ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1679         IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1680   }
1681 }
1682
1683 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1684                                           Value *ValueIfTrue,
1685                                           Instruction *ThenTerm,
1686                                           Value *ValueIfFalse) {
1687   PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1688   BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1689   PHI->addIncoming(ValueIfFalse, CondBlock);
1690   BasicBlock *ThenBlock = ThenTerm->getParent();
1691   PHI->addIncoming(ValueIfTrue, ThenBlock);
1692   return PHI;
1693 }
1694
1695 Value *FunctionStackPoisoner::createAllocaForLayout(
1696     IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1697   AllocaInst *Alloca;
1698   if (Dynamic) {
1699     Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1700                               ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1701                               "MyAlloca");
1702   } else {
1703     Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1704                               nullptr, "MyAlloca");
1705     assert(Alloca->isStaticAlloca());
1706   }
1707   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1708   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1709   Alloca->setAlignment(FrameAlignment);
1710   return IRB.CreatePointerCast(Alloca, IntptrTy);
1711 }
1712
1713 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1714   BasicBlock &FirstBB = *F.begin();
1715   IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1716   DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1717   IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1718   DynamicAllocaLayout->setAlignment(32);
1719 }
1720
1721 void FunctionStackPoisoner::poisonStack() {
1722   assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1723
1724   if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
1725     // Handle dynamic allocas.
1726     createDynamicAllocasInitStorage();
1727     for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
1728
1729     unpoisonDynamicAllocas();
1730   }
1731
1732   if (AllocaVec.size() == 0) return;
1733
1734   int StackMallocIdx = -1;
1735   DebugLoc EntryDebugLocation;
1736   if (auto SP = getDISubprogram(&F))
1737     EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
1738
1739   Instruction *InsBefore = AllocaVec[0];
1740   IRBuilder<> IRB(InsBefore);
1741   IRB.SetCurrentDebugLocation(EntryDebugLocation);
1742
1743   // Make sure non-instrumented allocas stay in the first basic block.
1744   // Otherwise, debug info is broken, because only first-basic-block allocas are
1745   // treated as regular stack slots.
1746   for (auto *AI : NonInstrumentedStaticAllocaVec) AI->moveBefore(InsBefore);
1747
1748   SmallVector<ASanStackVariableDescription, 16> SVD;
1749   SVD.reserve(AllocaVec.size());
1750   for (AllocaInst *AI : AllocaVec) {
1751     ASanStackVariableDescription D = {AI->getName().data(),
1752                                       ASan.getAllocaSizeInBytes(AI),
1753                                       AI->getAlignment(), AI, 0};
1754     SVD.push_back(D);
1755   }
1756   // Minimal header size (left redzone) is 4 pointers,
1757   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1758   size_t MinHeaderSize = ASan.LongSize / 2;
1759   ASanStackFrameLayout L;
1760   ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1761   DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1762   uint64_t LocalStackSize = L.FrameSize;
1763   bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
1764                        LocalStackSize <= kMaxStackMallocSize;
1765   // Don't do dynamic alloca or stack malloc in presence of inline asm:
1766   // too often it makes assumptions on which registers are available.
1767   bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
1768   DoStackMalloc &= !HasNonEmptyInlineAsm;
1769
1770   Value *StaticAlloca =
1771       DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1772
1773   Value *FakeStack;
1774   Value *LocalStackBase;
1775
1776   if (DoStackMalloc) {
1777     // void *FakeStack = __asan_option_detect_stack_use_after_return
1778     //     ? __asan_stack_malloc_N(LocalStackSize)
1779     //     : nullptr;
1780     // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
1781     Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1782         kAsanOptionDetectUAR, IRB.getInt32Ty());
1783     Value *UARIsEnabled =
1784         IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1785                          Constant::getNullValue(IRB.getInt32Ty()));
1786     Instruction *Term =
1787         SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
1788     IRBuilder<> IRBIf(Term);
1789     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1790     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1791     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1792     Value *FakeStackValue =
1793         IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1794                          ConstantInt::get(IntptrTy, LocalStackSize));
1795     IRB.SetInsertPoint(InsBefore);
1796     IRB.SetCurrentDebugLocation(EntryDebugLocation);
1797     FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1798                           ConstantInt::get(IntptrTy, 0));
1799
1800     Value *NoFakeStack =
1801         IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1802     Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1803     IRBIf.SetInsertPoint(Term);
1804     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1805     Value *AllocaValue =
1806         DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1807     IRB.SetInsertPoint(InsBefore);
1808     IRB.SetCurrentDebugLocation(EntryDebugLocation);
1809     LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1810   } else {
1811     // void *FakeStack = nullptr;
1812     // void *LocalStackBase = alloca(LocalStackSize);
1813     FakeStack = ConstantInt::get(IntptrTy, 0);
1814     LocalStackBase =
1815         DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
1816   }
1817
1818   // Insert poison calls for lifetime intrinsics for alloca.
1819   bool HavePoisonedAllocas = false;
1820   for (const auto &APC : AllocaPoisonCallVec) {
1821     assert(APC.InsBefore);
1822     assert(APC.AI);
1823     IRBuilder<> IRB(APC.InsBefore);
1824     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1825     HavePoisonedAllocas |= APC.DoPoison;
1826   }
1827
1828   // Replace Alloca instructions with base+offset.
1829   for (const auto &Desc : SVD) {
1830     AllocaInst *AI = Desc.AI;
1831     Value *NewAllocaPtr = IRB.CreateIntToPtr(
1832         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
1833         AI->getType());
1834     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
1835     AI->replaceAllUsesWith(NewAllocaPtr);
1836   }
1837
1838   // The left-most redzone has enough space for at least 4 pointers.
1839   // Write the Magic value to redzone[0].
1840   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1841   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1842                   BasePlus0);
1843   // Write the frame description constant to redzone[1].
1844   Value *BasePlus1 = IRB.CreateIntToPtr(
1845       IRB.CreateAdd(LocalStackBase,
1846                     ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1847       IntptrPtrTy);
1848   GlobalVariable *StackDescriptionGlobal =
1849       createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1850                                    /*AllowMerging*/ true);
1851   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
1852   IRB.CreateStore(Description, BasePlus1);
1853   // Write the PC to redzone[2].
1854   Value *BasePlus2 = IRB.CreateIntToPtr(
1855       IRB.CreateAdd(LocalStackBase,
1856                     ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1857       IntptrPtrTy);
1858   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1859
1860   // Poison the stack redzones at the entry.
1861   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
1862   poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
1863
1864   // (Un)poison the stack before all ret instructions.
1865   for (auto Ret : RetVec) {
1866     IRBuilder<> IRBRet(Ret);
1867     // Mark the current frame as retired.
1868     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1869                        BasePlus0);
1870     if (DoStackMalloc) {
1871       assert(StackMallocIdx >= 0);
1872       // if FakeStack != 0  // LocalStackBase == FakeStack
1873       //     // In use-after-return mode, poison the whole stack frame.
1874       //     if StackMallocIdx <= 4
1875       //         // For small sizes inline the whole thing:
1876       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1877       //         **SavedFlagPtr(FakeStack) = 0
1878       //     else
1879       //         __asan_stack_free_N(FakeStack, LocalStackSize)
1880       // else
1881       //     <This is not a fake stack; unpoison the redzones>
1882       Value *Cmp =
1883           IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
1884       TerminatorInst *ThenTerm, *ElseTerm;
1885       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1886
1887       IRBuilder<> IRBPoison(ThenTerm);
1888       if (StackMallocIdx <= 4) {
1889         int ClassSize = kMinStackMallocSize << StackMallocIdx;
1890         SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1891                                            ClassSize >> Mapping.Scale);
1892         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1893             FakeStack,
1894             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1895         Value *SavedFlagPtr = IRBPoison.CreateLoad(
1896             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1897         IRBPoison.CreateStore(
1898             Constant::getNullValue(IRBPoison.getInt8Ty()),
1899             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1900       } else {
1901         // For larger frames call __asan_stack_free_*.
1902         IRBPoison.CreateCall(
1903             AsanStackFreeFunc[StackMallocIdx],
1904             {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
1905       }
1906
1907       IRBuilder<> IRBElse(ElseTerm);
1908       poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
1909     } else if (HavePoisonedAllocas) {
1910       // If we poisoned some allocas in llvm.lifetime analysis,
1911       // unpoison whole stack frame now.
1912       poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1913     } else {
1914       poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
1915     }
1916   }
1917
1918   // We are done. Remove the old unused alloca instructions.
1919   for (auto AI : AllocaVec) AI->eraseFromParent();
1920 }
1921
1922 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
1923                                          IRBuilder<> &IRB, bool DoPoison) {
1924   // For now just insert the call to ASan runtime.
1925   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1926   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1927   IRB.CreateCall(
1928       DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
1929       {AddrArg, SizeArg});
1930 }
1931
1932 // Handling llvm.lifetime intrinsics for a given %alloca:
1933 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1934 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1935 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1936 //     could be poisoned by previous llvm.lifetime.end instruction, as the
1937 //     variable may go in and out of scope several times, e.g. in loops).
1938 // (3) if we poisoned at least one %alloca in a function,
1939 //     unpoison the whole stack frame at function exit.
1940
1941 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1942   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1943     // We're intested only in allocas we can handle.
1944     return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
1945   // See if we've already calculated (or started to calculate) alloca for a
1946   // given value.
1947   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1948   if (I != AllocaForValue.end()) return I->second;
1949   // Store 0 while we're calculating alloca for value V to avoid
1950   // infinite recursion if the value references itself.
1951   AllocaForValue[V] = nullptr;
1952   AllocaInst *Res = nullptr;
1953   if (CastInst *CI = dyn_cast<CastInst>(V))
1954     Res = findAllocaForValue(CI->getOperand(0));
1955   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1956     for (Value *IncValue : PN->incoming_values()) {
1957       // Allow self-referencing phi-nodes.
1958       if (IncValue == PN) continue;
1959       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1960       // AI for incoming values should exist and should all be equal.
1961       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1962         return nullptr;
1963       Res = IncValueAI;
1964     }
1965   }
1966   if (Res) AllocaForValue[V] = Res;
1967   return Res;
1968 }
1969
1970 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
1971   IRBuilder<> IRB(AI);
1972
1973   const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1974   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1975
1976   Value *Zero = Constant::getNullValue(IntptrTy);
1977   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1978   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1979
1980   // Since we need to extend alloca with additional memory to locate
1981   // redzones, and OldSize is number of allocated blocks with
1982   // ElementSize size, get allocated memory size in bytes by
1983   // OldSize * ElementSize.
1984   const unsigned ElementSize =
1985       F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
1986   Value *OldSize =
1987       IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
1988                     ConstantInt::get(IntptrTy, ElementSize));
1989
1990   // PartialSize = OldSize % 32
1991   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1992
1993   // Misalign = kAllocaRzSize - PartialSize;
1994   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1995
1996   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1997   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1998   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1999
2000   // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2001   // Align is added to locate left redzone, PartialPadding for possible
2002   // partial redzone and kAllocaRzSize for right redzone respectively.
2003   Value *AdditionalChunkSize = IRB.CreateAdd(
2004       ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2005
2006   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2007
2008   // Insert new alloca with new NewSize and Align params.
2009   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2010   NewAlloca->setAlignment(Align);
2011
2012   // NewAddress = Address + Align
2013   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2014                                     ConstantInt::get(IntptrTy, Align));
2015
2016   // Insert __asan_alloca_poison call for new created alloca.
2017   IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
2018
2019   // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2020   // for unpoisoning stuff.
2021   IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2022
2023   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2024
2025   // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
2026   AI->replaceAllUsesWith(NewAddressPtr);
2027
2028   // We are done. Erase old alloca from parent.
2029   AI->eraseFromParent();
2030 }
2031
2032 // isSafeAccess returns true if Addr is always inbounds with respect to its
2033 // base object. For example, it is a field access or an array access with
2034 // constant inbounds index.
2035 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2036                                     Value *Addr, uint64_t TypeSize) const {
2037   SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2038   if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
2039   uint64_t Size = SizeOffset.first.getZExtValue();
2040   int64_t Offset = SizeOffset.second.getSExtValue();
2041   // Three checks are required to ensure safety:
2042   // . Offset >= 0  (since the offset is given from the base ptr)
2043   // . Size >= Offset  (unsigned)
2044   // . Size - Offset >= NeededSize  (unsigned)
2045   return Offset >= 0 && Size >= uint64_t(Offset) &&
2046          Size - uint64_t(Offset) >= TypeSize / 8;
2047 }