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