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