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