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