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