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