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