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