1 //===- AddressSanitizer.cpp - memory error detector -----------------------===//
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 //  https://github.com/google/sanitizers/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/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/TargetLibraryInfo.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/BinaryFormat/MachO.h"
31 #include "llvm/IR/Argument.h"
32 #include "llvm/IR/Attributes.h"
33 #include "llvm/IR/BasicBlock.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/Comdat.h"
36 #include "llvm/IR/Constant.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DIBuilder.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DebugInfoMetadata.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalAlias.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/IRBuilder.h"
49 #include "llvm/IR/InlineAsm.h"
50 #include "llvm/IR/InstVisitor.h"
51 #include "llvm/IR/InstrTypes.h"
52 #include "llvm/IR/Instruction.h"
53 #include "llvm/IR/Instructions.h"
54 #include "llvm/IR/IntrinsicInst.h"
55 #include "llvm/IR/Intrinsics.h"
56 #include "llvm/IR/LLVMContext.h"
57 #include "llvm/IR/MDBuilder.h"
58 #include "llvm/IR/Metadata.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/Type.h"
61 #include "llvm/IR/Use.h"
62 #include "llvm/IR/Value.h"
63 #include "llvm/MC/MCSectionMachO.h"
64 #include "llvm/Pass.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/MathExtras.h"
70 #include "llvm/Support/ScopedPrinter.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Transforms/Instrumentation.h"
73 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
74 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
75 #include "llvm/Transforms/Utils/ModuleUtils.h"
76 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
77 #include <algorithm>
78 #include <cassert>
79 #include <cstddef>
80 #include <cstdint>
81 #include <iomanip>
82 #include <limits>
83 #include <memory>
84 #include <sstream>
85 #include <string>
86 #include <tuple>
87 
88 using namespace llvm;
89 
90 #define DEBUG_TYPE "asan"
91 
92 static const uint64_t kDefaultShadowScale = 3;
93 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
94 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
95 static const uint64_t kDynamicShadowSentinel =
96     std::numeric_limits<uint64_t>::max();
97 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
98 static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
99 static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
100 static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF;  // < 2G.
101 static const uint64_t kSmallX86_64ShadowOffsetAlignMask = ~0xFFFULL;
102 static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
103 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 44;
104 static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
105 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
106 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
107 static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
108 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
109 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
110 static const uint64_t kNetBSD_ShadowOffset32 = 1ULL << 30;
111 static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
112 static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
113 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
114 
115 static const uint64_t kMyriadShadowScale = 5;
116 static const uint64_t kMyriadMemoryOffset32 = 0x80000000ULL;
117 static const uint64_t kMyriadMemorySize32 = 0x20000000ULL;
118 static const uint64_t kMyriadTagShift = 29;
119 static const uint64_t kMyriadDDRTag = 4;
120 static const uint64_t kMyriadCacheBitMask32 = 0x40000000ULL;
121 
122 // The shadow memory space is dynamically allocated.
123 static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
124 
125 static const size_t kMinStackMallocSize = 1 << 6;   // 64B
126 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
127 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
128 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
129 
130 static const char *const kAsanModuleCtorName = "asan.module_ctor";
131 static const char *const kAsanModuleDtorName = "asan.module_dtor";
132 static const uint64_t kAsanCtorAndDtorPriority = 1;
133 static const char *const kAsanReportErrorTemplate = "__asan_report_";
134 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
135 static const char *const kAsanUnregisterGlobalsName =
136     "__asan_unregister_globals";
137 static const char *const kAsanRegisterImageGlobalsName =
138   "__asan_register_image_globals";
139 static const char *const kAsanUnregisterImageGlobalsName =
140   "__asan_unregister_image_globals";
141 static const char *const kAsanRegisterElfGlobalsName =
142   "__asan_register_elf_globals";
143 static const char *const kAsanUnregisterElfGlobalsName =
144   "__asan_unregister_elf_globals";
145 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
146 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
147 static const char *const kAsanInitName = "__asan_init";
148 static const char *const kAsanVersionCheckNamePrefix =
149     "__asan_version_mismatch_check_v";
150 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
151 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
152 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
153 static const int kMaxAsanStackMallocSizeClass = 10;
154 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
155 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
156 static const char *const kAsanGenPrefix = "___asan_gen_";
157 static const char *const kODRGenPrefix = "__odr_asan_gen_";
158 static const char *const kSanCovGenPrefix = "__sancov_gen_";
159 static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
160 static const char *const kAsanPoisonStackMemoryName =
161     "__asan_poison_stack_memory";
162 static const char *const kAsanUnpoisonStackMemoryName =
163     "__asan_unpoison_stack_memory";
164 
165 // ASan version script has __asan_* wildcard. Triple underscore prevents a
166 // linker (gold) warning about attempting to export a local symbol.
167 static const char *const kAsanGlobalsRegisteredFlagName =
168     "___asan_globals_registered";
169 
170 static const char *const kAsanOptionDetectUseAfterReturn =
171     "__asan_option_detect_stack_use_after_return";
172 
173 static const char *const kAsanShadowMemoryDynamicAddress =
174     "__asan_shadow_memory_dynamic_address";
175 
176 static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
177 static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
178 
179 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
180 static const size_t kNumberOfAccessSizes = 5;
181 
182 static const unsigned kAllocaRzSize = 32;
183 
184 // Command-line flags.
185 
186 static cl::opt<bool> ClEnableKasan(
187     "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
188     cl::Hidden, cl::init(false));
189 
190 static cl::opt<bool> ClRecover(
191     "asan-recover",
192     cl::desc("Enable recovery mode (continue-after-error)."),
193     cl::Hidden, cl::init(false));
194 
195 // This flag may need to be replaced with -f[no-]asan-reads.
196 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
197                                        cl::desc("instrument read instructions"),
198                                        cl::Hidden, cl::init(true));
199 
200 static cl::opt<bool> ClInstrumentWrites(
201     "asan-instrument-writes", cl::desc("instrument write instructions"),
202     cl::Hidden, cl::init(true));
203 
204 static cl::opt<bool> ClInstrumentAtomics(
205     "asan-instrument-atomics",
206     cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
207     cl::init(true));
208 
209 static cl::opt<bool> ClAlwaysSlowPath(
210     "asan-always-slow-path",
211     cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
212     cl::init(false));
213 
214 static cl::opt<bool> ClForceDynamicShadow(
215     "asan-force-dynamic-shadow",
216     cl::desc("Load shadow address into a local variable for each function"),
217     cl::Hidden, cl::init(false));
218 
219 static cl::opt<bool>
220     ClWithIfunc("asan-with-ifunc",
221                 cl::desc("Access dynamic shadow through an ifunc global on "
222                          "platforms that support this"),
223                 cl::Hidden, cl::init(true));
224 
225 static cl::opt<bool> ClWithIfuncSuppressRemat(
226     "asan-with-ifunc-suppress-remat",
227     cl::desc("Suppress rematerialization of dynamic shadow address by passing "
228              "it through inline asm in prologue."),
229     cl::Hidden, cl::init(true));
230 
231 // This flag limits the number of instructions to be instrumented
232 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
233 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
234 // set it to 10000.
235 static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
236     "asan-max-ins-per-bb", cl::init(10000),
237     cl::desc("maximal number of instructions to instrument in any given BB"),
238     cl::Hidden);
239 
240 // This flag may need to be replaced with -f[no]asan-stack.
241 static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
242                              cl::Hidden, cl::init(true));
243 static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
244     "asan-max-inline-poisoning-size",
245     cl::desc(
246         "Inline shadow poisoning for blocks up to the given size in bytes."),
247     cl::Hidden, cl::init(64));
248 
249 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
250                                       cl::desc("Check stack-use-after-return"),
251                                       cl::Hidden, cl::init(true));
252 
253 static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
254                                         cl::desc("Create redzones for byval "
255                                                  "arguments (extra copy "
256                                                  "required)"), cl::Hidden,
257                                         cl::init(true));
258 
259 static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
260                                      cl::desc("Check stack-use-after-scope"),
261                                      cl::Hidden, cl::init(false));
262 
263 // This flag may need to be replaced with -f[no]asan-globals.
264 static cl::opt<bool> ClGlobals("asan-globals",
265                                cl::desc("Handle global objects"), cl::Hidden,
266                                cl::init(true));
267 
268 static cl::opt<bool> ClInitializers("asan-initialization-order",
269                                     cl::desc("Handle C++ initializer order"),
270                                     cl::Hidden, cl::init(true));
271 
272 static cl::opt<bool> ClInvalidPointerPairs(
273     "asan-detect-invalid-pointer-pair",
274     cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
275     cl::init(false));
276 
277 static cl::opt<unsigned> ClRealignStack(
278     "asan-realign-stack",
279     cl::desc("Realign stack to the value of this flag (power of two)"),
280     cl::Hidden, cl::init(32));
281 
282 static cl::opt<int> ClInstrumentationWithCallsThreshold(
283     "asan-instrumentation-with-call-threshold",
284     cl::desc(
285         "If the function being instrumented contains more than "
286         "this number of memory accesses, use callbacks instead of "
287         "inline checks (-1 means never use callbacks)."),
288     cl::Hidden, cl::init(7000));
289 
290 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
291     "asan-memory-access-callback-prefix",
292     cl::desc("Prefix for memory access callbacks"), cl::Hidden,
293     cl::init("__asan_"));
294 
295 static cl::opt<bool>
296     ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
297                                cl::desc("instrument dynamic allocas"),
298                                cl::Hidden, cl::init(true));
299 
300 static cl::opt<bool> ClSkipPromotableAllocas(
301     "asan-skip-promotable-allocas",
302     cl::desc("Do not instrument promotable allocas"), cl::Hidden,
303     cl::init(true));
304 
305 // These flags allow to change the shadow mapping.
306 // The shadow mapping looks like
307 //    Shadow = (Mem >> scale) + offset
308 
309 static cl::opt<int> ClMappingScale("asan-mapping-scale",
310                                    cl::desc("scale of asan shadow mapping"),
311                                    cl::Hidden, cl::init(0));
312 
313 static cl::opt<unsigned long long> ClMappingOffset(
314     "asan-mapping-offset",
315     cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
316     cl::init(0));
317 
318 // Optimization flags. Not user visible, used mostly for testing
319 // and benchmarking the tool.
320 
321 static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
322                            cl::Hidden, cl::init(true));
323 
324 static cl::opt<bool> ClOptSameTemp(
325     "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
326     cl::Hidden, cl::init(true));
327 
328 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
329                                   cl::desc("Don't instrument scalar globals"),
330                                   cl::Hidden, cl::init(true));
331 
332 static cl::opt<bool> ClOptStack(
333     "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
334     cl::Hidden, cl::init(false));
335 
336 static cl::opt<bool> ClDynamicAllocaStack(
337     "asan-stack-dynamic-alloca",
338     cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
339     cl::init(true));
340 
341 static cl::opt<uint32_t> ClForceExperiment(
342     "asan-force-experiment",
343     cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
344     cl::init(0));
345 
346 static cl::opt<bool>
347     ClUsePrivateAliasForGlobals("asan-use-private-alias",
348                                 cl::desc("Use private aliases for global"
349                                          " variables"),
350                                 cl::Hidden, cl::init(false));
351 
352 static cl::opt<bool>
353     ClUseGlobalsGC("asan-globals-live-support",
354                    cl::desc("Use linker features to support dead "
355                             "code stripping of globals"),
356                    cl::Hidden, cl::init(true));
357 
358 // This is on by default even though there is a bug in gold:
359 // https://sourceware.org/bugzilla/show_bug.cgi?id=19002
360 static cl::opt<bool>
361     ClWithComdat("asan-with-comdat",
362                  cl::desc("Place ASan constructors in comdat sections"),
363                  cl::Hidden, cl::init(true));
364 
365 // Debug flags.
366 
367 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
368                             cl::init(0));
369 
370 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
371                                  cl::Hidden, cl::init(0));
372 
373 static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
374                                         cl::desc("Debug func"));
375 
376 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
377                                cl::Hidden, cl::init(-1));
378 
379 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
380                                cl::Hidden, cl::init(-1));
381 
382 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
383 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
384 STATISTIC(NumOptimizedAccessesToGlobalVar,
385           "Number of optimized accesses to global vars");
386 STATISTIC(NumOptimizedAccessesToStackVar,
387           "Number of optimized accesses to stack vars");
388 
389 namespace {
390 
391 /// Frontend-provided metadata for source location.
392 struct LocationMetadata {
393   StringRef Filename;
394   int LineNo = 0;
395   int ColumnNo = 0;
396 
397   LocationMetadata() = default;
398 
399   bool empty() const { return Filename.empty(); }
400 
401   void parse(MDNode *MDN) {
402     assert(MDN->getNumOperands() == 3);
403     MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
404     Filename = DIFilename->getString();
405     LineNo =
406         mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
407     ColumnNo =
408         mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
409   }
410 };
411 
412 /// Frontend-provided metadata for global variables.
413 class GlobalsMetadata {
414 public:
415   struct Entry {
416     LocationMetadata SourceLoc;
417     StringRef Name;
418     bool IsDynInit = false;
419     bool IsBlacklisted = false;
420 
421     Entry() = default;
422   };
423 
424   GlobalsMetadata() = default;
425 
426   void reset() {
427     inited_ = false;
428     Entries.clear();
429   }
430 
431   void init(Module &M) {
432     assert(!inited_);
433     inited_ = true;
434     NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
435     if (!Globals) return;
436     for (auto MDN : Globals->operands()) {
437       // Metadata node contains the global and the fields of "Entry".
438       assert(MDN->getNumOperands() == 5);
439       auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
440       // The optimizer may optimize away a global entirely.
441       if (!GV) continue;
442       // We can already have an entry for GV if it was merged with another
443       // global.
444       Entry &E = Entries[GV];
445       if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
446         E.SourceLoc.parse(Loc);
447       if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
448         E.Name = Name->getString();
449       ConstantInt *IsDynInit =
450           mdconst::extract<ConstantInt>(MDN->getOperand(3));
451       E.IsDynInit |= IsDynInit->isOne();
452       ConstantInt *IsBlacklisted =
453           mdconst::extract<ConstantInt>(MDN->getOperand(4));
454       E.IsBlacklisted |= IsBlacklisted->isOne();
455     }
456   }
457 
458   /// Returns metadata entry for a given global.
459   Entry get(GlobalVariable *G) const {
460     auto Pos = Entries.find(G);
461     return (Pos != Entries.end()) ? Pos->second : Entry();
462   }
463 
464 private:
465   bool inited_ = false;
466   DenseMap<GlobalVariable *, Entry> Entries;
467 };
468 
469 /// This struct defines the shadow mapping using the rule:
470 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
471 /// If InGlobal is true, then
472 ///   extern char __asan_shadow[];
473 ///   shadow = (mem >> Scale) + &__asan_shadow
474 struct ShadowMapping {
475   int Scale;
476   uint64_t Offset;
477   bool OrShadowOffset;
478   bool InGlobal;
479 };
480 
481 } // end anonymous namespace
482 
483 static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
484                                       bool IsKasan) {
485   bool IsAndroid = TargetTriple.isAndroid();
486   bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
487   bool IsFreeBSD = TargetTriple.isOSFreeBSD();
488   bool IsNetBSD = TargetTriple.isOSNetBSD();
489   bool IsPS4CPU = TargetTriple.isPS4CPU();
490   bool IsLinux = TargetTriple.isOSLinux();
491   bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
492                  TargetTriple.getArch() == Triple::ppc64le;
493   bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
494   bool IsX86 = TargetTriple.getArch() == Triple::x86;
495   bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
496   bool IsMIPS32 = TargetTriple.isMIPS32();
497   bool IsMIPS64 = TargetTriple.isMIPS64();
498   bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();
499   bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64;
500   bool IsWindows = TargetTriple.isOSWindows();
501   bool IsFuchsia = TargetTriple.isOSFuchsia();
502   bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
503 
504   ShadowMapping Mapping;
505 
506   Mapping.Scale = IsMyriad ? kMyriadShadowScale : kDefaultShadowScale;
507   if (ClMappingScale.getNumOccurrences() > 0) {
508     Mapping.Scale = ClMappingScale;
509   }
510 
511   if (LongSize == 32) {
512     if (IsAndroid)
513       Mapping.Offset = kDynamicShadowSentinel;
514     else if (IsMIPS32)
515       Mapping.Offset = kMIPS32_ShadowOffset32;
516     else if (IsFreeBSD)
517       Mapping.Offset = kFreeBSD_ShadowOffset32;
518     else if (IsNetBSD)
519       Mapping.Offset = kNetBSD_ShadowOffset32;
520     else if (IsIOS)
521       // If we're targeting iOS and x86, the binary is built for iOS simulator.
522       Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
523     else if (IsWindows)
524       Mapping.Offset = kWindowsShadowOffset32;
525     else if (IsMyriad) {
526       uint64_t ShadowOffset = (kMyriadMemoryOffset32 + kMyriadMemorySize32 -
527                                (kMyriadMemorySize32 >> Mapping.Scale));
528       Mapping.Offset = ShadowOffset - (kMyriadMemoryOffset32 >> Mapping.Scale);
529     }
530     else
531       Mapping.Offset = kDefaultShadowOffset32;
532   } else {  // LongSize == 64
533     // Fuchsia is always PIE, which means that the beginning of the address
534     // space is always available.
535     if (IsFuchsia)
536       Mapping.Offset = 0;
537     else if (IsPPC64)
538       Mapping.Offset = kPPC64_ShadowOffset64;
539     else if (IsSystemZ)
540       Mapping.Offset = kSystemZ_ShadowOffset64;
541     else if (IsFreeBSD && !IsMIPS64)
542       Mapping.Offset = kFreeBSD_ShadowOffset64;
543     else if (IsNetBSD)
544       Mapping.Offset = kNetBSD_ShadowOffset64;
545     else if (IsPS4CPU)
546       Mapping.Offset = kPS4CPU_ShadowOffset64;
547     else if (IsLinux && IsX86_64) {
548       if (IsKasan)
549         Mapping.Offset = kLinuxKasan_ShadowOffset64;
550       else
551         Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
552                           (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
553     } else if (IsWindows && IsX86_64) {
554       Mapping.Offset = kWindowsShadowOffset64;
555     } else if (IsMIPS64)
556       Mapping.Offset = kMIPS64_ShadowOffset64;
557     else if (IsIOS)
558       // If we're targeting iOS and x86, the binary is built for iOS simulator.
559       // We are using dynamic shadow offset on the 64-bit devices.
560       Mapping.Offset =
561         IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
562     else if (IsAArch64)
563       Mapping.Offset = kAArch64_ShadowOffset64;
564     else
565       Mapping.Offset = kDefaultShadowOffset64;
566   }
567 
568   if (ClForceDynamicShadow) {
569     Mapping.Offset = kDynamicShadowSentinel;
570   }
571 
572   if (ClMappingOffset.getNumOccurrences() > 0) {
573     Mapping.Offset = ClMappingOffset;
574   }
575 
576   // OR-ing shadow offset if more efficient (at least on x86) if the offset
577   // is a power of two, but on ppc64 we have to use add since the shadow
578   // offset is not necessary 1/8-th of the address space.  On SystemZ,
579   // we could OR the constant in a single instruction, but it's more
580   // efficient to load it once and use indexed addressing.
581   Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
582                            !(Mapping.Offset & (Mapping.Offset - 1)) &&
583                            Mapping.Offset != kDynamicShadowSentinel;
584   bool IsAndroidWithIfuncSupport =
585       IsAndroid && !TargetTriple.isAndroidVersionLT(21);
586   Mapping.InGlobal = ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
587 
588   return Mapping;
589 }
590 
591 static size_t RedzoneSizeForScale(int MappingScale) {
592   // Redzone used for stack and globals is at least 32 bytes.
593   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
594   return std::max(32U, 1U << MappingScale);
595 }
596 
597 namespace {
598 
599 /// AddressSanitizer: instrument the code in module to find memory bugs.
600 struct AddressSanitizer : public FunctionPass {
601   // Pass identification, replacement for typeid
602   static char ID;
603 
604   explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
605                             bool UseAfterScope = false)
606       : FunctionPass(ID), UseAfterScope(UseAfterScope || ClUseAfterScope) {
607     this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
608     this->CompileKernel = ClEnableKasan.getNumOccurrences() > 0 ?
609         ClEnableKasan : CompileKernel;
610     initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
611   }
612 
613   StringRef getPassName() const override {
614     return "AddressSanitizerFunctionPass";
615   }
616 
617   void getAnalysisUsage(AnalysisUsage &AU) const override {
618     AU.addRequired<DominatorTreeWrapperPass>();
619     AU.addRequired<TargetLibraryInfoWrapperPass>();
620   }
621 
622   uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
623     uint64_t ArraySize = 1;
624     if (AI.isArrayAllocation()) {
625       const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
626       assert(CI && "non-constant array size");
627       ArraySize = CI->getZExtValue();
628     }
629     Type *Ty = AI.getAllocatedType();
630     uint64_t SizeInBytes =
631         AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
632     return SizeInBytes * ArraySize;
633   }
634 
635   /// Check if we want (and can) handle this alloca.
636   bool isInterestingAlloca(const AllocaInst &AI);
637 
638   /// If it is an interesting memory access, return the PointerOperand
639   /// and set IsWrite/Alignment. Otherwise return nullptr.
640   /// MaybeMask is an output parameter for the mask Value, if we're looking at a
641   /// masked load/store.
642   Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
643                                    uint64_t *TypeSize, unsigned *Alignment,
644                                    Value **MaybeMask = nullptr);
645 
646   void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
647                      bool UseCalls, const DataLayout &DL);
648   void instrumentPointerComparisonOrSubtraction(Instruction *I);
649   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
650                          Value *Addr, uint32_t TypeSize, bool IsWrite,
651                          Value *SizeArgument, bool UseCalls, uint32_t Exp);
652   void instrumentUnusualSizeOrAlignment(Instruction *I,
653                                         Instruction *InsertBefore, Value *Addr,
654                                         uint32_t TypeSize, bool IsWrite,
655                                         Value *SizeArgument, bool UseCalls,
656                                         uint32_t Exp);
657   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
658                            Value *ShadowValue, uint32_t TypeSize);
659   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
660                                  bool IsWrite, size_t AccessSizeIndex,
661                                  Value *SizeArgument, uint32_t Exp);
662   void instrumentMemIntrinsic(MemIntrinsic *MI);
663   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
664   bool runOnFunction(Function &F) override;
665   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
666   void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
667   void markEscapedLocalAllocas(Function &F);
668   bool doInitialization(Module &M) override;
669   bool doFinalization(Module &M) override;
670 
671   DominatorTree &getDominatorTree() const { return *DT; }
672 
673 private:
674   friend struct FunctionStackPoisoner;
675 
676   void initializeCallbacks(Module &M);
677 
678   bool LooksLikeCodeInBug11395(Instruction *I);
679   bool GlobalIsLinkerInitialized(GlobalVariable *G);
680   bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
681                     uint64_t TypeSize) const;
682 
683   /// Helper to cleanup per-function state.
684   struct FunctionStateRAII {
685     AddressSanitizer *Pass;
686 
687     FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
688       assert(Pass->ProcessedAllocas.empty() &&
689              "last pass forgot to clear cache");
690       assert(!Pass->LocalDynamicShadow);
691     }
692 
693     ~FunctionStateRAII() {
694       Pass->LocalDynamicShadow = nullptr;
695       Pass->ProcessedAllocas.clear();
696     }
697   };
698 
699   LLVMContext *C;
700   Triple TargetTriple;
701   int LongSize;
702   bool CompileKernel;
703   bool Recover;
704   bool UseAfterScope;
705   Type *IntptrTy;
706   ShadowMapping Mapping;
707   DominatorTree *DT;
708   Function *AsanHandleNoReturnFunc;
709   Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
710   Constant *AsanShadowGlobal;
711 
712   // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
713   Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
714   Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
715 
716   // These arrays is indexed by AccessIsWrite and Experiment.
717   Function *AsanErrorCallbackSized[2][2];
718   Function *AsanMemoryAccessCallbackSized[2][2];
719 
720   Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
721   InlineAsm *EmptyAsm;
722   Value *LocalDynamicShadow = nullptr;
723   GlobalsMetadata GlobalsMD;
724   DenseMap<const AllocaInst *, bool> ProcessedAllocas;
725 };
726 
727 class AddressSanitizerModule : public ModulePass {
728 public:
729   // Pass identification, replacement for typeid
730   static char ID;
731 
732   explicit AddressSanitizerModule(bool CompileKernel = false,
733                                   bool Recover = false,
734                                   bool UseGlobalsGC = true)
735       : ModulePass(ID),
736         UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
737         // Not a typo: ClWithComdat is almost completely pointless without
738         // ClUseGlobalsGC (because then it only works on modules without
739         // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
740         // and both suffer from gold PR19002 for which UseGlobalsGC constructor
741         // argument is designed as workaround. Therefore, disable both
742         // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
743         // do globals-gc.
744         UseCtorComdat(UseGlobalsGC && ClWithComdat) {
745           this->Recover = ClRecover.getNumOccurrences() > 0 ?
746               ClRecover : Recover;
747           this->CompileKernel = ClEnableKasan.getNumOccurrences() > 0 ?
748               ClEnableKasan : CompileKernel;
749 	}
750 
751   bool runOnModule(Module &M) override;
752   StringRef getPassName() const override { return "AddressSanitizerModule"; }
753 
754 private:
755   void initializeCallbacks(Module &M);
756 
757   bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
758   void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
759                              ArrayRef<GlobalVariable *> ExtendedGlobals,
760                              ArrayRef<Constant *> MetadataInitializers);
761   void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
762                             ArrayRef<GlobalVariable *> ExtendedGlobals,
763                             ArrayRef<Constant *> MetadataInitializers,
764                             const std::string &UniqueModuleId);
765   void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
766                               ArrayRef<GlobalVariable *> ExtendedGlobals,
767                               ArrayRef<Constant *> MetadataInitializers);
768   void
769   InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
770                                      ArrayRef<GlobalVariable *> ExtendedGlobals,
771                                      ArrayRef<Constant *> MetadataInitializers);
772 
773   GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
774                                        StringRef OriginalName);
775   void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
776                                   StringRef InternalSuffix);
777   IRBuilder<> CreateAsanModuleDtor(Module &M);
778 
779   bool ShouldInstrumentGlobal(GlobalVariable *G);
780   bool ShouldUseMachOGlobalsSection() const;
781   StringRef getGlobalMetadataSection() const;
782   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
783   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
784   size_t MinRedzoneSizeForGlobal() const {
785     return RedzoneSizeForScale(Mapping.Scale);
786   }
787   int GetAsanVersion(const Module &M) const;
788 
789   GlobalsMetadata GlobalsMD;
790   bool CompileKernel;
791   bool Recover;
792   bool UseGlobalsGC;
793   bool UseCtorComdat;
794   Type *IntptrTy;
795   LLVMContext *C;
796   Triple TargetTriple;
797   ShadowMapping Mapping;
798   Function *AsanPoisonGlobals;
799   Function *AsanUnpoisonGlobals;
800   Function *AsanRegisterGlobals;
801   Function *AsanUnregisterGlobals;
802   Function *AsanRegisterImageGlobals;
803   Function *AsanUnregisterImageGlobals;
804   Function *AsanRegisterElfGlobals;
805   Function *AsanUnregisterElfGlobals;
806 
807   Function *AsanCtorFunction = nullptr;
808   Function *AsanDtorFunction = nullptr;
809 };
810 
811 // Stack poisoning does not play well with exception handling.
812 // When an exception is thrown, we essentially bypass the code
813 // that unpoisones the stack. This is why the run-time library has
814 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
815 // stack in the interceptor. This however does not work inside the
816 // actual function which catches the exception. Most likely because the
817 // compiler hoists the load of the shadow value somewhere too high.
818 // This causes asan to report a non-existing bug on 453.povray.
819 // It sounds like an LLVM bug.
820 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
821   Function &F;
822   AddressSanitizer &ASan;
823   DIBuilder DIB;
824   LLVMContext *C;
825   Type *IntptrTy;
826   Type *IntptrPtrTy;
827   ShadowMapping Mapping;
828 
829   SmallVector<AllocaInst *, 16> AllocaVec;
830   SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
831   SmallVector<Instruction *, 8> RetVec;
832   unsigned StackAlignment;
833 
834   Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
835       *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
836   Function *AsanSetShadowFunc[0x100] = {};
837   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
838   Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
839 
840   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
841   struct AllocaPoisonCall {
842     IntrinsicInst *InsBefore;
843     AllocaInst *AI;
844     uint64_t Size;
845     bool DoPoison;
846   };
847   SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
848   SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
849 
850   SmallVector<AllocaInst *, 1> DynamicAllocaVec;
851   SmallVector<IntrinsicInst *, 1> StackRestoreVec;
852   AllocaInst *DynamicAllocaLayout = nullptr;
853   IntrinsicInst *LocalEscapeCall = nullptr;
854 
855   // Maps Value to an AllocaInst from which the Value is originated.
856   using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
857   AllocaForValueMapTy AllocaForValue;
858 
859   bool HasNonEmptyInlineAsm = false;
860   bool HasReturnsTwiceCall = false;
861   std::unique_ptr<CallInst> EmptyInlineAsm;
862 
863   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
864       : F(F),
865         ASan(ASan),
866         DIB(*F.getParent(), /*AllowUnresolved*/ false),
867         C(ASan.C),
868         IntptrTy(ASan.IntptrTy),
869         IntptrPtrTy(PointerType::get(IntptrTy, 0)),
870         Mapping(ASan.Mapping),
871         StackAlignment(1 << Mapping.Scale),
872         EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
873 
874   bool runOnFunction() {
875     if (!ClStack) return false;
876 
877     if (ClRedzoneByvalArgs)
878       copyArgsPassedByValToAllocas();
879 
880     // Collect alloca, ret, lifetime instructions etc.
881     for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
882 
883     if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
884 
885     initializeCallbacks(*F.getParent());
886 
887     processDynamicAllocas();
888     processStaticAllocas();
889 
890     if (ClDebugStack) {
891       LLVM_DEBUG(dbgs() << F);
892     }
893     return true;
894   }
895 
896   // Arguments marked with the "byval" attribute are implicitly copied without
897   // using an alloca instruction.  To produce redzones for those arguments, we
898   // copy them a second time into memory allocated with an alloca instruction.
899   void copyArgsPassedByValToAllocas();
900 
901   // Finds all Alloca instructions and puts
902   // poisoned red zones around all of them.
903   // Then unpoison everything back before the function returns.
904   void processStaticAllocas();
905   void processDynamicAllocas();
906 
907   void createDynamicAllocasInitStorage();
908 
909   // ----------------------- Visitors.
910   /// Collect all Ret instructions.
911   void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
912 
913   /// Collect all Resume instructions.
914   void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
915 
916   /// Collect all CatchReturnInst instructions.
917   void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
918 
919   void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
920                                         Value *SavedStack) {
921     IRBuilder<> IRB(InstBefore);
922     Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
923     // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
924     // need to adjust extracted SP to compute the address of the most recent
925     // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
926     // this purpose.
927     if (!isa<ReturnInst>(InstBefore)) {
928       Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
929           InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
930           {IntptrTy});
931 
932       Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
933 
934       DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
935                                      DynamicAreaOffset);
936     }
937 
938     IRB.CreateCall(AsanAllocasUnpoisonFunc,
939                    {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
940   }
941 
942   // Unpoison dynamic allocas redzones.
943   void unpoisonDynamicAllocas() {
944     for (auto &Ret : RetVec)
945       unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
946 
947     for (auto &StackRestoreInst : StackRestoreVec)
948       unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
949                                        StackRestoreInst->getOperand(0));
950   }
951 
952   // Deploy and poison redzones around dynamic alloca call. To do this, we
953   // should replace this call with another one with changed parameters and
954   // replace all its uses with new address, so
955   //   addr = alloca type, old_size, align
956   // is replaced by
957   //   new_size = (old_size + additional_size) * sizeof(type)
958   //   tmp = alloca i8, new_size, max(align, 32)
959   //   addr = tmp + 32 (first 32 bytes are for the left redzone).
960   // Additional_size is added to make new memory allocation contain not only
961   // requested memory, but also left, partial and right redzones.
962   void handleDynamicAllocaCall(AllocaInst *AI);
963 
964   /// Collect Alloca instructions we want (and can) handle.
965   void visitAllocaInst(AllocaInst &AI) {
966     if (!ASan.isInterestingAlloca(AI)) {
967       if (AI.isStaticAlloca()) {
968         // Skip over allocas that are present *before* the first instrumented
969         // alloca, we don't want to move those around.
970         if (AllocaVec.empty())
971           return;
972 
973         StaticAllocasToMoveUp.push_back(&AI);
974       }
975       return;
976     }
977 
978     StackAlignment = std::max(StackAlignment, AI.getAlignment());
979     if (!AI.isStaticAlloca())
980       DynamicAllocaVec.push_back(&AI);
981     else
982       AllocaVec.push_back(&AI);
983   }
984 
985   /// Collect lifetime intrinsic calls to check for use-after-scope
986   /// errors.
987   void visitIntrinsicInst(IntrinsicInst &II) {
988     Intrinsic::ID ID = II.getIntrinsicID();
989     if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
990     if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
991     if (!ASan.UseAfterScope)
992       return;
993     if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
994       return;
995     // Found lifetime intrinsic, add ASan instrumentation if necessary.
996     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
997     // If size argument is undefined, don't do anything.
998     if (Size->isMinusOne()) return;
999     // Check that size doesn't saturate uint64_t and can
1000     // be stored in IntptrTy.
1001     const uint64_t SizeValue = Size->getValue().getLimitedValue();
1002     if (SizeValue == ~0ULL ||
1003         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
1004       return;
1005     // Find alloca instruction that corresponds to llvm.lifetime argument.
1006     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
1007     if (!AI || !ASan.isInterestingAlloca(*AI))
1008       return;
1009     bool DoPoison = (ID == Intrinsic::lifetime_end);
1010     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
1011     if (AI->isStaticAlloca())
1012       StaticAllocaPoisonCallVec.push_back(APC);
1013     else if (ClInstrumentDynamicAllocas)
1014       DynamicAllocaPoisonCallVec.push_back(APC);
1015   }
1016 
1017   void visitCallSite(CallSite CS) {
1018     Instruction *I = CS.getInstruction();
1019     if (CallInst *CI = dyn_cast<CallInst>(I)) {
1020       HasNonEmptyInlineAsm |= CI->isInlineAsm() &&
1021                               !CI->isIdenticalTo(EmptyInlineAsm.get()) &&
1022                               I != ASan.LocalDynamicShadow;
1023       HasReturnsTwiceCall |= CI->canReturnTwice();
1024     }
1025   }
1026 
1027   // ---------------------- Helpers.
1028   void initializeCallbacks(Module &M);
1029 
1030   bool doesDominateAllExits(const Instruction *I) const {
1031     for (auto Ret : RetVec) {
1032       if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
1033     }
1034     return true;
1035   }
1036 
1037   /// Finds alloca where the value comes from.
1038   AllocaInst *findAllocaForValue(Value *V);
1039 
1040   // Copies bytes from ShadowBytes into shadow memory for indexes where
1041   // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1042   // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1043   void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1044                     IRBuilder<> &IRB, Value *ShadowBase);
1045   void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1046                     size_t Begin, size_t End, IRBuilder<> &IRB,
1047                     Value *ShadowBase);
1048   void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1049                           ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1050                           size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1051 
1052   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
1053 
1054   Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1055                                bool Dynamic);
1056   PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1057                      Instruction *ThenTerm, Value *ValueIfFalse);
1058 };
1059 
1060 } // end anonymous namespace
1061 
1062 char AddressSanitizer::ID = 0;
1063 
1064 INITIALIZE_PASS_BEGIN(
1065     AddressSanitizer, "asan",
1066     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1067     false)
1068 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1069 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1070 INITIALIZE_PASS_END(
1071     AddressSanitizer, "asan",
1072     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1073     false)
1074 
1075 FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
1076                                                        bool Recover,
1077                                                        bool UseAfterScope) {
1078   assert(!CompileKernel || Recover);
1079   return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
1080 }
1081 
1082 char AddressSanitizerModule::ID = 0;
1083 
1084 INITIALIZE_PASS(
1085     AddressSanitizerModule, "asan-module",
1086     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
1087     "ModulePass",
1088     false, false)
1089 
1090 ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
1091                                                    bool Recover,
1092                                                    bool UseGlobalsGC) {
1093   assert(!CompileKernel || Recover);
1094   return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
1095 }
1096 
1097 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
1098   size_t Res = countTrailingZeros(TypeSize / 8);
1099   assert(Res < kNumberOfAccessSizes);
1100   return Res;
1101 }
1102 
1103 // Create a constant for Str so that we can pass it to the run-time lib.
1104 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
1105                                                     bool AllowMerging) {
1106   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
1107   // We use private linkage for module-local strings. If they can be merged
1108   // with another one, we set the unnamed_addr attribute.
1109   GlobalVariable *GV =
1110       new GlobalVariable(M, StrConst->getType(), true,
1111                          GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
1112   if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1113   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
1114   return GV;
1115 }
1116 
1117 /// Create a global describing a source location.
1118 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
1119                                                        LocationMetadata MD) {
1120   Constant *LocData[] = {
1121       createPrivateGlobalForString(M, MD.Filename, true),
1122       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1123       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1124   };
1125   auto LocStruct = ConstantStruct::getAnon(LocData);
1126   auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1127                                GlobalValue::PrivateLinkage, LocStruct,
1128                                kAsanGenPrefix);
1129   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1130   return GV;
1131 }
1132 
1133 /// Check if \p G has been created by a trusted compiler pass.
1134 static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
1135   // Do not instrument @llvm.global_ctors, @llvm.used, etc.
1136   if (G->getName().startswith("llvm."))
1137     return true;
1138 
1139   // Do not instrument asan globals.
1140   if (G->getName().startswith(kAsanGenPrefix) ||
1141       G->getName().startswith(kSanCovGenPrefix) ||
1142       G->getName().startswith(kODRGenPrefix))
1143     return true;
1144 
1145   // Do not instrument gcov counter arrays.
1146   if (G->getName() == "__llvm_gcov_ctr")
1147     return true;
1148 
1149   return false;
1150 }
1151 
1152 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1153   // Shadow >> scale
1154   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
1155   if (Mapping.Offset == 0) return Shadow;
1156   // (Shadow >> scale) | offset
1157   Value *ShadowBase;
1158   if (LocalDynamicShadow)
1159     ShadowBase = LocalDynamicShadow;
1160   else
1161     ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1162   if (Mapping.OrShadowOffset)
1163     return IRB.CreateOr(Shadow, ShadowBase);
1164   else
1165     return IRB.CreateAdd(Shadow, ShadowBase);
1166 }
1167 
1168 // Instrument memset/memmove/memcpy
1169 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1170   IRBuilder<> IRB(MI);
1171   if (isa<MemTransferInst>(MI)) {
1172     IRB.CreateCall(
1173         isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
1174         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1175          IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1176          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1177   } else if (isa<MemSetInst>(MI)) {
1178     IRB.CreateCall(
1179         AsanMemset,
1180         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1181          IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1182          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1183   }
1184   MI->eraseFromParent();
1185 }
1186 
1187 /// Check if we want (and can) handle this alloca.
1188 bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
1189   auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1190 
1191   if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1192     return PreviouslySeenAllocaInfo->getSecond();
1193 
1194   bool IsInteresting =
1195       (AI.getAllocatedType()->isSized() &&
1196        // alloca() may be called with 0 size, ignore it.
1197        ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
1198        // We are only interested in allocas not promotable to registers.
1199        // Promotable allocas are common under -O0.
1200        (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1201        // inalloca allocas are not treated as static, and we don't want
1202        // dynamic alloca instrumentation for them as well.
1203        !AI.isUsedWithInAlloca() &&
1204        // swifterror allocas are register promoted by ISel
1205        !AI.isSwiftError());
1206 
1207   ProcessedAllocas[&AI] = IsInteresting;
1208   return IsInteresting;
1209 }
1210 
1211 Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1212                                                    bool *IsWrite,
1213                                                    uint64_t *TypeSize,
1214                                                    unsigned *Alignment,
1215                                                    Value **MaybeMask) {
1216   // Skip memory accesses inserted by another instrumentation.
1217   if (I->getMetadata("nosanitize")) return nullptr;
1218 
1219   // Do not instrument the load fetching the dynamic shadow address.
1220   if (LocalDynamicShadow == I)
1221     return nullptr;
1222 
1223   Value *PtrOperand = nullptr;
1224   const DataLayout &DL = I->getModule()->getDataLayout();
1225   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1226     if (!ClInstrumentReads) return nullptr;
1227     *IsWrite = false;
1228     *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
1229     *Alignment = LI->getAlignment();
1230     PtrOperand = LI->getPointerOperand();
1231   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1232     if (!ClInstrumentWrites) return nullptr;
1233     *IsWrite = true;
1234     *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
1235     *Alignment = SI->getAlignment();
1236     PtrOperand = SI->getPointerOperand();
1237   } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1238     if (!ClInstrumentAtomics) return nullptr;
1239     *IsWrite = true;
1240     *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
1241     *Alignment = 0;
1242     PtrOperand = RMW->getPointerOperand();
1243   } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
1244     if (!ClInstrumentAtomics) return nullptr;
1245     *IsWrite = true;
1246     *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
1247     *Alignment = 0;
1248     PtrOperand = XCHG->getPointerOperand();
1249   } else if (auto CI = dyn_cast<CallInst>(I)) {
1250     auto *F = dyn_cast<Function>(CI->getCalledValue());
1251     if (F && (F->getName().startswith("llvm.masked.load.") ||
1252               F->getName().startswith("llvm.masked.store."))) {
1253       unsigned OpOffset = 0;
1254       if (F->getName().startswith("llvm.masked.store.")) {
1255         if (!ClInstrumentWrites)
1256           return nullptr;
1257         // Masked store has an initial operand for the value.
1258         OpOffset = 1;
1259         *IsWrite = true;
1260       } else {
1261         if (!ClInstrumentReads)
1262           return nullptr;
1263         *IsWrite = false;
1264       }
1265 
1266       auto BasePtr = CI->getOperand(0 + OpOffset);
1267       auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1268       *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1269       if (auto AlignmentConstant =
1270               dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1271         *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1272       else
1273         *Alignment = 1; // No alignment guarantees. We probably got Undef
1274       if (MaybeMask)
1275         *MaybeMask = CI->getOperand(2 + OpOffset);
1276       PtrOperand = BasePtr;
1277     }
1278   }
1279 
1280   if (PtrOperand) {
1281     // Do not instrument acesses from different address spaces; we cannot deal
1282     // with them.
1283     Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1284     if (PtrTy->getPointerAddressSpace() != 0)
1285       return nullptr;
1286 
1287     // Ignore swifterror addresses.
1288     // swifterror memory addresses are mem2reg promoted by instruction
1289     // selection. As such they cannot have regular uses like an instrumentation
1290     // function and it makes no sense to track them as memory.
1291     if (PtrOperand->isSwiftError())
1292       return nullptr;
1293   }
1294 
1295   // Treat memory accesses to promotable allocas as non-interesting since they
1296   // will not cause memory violations. This greatly speeds up the instrumented
1297   // executable at -O0.
1298   if (ClSkipPromotableAllocas)
1299     if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1300       return isInterestingAlloca(*AI) ? AI : nullptr;
1301 
1302   return PtrOperand;
1303 }
1304 
1305 static bool isPointerOperand(Value *V) {
1306   return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1307 }
1308 
1309 // This is a rough heuristic; it may cause both false positives and
1310 // false negatives. The proper implementation requires cooperation with
1311 // the frontend.
1312 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1313   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
1314     if (!Cmp->isRelational()) return false;
1315   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1316     if (BO->getOpcode() != Instruction::Sub) return false;
1317   } else {
1318     return false;
1319   }
1320   return isPointerOperand(I->getOperand(0)) &&
1321          isPointerOperand(I->getOperand(1));
1322 }
1323 
1324 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1325   // If a global variable does not have dynamic initialization we don't
1326   // have to instrument it.  However, if a global does not have initializer
1327   // at all, we assume it has dynamic initializer (in other TU).
1328   return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
1329 }
1330 
1331 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1332     Instruction *I) {
1333   IRBuilder<> IRB(I);
1334   Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1335   Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
1336   for (Value *&i : Param) {
1337     if (i->getType()->isPointerTy())
1338       i = IRB.CreatePointerCast(i, IntptrTy);
1339   }
1340   IRB.CreateCall(F, Param);
1341 }
1342 
1343 static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
1344                                 Instruction *InsertBefore, Value *Addr,
1345                                 unsigned Alignment, unsigned Granularity,
1346                                 uint32_t TypeSize, bool IsWrite,
1347                                 Value *SizeArgument, bool UseCalls,
1348                                 uint32_t Exp) {
1349   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1350   // if the data is properly aligned.
1351   if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1352        TypeSize == 128) &&
1353       (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
1354     return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1355                                    nullptr, UseCalls, Exp);
1356   Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1357                                          IsWrite, nullptr, UseCalls, Exp);
1358 }
1359 
1360 static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1361                                         const DataLayout &DL, Type *IntptrTy,
1362                                         Value *Mask, Instruction *I,
1363                                         Value *Addr, unsigned Alignment,
1364                                         unsigned Granularity, uint32_t TypeSize,
1365                                         bool IsWrite, Value *SizeArgument,
1366                                         bool UseCalls, uint32_t Exp) {
1367   auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1368   uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1369   unsigned Num = VTy->getVectorNumElements();
1370   auto Zero = ConstantInt::get(IntptrTy, 0);
1371   for (unsigned Idx = 0; Idx < Num; ++Idx) {
1372     Value *InstrumentedAddress = nullptr;
1373     Instruction *InsertBefore = I;
1374     if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1375       // dyn_cast as we might get UndefValue
1376       if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1377         if (Masked->isZero())
1378           // Mask is constant false, so no instrumentation needed.
1379           continue;
1380         // If we have a true or undef value, fall through to doInstrumentAddress
1381         // with InsertBefore == I
1382       }
1383     } else {
1384       IRBuilder<> IRB(I);
1385       Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1386       TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1387       InsertBefore = ThenTerm;
1388     }
1389 
1390     IRBuilder<> IRB(InsertBefore);
1391     InstrumentedAddress =
1392         IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1393     doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1394                         Granularity, ElemTypeSize, IsWrite, SizeArgument,
1395                         UseCalls, Exp);
1396   }
1397 }
1398 
1399 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
1400                                      Instruction *I, bool UseCalls,
1401                                      const DataLayout &DL) {
1402   bool IsWrite = false;
1403   unsigned Alignment = 0;
1404   uint64_t TypeSize = 0;
1405   Value *MaybeMask = nullptr;
1406   Value *Addr =
1407       isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
1408   assert(Addr);
1409 
1410   // Optimization experiments.
1411   // The experiments can be used to evaluate potential optimizations that remove
1412   // instrumentation (assess false negatives). Instead of completely removing
1413   // some instrumentation, you set Exp to a non-zero value (mask of optimization
1414   // experiments that want to remove instrumentation of this instruction).
1415   // If Exp is non-zero, this pass will emit special calls into runtime
1416   // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1417   // make runtime terminate the program in a special way (with a different
1418   // exit status). Then you run the new compiler on a buggy corpus, collect
1419   // the special terminations (ideally, you don't see them at all -- no false
1420   // negatives) and make the decision on the optimization.
1421   uint32_t Exp = ClForceExperiment;
1422 
1423   if (ClOpt && ClOptGlobals) {
1424     // If initialization order checking is disabled, a simple access to a
1425     // dynamically initialized global is always valid.
1426     GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
1427     if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
1428         isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1429       NumOptimizedAccessesToGlobalVar++;
1430       return;
1431     }
1432   }
1433 
1434   if (ClOpt && ClOptStack) {
1435     // A direct inbounds access to a stack variable is always valid.
1436     if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
1437         isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1438       NumOptimizedAccessesToStackVar++;
1439       return;
1440     }
1441   }
1442 
1443   if (IsWrite)
1444     NumInstrumentedWrites++;
1445   else
1446     NumInstrumentedReads++;
1447 
1448   unsigned Granularity = 1 << Mapping.Scale;
1449   if (MaybeMask) {
1450     instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1451                                 Alignment, Granularity, TypeSize, IsWrite,
1452                                 nullptr, UseCalls, Exp);
1453   } else {
1454     doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
1455                         IsWrite, nullptr, UseCalls, Exp);
1456   }
1457 }
1458 
1459 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1460                                                  Value *Addr, bool IsWrite,
1461                                                  size_t AccessSizeIndex,
1462                                                  Value *SizeArgument,
1463                                                  uint32_t Exp) {
1464   IRBuilder<> IRB(InsertBefore);
1465   Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1466   CallInst *Call = nullptr;
1467   if (SizeArgument) {
1468     if (Exp == 0)
1469       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1470                             {Addr, SizeArgument});
1471     else
1472       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1473                             {Addr, SizeArgument, ExpVal});
1474   } else {
1475     if (Exp == 0)
1476       Call =
1477           IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1478     else
1479       Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1480                             {Addr, ExpVal});
1481   }
1482 
1483   // We don't do Call->setDoesNotReturn() because the BB already has
1484   // UnreachableInst at the end.
1485   // This EmptyAsm is required to avoid callback merge.
1486   IRB.CreateCall(EmptyAsm, {});
1487   return Call;
1488 }
1489 
1490 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
1491                                            Value *ShadowValue,
1492                                            uint32_t TypeSize) {
1493   size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
1494   // Addr & (Granularity - 1)
1495   Value *LastAccessedByte =
1496       IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
1497   // (Addr & (Granularity - 1)) + size - 1
1498   if (TypeSize / 8 > 1)
1499     LastAccessedByte = IRB.CreateAdd(
1500         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1501   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1502   LastAccessedByte =
1503       IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1504   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1505   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1506 }
1507 
1508 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1509                                          Instruction *InsertBefore, Value *Addr,
1510                                          uint32_t TypeSize, bool IsWrite,
1511                                          Value *SizeArgument, bool UseCalls,
1512                                          uint32_t Exp) {
1513   bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
1514 
1515   IRBuilder<> IRB(InsertBefore);
1516   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1517   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1518 
1519   if (UseCalls) {
1520     if (Exp == 0)
1521       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1522                      AddrLong);
1523     else
1524       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1525                      {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1526     return;
1527   }
1528 
1529   if (IsMyriad) {
1530     // Strip the cache bit and do range check.
1531     // AddrLong &= ~kMyriadCacheBitMask32
1532     AddrLong = IRB.CreateAnd(AddrLong, ~kMyriadCacheBitMask32);
1533     // Tag = AddrLong >> kMyriadTagShift
1534     Value *Tag = IRB.CreateLShr(AddrLong, kMyriadTagShift);
1535     // Tag == kMyriadDDRTag
1536     Value *TagCheck =
1537         IRB.CreateICmpEQ(Tag, ConstantInt::get(IntptrTy, kMyriadDDRTag));
1538 
1539     TerminatorInst *TagCheckTerm = SplitBlockAndInsertIfThen(
1540         TagCheck, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1541     assert(cast<BranchInst>(TagCheckTerm)->isUnconditional());
1542     IRB.SetInsertPoint(TagCheckTerm);
1543     InsertBefore = TagCheckTerm;
1544   }
1545 
1546   Type *ShadowTy =
1547       IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1548   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1549   Value *ShadowPtr = memToShadow(AddrLong, IRB);
1550   Value *CmpVal = Constant::getNullValue(ShadowTy);
1551   Value *ShadowValue =
1552       IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1553 
1554   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1555   size_t Granularity = 1ULL << Mapping.Scale;
1556   TerminatorInst *CrashTerm = nullptr;
1557 
1558   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1559     // We use branch weights for the slow path check, to indicate that the slow
1560     // path is rarely taken. This seems to be the case for SPEC benchmarks.
1561     TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1562         Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1563     assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1564     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1565     IRB.SetInsertPoint(CheckTerm);
1566     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1567     if (Recover) {
1568       CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1569     } else {
1570       BasicBlock *CrashBlock =
1571         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1572       CrashTerm = new UnreachableInst(*C, CrashBlock);
1573       BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1574       ReplaceInstWithInst(CheckTerm, NewTerm);
1575     }
1576   } else {
1577     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
1578   }
1579 
1580   Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1581                                          AccessSizeIndex, SizeArgument, Exp);
1582   Crash->setDebugLoc(OrigIns->getDebugLoc());
1583 }
1584 
1585 // Instrument unusual size or unusual alignment.
1586 // We can not do it with a single check, so we do 1-byte check for the first
1587 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1588 // to report the actual access size.
1589 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1590     Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1591     bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1592   IRBuilder<> IRB(InsertBefore);
1593   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1594   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1595   if (UseCalls) {
1596     if (Exp == 0)
1597       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1598                      {AddrLong, Size});
1599     else
1600       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1601                      {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1602   } else {
1603     Value *LastByte = IRB.CreateIntToPtr(
1604         IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1605         Addr->getType());
1606     instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1607     instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
1608   }
1609 }
1610 
1611 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1612                                                   GlobalValue *ModuleName) {
1613   // Set up the arguments to our poison/unpoison functions.
1614   IRBuilder<> IRB(&GlobalInit.front(),
1615                   GlobalInit.front().getFirstInsertionPt());
1616 
1617   // Add a call to poison all external globals before the given function starts.
1618   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1619   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1620 
1621   // Add calls to unpoison all globals before each return instruction.
1622   for (auto &BB : GlobalInit.getBasicBlockList())
1623     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1624       CallInst::Create(AsanUnpoisonGlobals, "", RI);
1625 }
1626 
1627 void AddressSanitizerModule::createInitializerPoisonCalls(
1628     Module &M, GlobalValue *ModuleName) {
1629   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1630   if (!GV)
1631     return;
1632 
1633   ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1634   if (!CA)
1635     return;
1636 
1637   for (Use &OP : CA->operands()) {
1638     if (isa<ConstantAggregateZero>(OP)) continue;
1639     ConstantStruct *CS = cast<ConstantStruct>(OP);
1640 
1641     // Must have a function or null ptr.
1642     if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1643       if (F->getName() == kAsanModuleCtorName) continue;
1644       ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1645       // Don't instrument CTORs that will run before asan.module_ctor.
1646       if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1647       poisonOneInitializer(*F, ModuleName);
1648     }
1649   }
1650 }
1651 
1652 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1653   Type *Ty = G->getValueType();
1654   LLVM_DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1655 
1656   if (GlobalsMD.get(G).IsBlacklisted) return false;
1657   if (!Ty->isSized()) return false;
1658   if (!G->hasInitializer()) return false;
1659   if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
1660   // Two problems with thread-locals:
1661   //   - The address of the main thread's copy can't be computed at link-time.
1662   //   - Need to poison all copies, not just the main thread's one.
1663   if (G->isThreadLocal()) return false;
1664   // For now, just ignore this Global if the alignment is large.
1665   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1666 
1667   // For non-COFF targets, only instrument globals known to be defined by this
1668   // TU.
1669   // FIXME: We can instrument comdat globals on ELF if we are using the
1670   // GC-friendly metadata scheme.
1671   if (!TargetTriple.isOSBinFormatCOFF()) {
1672     if (!G->hasExactDefinition() || G->hasComdat())
1673       return false;
1674   } else {
1675     // On COFF, don't instrument non-ODR linkages.
1676     if (G->isInterposable())
1677       return false;
1678   }
1679 
1680   // If a comdat is present, it must have a selection kind that implies ODR
1681   // semantics: no duplicates, any, or exact match.
1682   if (Comdat *C = G->getComdat()) {
1683     switch (C->getSelectionKind()) {
1684     case Comdat::Any:
1685     case Comdat::ExactMatch:
1686     case Comdat::NoDuplicates:
1687       break;
1688     case Comdat::Largest:
1689     case Comdat::SameSize:
1690       return false;
1691     }
1692   }
1693 
1694   if (G->hasSection()) {
1695     StringRef Section = G->getSection();
1696 
1697     // Globals from llvm.metadata aren't emitted, do not instrument them.
1698     if (Section == "llvm.metadata") return false;
1699     // Do not instrument globals from special LLVM sections.
1700     if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
1701 
1702     // Do not instrument function pointers to initialization and termination
1703     // routines: dynamic linker will not properly handle redzones.
1704     if (Section.startswith(".preinit_array") ||
1705         Section.startswith(".init_array") ||
1706         Section.startswith(".fini_array")) {
1707       return false;
1708     }
1709 
1710     // On COFF, if the section name contains '$', it is highly likely that the
1711     // user is using section sorting to create an array of globals similar to
1712     // the way initialization callbacks are registered in .init_array and
1713     // .CRT$XCU. The ATL also registers things in .ATL$__[azm]. Adding redzones
1714     // to such globals is counterproductive, because the intent is that they
1715     // will form an array, and out-of-bounds accesses are expected.
1716     // See https://github.com/google/sanitizers/issues/305
1717     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1718     if (TargetTriple.isOSBinFormatCOFF() && Section.contains('$')) {
1719       LLVM_DEBUG(dbgs() << "Ignoring global in sorted section (contains '$'): "
1720                         << *G << "\n");
1721       return false;
1722     }
1723 
1724     if (TargetTriple.isOSBinFormatMachO()) {
1725       StringRef ParsedSegment, ParsedSection;
1726       unsigned TAA = 0, StubSize = 0;
1727       bool TAAParsed;
1728       std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1729           Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1730       assert(ErrorCode.empty() && "Invalid section specifier.");
1731 
1732       // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1733       // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1734       // them.
1735       if (ParsedSegment == "__OBJC" ||
1736           (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1737         LLVM_DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1738         return false;
1739       }
1740       // See https://github.com/google/sanitizers/issues/32
1741       // Constant CFString instances are compiled in the following way:
1742       //  -- the string buffer is emitted into
1743       //     __TEXT,__cstring,cstring_literals
1744       //  -- the constant NSConstantString structure referencing that buffer
1745       //     is placed into __DATA,__cfstring
1746       // Therefore there's no point in placing redzones into __DATA,__cfstring.
1747       // Moreover, it causes the linker to crash on OS X 10.7
1748       if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1749         LLVM_DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1750         return false;
1751       }
1752       // The linker merges the contents of cstring_literals and removes the
1753       // trailing zeroes.
1754       if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1755         LLVM_DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1756         return false;
1757       }
1758     }
1759   }
1760 
1761   return true;
1762 }
1763 
1764 // On Mach-O platforms, we emit global metadata in a separate section of the
1765 // binary in order to allow the linker to properly dead strip. This is only
1766 // supported on recent versions of ld64.
1767 bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1768   if (!TargetTriple.isOSBinFormatMachO())
1769     return false;
1770 
1771   if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1772     return true;
1773   if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
1774     return true;
1775   if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1776     return true;
1777 
1778   return false;
1779 }
1780 
1781 StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1782   switch (TargetTriple.getObjectFormat()) {
1783   case Triple::COFF:  return ".ASAN$GL";
1784   case Triple::ELF:   return "asan_globals";
1785   case Triple::MachO: return "__DATA,__asan_globals,regular";
1786   default: break;
1787   }
1788   llvm_unreachable("unsupported object format");
1789 }
1790 
1791 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1792   IRBuilder<> IRB(*C);
1793 
1794   // Declare our poisoning and unpoisoning functions.
1795   AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1796       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
1797   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1798   AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1799       kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
1800   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1801 
1802   // Declare functions that register/unregister globals.
1803   AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1804       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
1805   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1806   AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1807       M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1808                             IntptrTy, IntptrTy));
1809   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1810 
1811   // Declare the functions that find globals in a shared object and then invoke
1812   // the (un)register function on them.
1813   AsanRegisterImageGlobals =
1814       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1815           kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
1816   AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
1817 
1818   AsanUnregisterImageGlobals =
1819       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1820           kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
1821   AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
1822 
1823   AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1824       M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1825                             IntptrTy, IntptrTy, IntptrTy));
1826   AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1827 
1828   AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1829       M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1830                             IntptrTy, IntptrTy, IntptrTy));
1831   AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
1832 }
1833 
1834 // Put the metadata and the instrumented global in the same group. This ensures
1835 // that the metadata is discarded if the instrumented global is discarded.
1836 void AddressSanitizerModule::SetComdatForGlobalMetadata(
1837     GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
1838   Module &M = *G->getParent();
1839   Comdat *C = G->getComdat();
1840   if (!C) {
1841     if (!G->hasName()) {
1842       // If G is unnamed, it must be internal. Give it an artificial name
1843       // so we can put it in a comdat.
1844       assert(G->hasLocalLinkage());
1845       G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1846     }
1847 
1848     if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1849       std::string Name = G->getName();
1850       Name += InternalSuffix;
1851       C = M.getOrInsertComdat(Name);
1852     } else {
1853       C = M.getOrInsertComdat(G->getName());
1854     }
1855 
1856     // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
1857     // linkage to internal linkage so that a symbol table entry is emitted. This
1858     // is necessary in order to create the comdat group.
1859     if (TargetTriple.isOSBinFormatCOFF()) {
1860       C->setSelectionKind(Comdat::NoDuplicates);
1861       if (G->hasPrivateLinkage())
1862         G->setLinkage(GlobalValue::InternalLinkage);
1863     }
1864     G->setComdat(C);
1865   }
1866 
1867   assert(G->hasComdat());
1868   Metadata->setComdat(G->getComdat());
1869 }
1870 
1871 // Create a separate metadata global and put it in the appropriate ASan
1872 // global registration section.
1873 GlobalVariable *
1874 AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1875                                              StringRef OriginalName) {
1876   auto Linkage = TargetTriple.isOSBinFormatMachO()
1877                      ? GlobalVariable::InternalLinkage
1878                      : GlobalVariable::PrivateLinkage;
1879   GlobalVariable *Metadata = new GlobalVariable(
1880       M, Initializer->getType(), false, Linkage, Initializer,
1881       Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
1882   Metadata->setSection(getGlobalMetadataSection());
1883   return Metadata;
1884 }
1885 
1886 IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
1887   AsanDtorFunction =
1888       Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1889                        GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1890   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1891 
1892   return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1893 }
1894 
1895 void AddressSanitizerModule::InstrumentGlobalsCOFF(
1896     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1897     ArrayRef<Constant *> MetadataInitializers) {
1898   assert(ExtendedGlobals.size() == MetadataInitializers.size());
1899   auto &DL = M.getDataLayout();
1900 
1901   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1902     Constant *Initializer = MetadataInitializers[i];
1903     GlobalVariable *G = ExtendedGlobals[i];
1904     GlobalVariable *Metadata =
1905         CreateMetadataGlobal(M, Initializer, G->getName());
1906 
1907     // The MSVC linker always inserts padding when linking incrementally. We
1908     // cope with that by aligning each struct to its size, which must be a power
1909     // of two.
1910     unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1911     assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1912            "global metadata will not be padded appropriately");
1913     Metadata->setAlignment(SizeOfGlobalStruct);
1914 
1915     SetComdatForGlobalMetadata(G, Metadata, "");
1916   }
1917 }
1918 
1919 void AddressSanitizerModule::InstrumentGlobalsELF(
1920     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1921     ArrayRef<Constant *> MetadataInitializers,
1922     const std::string &UniqueModuleId) {
1923   assert(ExtendedGlobals.size() == MetadataInitializers.size());
1924 
1925   SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1926   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1927     GlobalVariable *G = ExtendedGlobals[i];
1928     GlobalVariable *Metadata =
1929         CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1930     MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1931     Metadata->setMetadata(LLVMContext::MD_associated, MD);
1932     MetadataGlobals[i] = Metadata;
1933 
1934     SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1935   }
1936 
1937   // Update llvm.compiler.used, adding the new metadata globals. This is
1938   // needed so that during LTO these variables stay alive.
1939   if (!MetadataGlobals.empty())
1940     appendToCompilerUsed(M, MetadataGlobals);
1941 
1942   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1943   // to look up the loaded image that contains it. Second, we can store in it
1944   // whether registration has already occurred, to prevent duplicate
1945   // registration.
1946   //
1947   // Common linkage ensures that there is only one global per shared library.
1948   GlobalVariable *RegisteredFlag = new GlobalVariable(
1949       M, IntptrTy, false, GlobalVariable::CommonLinkage,
1950       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1951   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1952 
1953   // Create start and stop symbols.
1954   GlobalVariable *StartELFMetadata = new GlobalVariable(
1955       M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1956       "__start_" + getGlobalMetadataSection());
1957   StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1958   GlobalVariable *StopELFMetadata = new GlobalVariable(
1959       M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1960       "__stop_" + getGlobalMetadataSection());
1961   StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1962 
1963   // Create a call to register the globals with the runtime.
1964   IRB.CreateCall(AsanRegisterElfGlobals,
1965                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1966                   IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1967                   IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1968 
1969   // We also need to unregister globals at the end, e.g., when a shared library
1970   // gets closed.
1971   IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1972   IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1973                       {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1974                        IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1975                        IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1976 }
1977 
1978 void AddressSanitizerModule::InstrumentGlobalsMachO(
1979     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1980     ArrayRef<Constant *> MetadataInitializers) {
1981   assert(ExtendedGlobals.size() == MetadataInitializers.size());
1982 
1983   // On recent Mach-O platforms, use a structure which binds the liveness of
1984   // the global variable to the metadata struct. Keep the list of "Liveness" GV
1985   // created to be added to llvm.compiler.used
1986   StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
1987   SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1988 
1989   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1990     Constant *Initializer = MetadataInitializers[i];
1991     GlobalVariable *G = ExtendedGlobals[i];
1992     GlobalVariable *Metadata =
1993         CreateMetadataGlobal(M, Initializer, G->getName());
1994 
1995     // On recent Mach-O platforms, we emit the global metadata in a way that
1996     // allows the linker to properly strip dead globals.
1997     auto LivenessBinder =
1998         ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
1999                             ConstantExpr::getPointerCast(Metadata, IntptrTy));
2000     GlobalVariable *Liveness = new GlobalVariable(
2001         M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
2002         Twine("__asan_binder_") + G->getName());
2003     Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
2004     LivenessGlobals[i] = Liveness;
2005   }
2006 
2007   // Update llvm.compiler.used, adding the new liveness globals. This is
2008   // needed so that during LTO these variables stay alive. The alternative
2009   // would be to have the linker handling the LTO symbols, but libLTO
2010   // current API does not expose access to the section for each symbol.
2011   if (!LivenessGlobals.empty())
2012     appendToCompilerUsed(M, LivenessGlobals);
2013 
2014   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2015   // to look up the loaded image that contains it. Second, we can store in it
2016   // whether registration has already occurred, to prevent duplicate
2017   // registration.
2018   //
2019   // common linkage ensures that there is only one global per shared library.
2020   GlobalVariable *RegisteredFlag = new GlobalVariable(
2021       M, IntptrTy, false, GlobalVariable::CommonLinkage,
2022       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2023   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2024 
2025   IRB.CreateCall(AsanRegisterImageGlobals,
2026                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2027 
2028   // We also need to unregister globals at the end, e.g., when a shared library
2029   // gets closed.
2030   IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2031   IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
2032                       {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2033 }
2034 
2035 void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
2036     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2037     ArrayRef<Constant *> MetadataInitializers) {
2038   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2039   unsigned N = ExtendedGlobals.size();
2040   assert(N > 0);
2041 
2042   // On platforms that don't have a custom metadata section, we emit an array
2043   // of global metadata structures.
2044   ArrayType *ArrayOfGlobalStructTy =
2045       ArrayType::get(MetadataInitializers[0]->getType(), N);
2046   auto AllGlobals = new GlobalVariable(
2047       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
2048       ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
2049   if (Mapping.Scale > 3)
2050     AllGlobals->setAlignment(1ULL << Mapping.Scale);
2051 
2052   IRB.CreateCall(AsanRegisterGlobals,
2053                  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2054                   ConstantInt::get(IntptrTy, N)});
2055 
2056   // We also need to unregister globals at the end, e.g., when a shared library
2057   // gets closed.
2058   IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2059   IRB_Dtor.CreateCall(AsanUnregisterGlobals,
2060                       {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2061                        ConstantInt::get(IntptrTy, N)});
2062 }
2063 
2064 // This function replaces all global variables with new variables that have
2065 // trailing redzones. It also creates a function that poisons
2066 // redzones and inserts this function into llvm.global_ctors.
2067 // Sets *CtorComdat to true if the global registration code emitted into the
2068 // asan constructor is comdat-compatible.
2069 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
2070   *CtorComdat = false;
2071   GlobalsMD.init(M);
2072 
2073   SmallVector<GlobalVariable *, 16> GlobalsToChange;
2074 
2075   for (auto &G : M.globals()) {
2076     if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
2077   }
2078 
2079   size_t n = GlobalsToChange.size();
2080   if (n == 0) {
2081     *CtorComdat = true;
2082     return false;
2083   }
2084 
2085   auto &DL = M.getDataLayout();
2086 
2087   // A global is described by a structure
2088   //   size_t beg;
2089   //   size_t size;
2090   //   size_t size_with_redzone;
2091   //   const char *name;
2092   //   const char *module_name;
2093   //   size_t has_dynamic_init;
2094   //   void *source_location;
2095   //   size_t odr_indicator;
2096   // We initialize an array of such structures and pass it to a run-time call.
2097   StructType *GlobalStructTy =
2098       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
2099                       IntptrTy, IntptrTy, IntptrTy);
2100   SmallVector<GlobalVariable *, 16> NewGlobals(n);
2101   SmallVector<Constant *, 16> Initializers(n);
2102 
2103   bool HasDynamicallyInitializedGlobals = false;
2104 
2105   // We shouldn't merge same module names, as this string serves as unique
2106   // module ID in runtime.
2107   GlobalVariable *ModuleName = createPrivateGlobalForString(
2108       M, M.getModuleIdentifier(), /*AllowMerging*/ false);
2109 
2110   for (size_t i = 0; i < n; i++) {
2111     static const uint64_t kMaxGlobalRedzone = 1 << 18;
2112     GlobalVariable *G = GlobalsToChange[i];
2113 
2114     auto MD = GlobalsMD.get(G);
2115     StringRef NameForGlobal = G->getName();
2116     // Create string holding the global name (use global name from metadata
2117     // if it's available, otherwise just write the name of global variable).
2118     GlobalVariable *Name = createPrivateGlobalForString(
2119         M, MD.Name.empty() ? NameForGlobal : MD.Name,
2120         /*AllowMerging*/ true);
2121 
2122     Type *Ty = G->getValueType();
2123     uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
2124     uint64_t MinRZ = MinRedzoneSizeForGlobal();
2125     // MinRZ <= RZ <= kMaxGlobalRedzone
2126     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
2127     uint64_t RZ = std::max(
2128         MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
2129     uint64_t RightRedzoneSize = RZ;
2130     // Round up to MinRZ
2131     if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
2132     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
2133     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2134 
2135     StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2136     Constant *NewInitializer = ConstantStruct::get(
2137         NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
2138 
2139     // Create a new global variable with enough space for a redzone.
2140     GlobalValue::LinkageTypes Linkage = G->getLinkage();
2141     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2142       Linkage = GlobalValue::InternalLinkage;
2143     GlobalVariable *NewGlobal =
2144         new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2145                            "", G, G->getThreadLocalMode());
2146     NewGlobal->copyAttributesFrom(G);
2147     NewGlobal->setComdat(G->getComdat());
2148     NewGlobal->setAlignment(MinRZ);
2149 
2150     // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2151     if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2152         G->isConstant()) {
2153       auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2154       if (Seq && Seq->isCString())
2155         NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2156     }
2157 
2158     // Transfer the debug info.  The payload starts at offset zero so we can
2159     // copy the debug info over as is.
2160     SmallVector<DIGlobalVariableExpression *, 1> GVs;
2161     G->getDebugInfo(GVs);
2162     for (auto *GV : GVs)
2163       NewGlobal->addDebugInfo(GV);
2164 
2165     Value *Indices2[2];
2166     Indices2[0] = IRB.getInt32(0);
2167     Indices2[1] = IRB.getInt32(0);
2168 
2169     G->replaceAllUsesWith(
2170         ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
2171     NewGlobal->takeName(G);
2172     G->eraseFromParent();
2173     NewGlobals[i] = NewGlobal;
2174 
2175     Constant *SourceLoc;
2176     if (!MD.SourceLoc.empty()) {
2177       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2178       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2179     } else {
2180       SourceLoc = ConstantInt::get(IntptrTy, 0);
2181     }
2182 
2183     Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2184     GlobalValue *InstrumentedGlobal = NewGlobal;
2185 
2186     bool CanUsePrivateAliases =
2187         TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2188         TargetTriple.isOSBinFormatWasm();
2189     if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
2190       // Create local alias for NewGlobal to avoid crash on ODR between
2191       // instrumented and non-instrumented libraries.
2192       auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
2193                                      NameForGlobal + M.getName(), NewGlobal);
2194 
2195       // With local aliases, we need to provide another externally visible
2196       // symbol __odr_asan_XXX to detect ODR violation.
2197       auto *ODRIndicatorSym =
2198           new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2199                              Constant::getNullValue(IRB.getInt8Ty()),
2200                              kODRGenPrefix + NameForGlobal, nullptr,
2201                              NewGlobal->getThreadLocalMode());
2202 
2203       // Set meaningful attributes for indicator symbol.
2204       ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2205       ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2206       ODRIndicatorSym->setAlignment(1);
2207       ODRIndicator = ODRIndicatorSym;
2208       InstrumentedGlobal = GA;
2209     }
2210 
2211     Constant *Initializer = ConstantStruct::get(
2212         GlobalStructTy,
2213         ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
2214         ConstantInt::get(IntptrTy, SizeInBytes),
2215         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2216         ConstantExpr::getPointerCast(Name, IntptrTy),
2217         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
2218         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
2219         ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
2220 
2221     if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
2222 
2223     LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
2224 
2225     Initializers[i] = Initializer;
2226   }
2227 
2228   // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2229   // ConstantMerge'ing them.
2230   SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2231   for (size_t i = 0; i < n; i++) {
2232     GlobalVariable *G = NewGlobals[i];
2233     if (G->getName().empty()) continue;
2234     GlobalsToAddToUsedList.push_back(G);
2235   }
2236   appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2237 
2238   std::string ELFUniqueModuleId =
2239       (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2240                                                         : "";
2241 
2242   if (!ELFUniqueModuleId.empty()) {
2243     InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2244     *CtorComdat = true;
2245   } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
2246     InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2247   } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2248     InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2249   } else {
2250     InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2251   }
2252 
2253   // Create calls for poisoning before initializers run and unpoisoning after.
2254   if (HasDynamicallyInitializedGlobals)
2255     createInitializerPoisonCalls(M, ModuleName);
2256 
2257   LLVM_DEBUG(dbgs() << M);
2258   return true;
2259 }
2260 
2261 int AddressSanitizerModule::GetAsanVersion(const Module &M) const {
2262   int LongSize = M.getDataLayout().getPointerSizeInBits();
2263   bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2264   int Version = 8;
2265   // 32-bit Android is one version ahead because of the switch to dynamic
2266   // shadow.
2267   Version += (LongSize == 32 && isAndroid);
2268   return Version;
2269 }
2270 
2271 bool AddressSanitizerModule::runOnModule(Module &M) {
2272   C = &(M.getContext());
2273   int LongSize = M.getDataLayout().getPointerSizeInBits();
2274   IntptrTy = Type::getIntNTy(*C, LongSize);
2275   TargetTriple = Triple(M.getTargetTriple());
2276   Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2277   initializeCallbacks(M);
2278 
2279   if (CompileKernel)
2280     return false;
2281 
2282   // Create a module constructor. A destructor is created lazily because not all
2283   // platforms, and not all modules need it.
2284   std::string VersionCheckName =
2285       kAsanVersionCheckNamePrefix + std::to_string(GetAsanVersion(M));
2286   std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2287       M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
2288       /*InitArgs=*/{}, VersionCheckName);
2289 
2290   bool CtorComdat = true;
2291   bool Changed = false;
2292   // TODO(glider): temporarily disabled globals instrumentation for KASan.
2293   if (ClGlobals) {
2294     IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2295     Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2296   }
2297 
2298   // Put the constructor and destructor in comdat if both
2299   // (1) global instrumentation is not TU-specific
2300   // (2) target is ELF.
2301   if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2302     AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2303     appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2304                         AsanCtorFunction);
2305     if (AsanDtorFunction) {
2306       AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2307       appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2308                           AsanDtorFunction);
2309     }
2310   } else {
2311     appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2312     if (AsanDtorFunction)
2313       appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
2314   }
2315 
2316   return Changed;
2317 }
2318 
2319 void AddressSanitizer::initializeCallbacks(Module &M) {
2320   IRBuilder<> IRB(*C);
2321   // Create __asan_report* callbacks.
2322   // IsWrite, TypeSize and Exp are encoded in the function name.
2323   for (int Exp = 0; Exp < 2; Exp++) {
2324     for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2325       const std::string TypeStr = AccessIsWrite ? "store" : "load";
2326       const std::string ExpStr = Exp ? "exp_" : "";
2327       const std::string EndingStr = Recover ? "_noabort" : "";
2328 
2329       SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2330       SmallVector<Type *, 2> Args1{1, IntptrTy};
2331       if (Exp) {
2332         Type *ExpType = Type::getInt32Ty(*C);
2333         Args2.push_back(ExpType);
2334         Args1.push_back(ExpType);
2335       }
2336       AsanErrorCallbackSized[AccessIsWrite][Exp] =
2337           checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2338               kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
2339               FunctionType::get(IRB.getVoidTy(), Args2, false)));
2340 
2341       AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2342           checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2343               ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2344               FunctionType::get(IRB.getVoidTy(), Args2, false)));
2345 
2346       for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2347            AccessSizeIndex++) {
2348         const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2349         AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2350             checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2351                 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2352                 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2353 
2354         AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2355             checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2356                 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2357                 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2358       }
2359     }
2360   }
2361 
2362   const std::string MemIntrinCallbackPrefix =
2363       CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
2364   AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2365       MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
2366       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
2367   AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2368       MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
2369       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
2370   AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2371       MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
2372       IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
2373 
2374   AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
2375       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
2376 
2377   AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2378       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
2379   AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2380       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
2381   // We insert an empty inline asm after __asan_report* to avoid callback merge.
2382   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2383                             StringRef(""), StringRef(""),
2384                             /*hasSideEffects=*/true);
2385   if (Mapping.InGlobal)
2386     AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2387                                            ArrayType::get(IRB.getInt8Ty(), 0));
2388 }
2389 
2390 // virtual
2391 bool AddressSanitizer::doInitialization(Module &M) {
2392   // Initialize the private fields. No one has accessed them before.
2393   GlobalsMD.init(M);
2394 
2395   C = &(M.getContext());
2396   LongSize = M.getDataLayout().getPointerSizeInBits();
2397   IntptrTy = Type::getIntNTy(*C, LongSize);
2398   TargetTriple = Triple(M.getTargetTriple());
2399 
2400   Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2401   return true;
2402 }
2403 
2404 bool AddressSanitizer::doFinalization(Module &M) {
2405   GlobalsMD.reset();
2406   return false;
2407 }
2408 
2409 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2410   // For each NSObject descendant having a +load method, this method is invoked
2411   // by the ObjC runtime before any of the static constructors is called.
2412   // Therefore we need to instrument such methods with a call to __asan_init
2413   // at the beginning in order to initialize our runtime before any access to
2414   // the shadow memory.
2415   // We cannot just ignore these methods, because they may call other
2416   // instrumented functions.
2417   if (F.getName().find(" load]") != std::string::npos) {
2418     Function *AsanInitFunction =
2419         declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
2420     IRBuilder<> IRB(&F.front(), F.front().begin());
2421     IRB.CreateCall(AsanInitFunction, {});
2422     return true;
2423   }
2424   return false;
2425 }
2426 
2427 void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2428   // Generate code only when dynamic addressing is needed.
2429   if (Mapping.Offset != kDynamicShadowSentinel)
2430     return;
2431 
2432   IRBuilder<> IRB(&F.front().front());
2433   if (Mapping.InGlobal) {
2434     if (ClWithIfuncSuppressRemat) {
2435       // An empty inline asm with input reg == output reg.
2436       // An opaque pointer-to-int cast, basically.
2437       InlineAsm *Asm = InlineAsm::get(
2438           FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2439           StringRef(""), StringRef("=r,0"),
2440           /*hasSideEffects=*/false);
2441       LocalDynamicShadow =
2442           IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2443     } else {
2444       LocalDynamicShadow =
2445           IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2446     }
2447   } else {
2448     Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2449         kAsanShadowMemoryDynamicAddress, IntptrTy);
2450     LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2451   }
2452 }
2453 
2454 void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2455   // Find the one possible call to llvm.localescape and pre-mark allocas passed
2456   // to it as uninteresting. This assumes we haven't started processing allocas
2457   // yet. This check is done up front because iterating the use list in
2458   // isInterestingAlloca would be algorithmically slower.
2459   assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2460 
2461   // Try to get the declaration of llvm.localescape. If it's not in the module,
2462   // we can exit early.
2463   if (!F.getParent()->getFunction("llvm.localescape")) return;
2464 
2465   // Look for a call to llvm.localescape call in the entry block. It can't be in
2466   // any other block.
2467   for (Instruction &I : F.getEntryBlock()) {
2468     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2469     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2470       // We found a call. Mark all the allocas passed in as uninteresting.
2471       for (Value *Arg : II->arg_operands()) {
2472         AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2473         assert(AI && AI->isStaticAlloca() &&
2474                "non-static alloca arg to localescape");
2475         ProcessedAllocas[AI] = false;
2476       }
2477       break;
2478     }
2479   }
2480 }
2481 
2482 bool AddressSanitizer::runOnFunction(Function &F) {
2483   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2484   if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2485   if (F.getName().startswith("__asan_")) return false;
2486 
2487   bool FunctionModified = false;
2488 
2489   // If needed, insert __asan_init before checking for SanitizeAddress attr.
2490   // This function needs to be called even if the function body is not
2491   // instrumented.
2492   if (maybeInsertAsanInitAtFunctionEntry(F))
2493     FunctionModified = true;
2494 
2495   // Leave if the function doesn't need instrumentation.
2496   if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2497 
2498   LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2499 
2500   initializeCallbacks(*F.getParent());
2501   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2502 
2503   FunctionStateRAII CleanupObj(this);
2504 
2505   maybeInsertDynamicShadowAtFunctionEntry(F);
2506 
2507   // We can't instrument allocas used with llvm.localescape. Only static allocas
2508   // can be passed to that intrinsic.
2509   markEscapedLocalAllocas(F);
2510 
2511   // We want to instrument every address only once per basic block (unless there
2512   // are calls between uses).
2513   SmallPtrSet<Value *, 16> TempsToInstrument;
2514   SmallVector<Instruction *, 16> ToInstrument;
2515   SmallVector<Instruction *, 8> NoReturnCalls;
2516   SmallVector<BasicBlock *, 16> AllBlocks;
2517   SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2518   int NumAllocas = 0;
2519   bool IsWrite;
2520   unsigned Alignment;
2521   uint64_t TypeSize;
2522   const TargetLibraryInfo *TLI =
2523       &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2524 
2525   // Fill the set of memory operations to instrument.
2526   for (auto &BB : F) {
2527     AllBlocks.push_back(&BB);
2528     TempsToInstrument.clear();
2529     int NumInsnsPerBB = 0;
2530     for (auto &Inst : BB) {
2531       if (LooksLikeCodeInBug11395(&Inst)) return false;
2532       Value *MaybeMask = nullptr;
2533       if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
2534                                                   &Alignment, &MaybeMask)) {
2535         if (ClOpt && ClOptSameTemp) {
2536           // If we have a mask, skip instrumentation if we've already
2537           // instrumented the full object. But don't add to TempsToInstrument
2538           // because we might get another load/store with a different mask.
2539           if (MaybeMask) {
2540             if (TempsToInstrument.count(Addr))
2541               continue; // We've seen this (whole) temp in the current BB.
2542           } else {
2543             if (!TempsToInstrument.insert(Addr).second)
2544               continue; // We've seen this temp in the current BB.
2545           }
2546         }
2547       } else if (ClInvalidPointerPairs &&
2548                  isInterestingPointerComparisonOrSubtraction(&Inst)) {
2549         PointerComparisonsOrSubtracts.push_back(&Inst);
2550         continue;
2551       } else if (isa<MemIntrinsic>(Inst)) {
2552         // ok, take it.
2553       } else {
2554         if (isa<AllocaInst>(Inst)) NumAllocas++;
2555         CallSite CS(&Inst);
2556         if (CS) {
2557           // A call inside BB.
2558           TempsToInstrument.clear();
2559           if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
2560         }
2561         if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2562           maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
2563         continue;
2564       }
2565       ToInstrument.push_back(&Inst);
2566       NumInsnsPerBB++;
2567       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
2568     }
2569   }
2570 
2571   bool UseCalls =
2572       (ClInstrumentationWithCallsThreshold >= 0 &&
2573        ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
2574   const DataLayout &DL = F.getParent()->getDataLayout();
2575   ObjectSizeOpts ObjSizeOpts;
2576   ObjSizeOpts.RoundToAlign = true;
2577   ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
2578 
2579   // Instrument.
2580   int NumInstrumented = 0;
2581   for (auto Inst : ToInstrument) {
2582     if (ClDebugMin < 0 || ClDebugMax < 0 ||
2583         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
2584       if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
2585         instrumentMop(ObjSizeVis, Inst, UseCalls,
2586                       F.getParent()->getDataLayout());
2587       else
2588         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
2589     }
2590     NumInstrumented++;
2591   }
2592 
2593   FunctionStackPoisoner FSP(F, *this);
2594   bool ChangedStack = FSP.runOnFunction();
2595 
2596   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2597   // See e.g. https://github.com/google/sanitizers/issues/37
2598   for (auto CI : NoReturnCalls) {
2599     IRBuilder<> IRB(CI);
2600     IRB.CreateCall(AsanHandleNoReturnFunc, {});
2601   }
2602 
2603   for (auto Inst : PointerComparisonsOrSubtracts) {
2604     instrumentPointerComparisonOrSubtraction(Inst);
2605     NumInstrumented++;
2606   }
2607 
2608   if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2609     FunctionModified = true;
2610 
2611   LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2612                     << F << "\n");
2613 
2614   return FunctionModified;
2615 }
2616 
2617 // Workaround for bug 11395: we don't want to instrument stack in functions
2618 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2619 // FIXME: remove once the bug 11395 is fixed.
2620 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2621   if (LongSize != 32) return false;
2622   CallInst *CI = dyn_cast<CallInst>(I);
2623   if (!CI || !CI->isInlineAsm()) return false;
2624   if (CI->getNumArgOperands() <= 5) return false;
2625   // We have inline assembly with quite a few arguments.
2626   return true;
2627 }
2628 
2629 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2630   IRBuilder<> IRB(*C);
2631   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2632     std::string Suffix = itostr(i);
2633     AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2634         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
2635                               IntptrTy));
2636     AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
2637         M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2638                               IRB.getVoidTy(), IntptrTy, IntptrTy));
2639   }
2640   if (ASan.UseAfterScope) {
2641     AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2642         M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2643                               IntptrTy, IntptrTy));
2644     AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2645         M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2646                               IntptrTy, IntptrTy));
2647   }
2648 
2649   for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2650     std::ostringstream Name;
2651     Name << kAsanSetShadowPrefix;
2652     Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2653     AsanSetShadowFunc[Val] =
2654         checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2655             Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
2656   }
2657 
2658   AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2659       kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
2660   AsanAllocasUnpoisonFunc =
2661       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2662           kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
2663 }
2664 
2665 void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2666                                                ArrayRef<uint8_t> ShadowBytes,
2667                                                size_t Begin, size_t End,
2668                                                IRBuilder<> &IRB,
2669                                                Value *ShadowBase) {
2670   if (Begin >= End)
2671     return;
2672 
2673   const size_t LargestStoreSizeInBytes =
2674       std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2675 
2676   const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2677 
2678   // Poison given range in shadow using larges store size with out leading and
2679   // trailing zeros in ShadowMask. Zeros never change, so they need neither
2680   // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2681   // middle of a store.
2682   for (size_t i = Begin; i < End;) {
2683     if (!ShadowMask[i]) {
2684       assert(!ShadowBytes[i]);
2685       ++i;
2686       continue;
2687     }
2688 
2689     size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2690     // Fit store size into the range.
2691     while (StoreSizeInBytes > End - i)
2692       StoreSizeInBytes /= 2;
2693 
2694     // Minimize store size by trimming trailing zeros.
2695     for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2696       while (j <= StoreSizeInBytes / 2)
2697         StoreSizeInBytes /= 2;
2698     }
2699 
2700     uint64_t Val = 0;
2701     for (size_t j = 0; j < StoreSizeInBytes; j++) {
2702       if (IsLittleEndian)
2703         Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2704       else
2705         Val = (Val << 8) | ShadowBytes[i + j];
2706     }
2707 
2708     Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2709     Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
2710     IRB.CreateAlignedStore(
2711         Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
2712 
2713     i += StoreSizeInBytes;
2714   }
2715 }
2716 
2717 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2718                                          ArrayRef<uint8_t> ShadowBytes,
2719                                          IRBuilder<> &IRB, Value *ShadowBase) {
2720   copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2721 }
2722 
2723 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2724                                          ArrayRef<uint8_t> ShadowBytes,
2725                                          size_t Begin, size_t End,
2726                                          IRBuilder<> &IRB, Value *ShadowBase) {
2727   assert(ShadowMask.size() == ShadowBytes.size());
2728   size_t Done = Begin;
2729   for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2730     if (!ShadowMask[i]) {
2731       assert(!ShadowBytes[i]);
2732       continue;
2733     }
2734     uint8_t Val = ShadowBytes[i];
2735     if (!AsanSetShadowFunc[Val])
2736       continue;
2737 
2738     // Skip same values.
2739     for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
2740     }
2741 
2742     if (j - i >= ClMaxInlinePoisoningSize) {
2743       copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
2744       IRB.CreateCall(AsanSetShadowFunc[Val],
2745                      {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2746                       ConstantInt::get(IntptrTy, j - i)});
2747       Done = j;
2748     }
2749   }
2750 
2751   copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
2752 }
2753 
2754 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
2755 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2756 static int StackMallocSizeClass(uint64_t LocalStackSize) {
2757   assert(LocalStackSize <= kMaxStackMallocSize);
2758   uint64_t MaxSize = kMinStackMallocSize;
2759   for (int i = 0;; i++, MaxSize *= 2)
2760     if (LocalStackSize <= MaxSize) return i;
2761   llvm_unreachable("impossible LocalStackSize");
2762 }
2763 
2764 void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
2765   Instruction *CopyInsertPoint = &F.front().front();
2766   if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2767     // Insert after the dynamic shadow location is determined
2768     CopyInsertPoint = CopyInsertPoint->getNextNode();
2769     assert(CopyInsertPoint);
2770   }
2771   IRBuilder<> IRB(CopyInsertPoint);
2772   const DataLayout &DL = F.getParent()->getDataLayout();
2773   for (Argument &Arg : F.args()) {
2774     if (Arg.hasByValAttr()) {
2775       Type *Ty = Arg.getType()->getPointerElementType();
2776       unsigned Align = Arg.getParamAlignment();
2777       if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2778 
2779       AllocaInst *AI = IRB.CreateAlloca(
2780           Ty, nullptr,
2781           (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
2782               ".byval");
2783       AI->setAlignment(Align);
2784       Arg.replaceAllUsesWith(AI);
2785 
2786       uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2787       IRB.CreateMemCpy(AI, Align, &Arg, Align, AllocSize);
2788     }
2789   }
2790 }
2791 
2792 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2793                                           Value *ValueIfTrue,
2794                                           Instruction *ThenTerm,
2795                                           Value *ValueIfFalse) {
2796   PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2797   BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2798   PHI->addIncoming(ValueIfFalse, CondBlock);
2799   BasicBlock *ThenBlock = ThenTerm->getParent();
2800   PHI->addIncoming(ValueIfTrue, ThenBlock);
2801   return PHI;
2802 }
2803 
2804 Value *FunctionStackPoisoner::createAllocaForLayout(
2805     IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2806   AllocaInst *Alloca;
2807   if (Dynamic) {
2808     Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2809                               ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2810                               "MyAlloca");
2811   } else {
2812     Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2813                               nullptr, "MyAlloca");
2814     assert(Alloca->isStaticAlloca());
2815   }
2816   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2817   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2818   Alloca->setAlignment(FrameAlignment);
2819   return IRB.CreatePointerCast(Alloca, IntptrTy);
2820 }
2821 
2822 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2823   BasicBlock &FirstBB = *F.begin();
2824   IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2825   DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2826   IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2827   DynamicAllocaLayout->setAlignment(32);
2828 }
2829 
2830 void FunctionStackPoisoner::processDynamicAllocas() {
2831   if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2832     assert(DynamicAllocaPoisonCallVec.empty());
2833     return;
2834   }
2835 
2836   // Insert poison calls for lifetime intrinsics for dynamic allocas.
2837   for (const auto &APC : DynamicAllocaPoisonCallVec) {
2838     assert(APC.InsBefore);
2839     assert(APC.AI);
2840     assert(ASan.isInterestingAlloca(*APC.AI));
2841     assert(!APC.AI->isStaticAlloca());
2842 
2843     IRBuilder<> IRB(APC.InsBefore);
2844     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2845     // Dynamic allocas will be unpoisoned unconditionally below in
2846     // unpoisonDynamicAllocas.
2847     // Flag that we need unpoison static allocas.
2848   }
2849 
2850   // Handle dynamic allocas.
2851   createDynamicAllocasInitStorage();
2852   for (auto &AI : DynamicAllocaVec)
2853     handleDynamicAllocaCall(AI);
2854   unpoisonDynamicAllocas();
2855 }
2856 
2857 void FunctionStackPoisoner::processStaticAllocas() {
2858   if (AllocaVec.empty()) {
2859     assert(StaticAllocaPoisonCallVec.empty());
2860     return;
2861   }
2862 
2863   int StackMallocIdx = -1;
2864   DebugLoc EntryDebugLocation;
2865   if (auto SP = F.getSubprogram())
2866     EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
2867 
2868   Instruction *InsBefore = AllocaVec[0];
2869   IRBuilder<> IRB(InsBefore);
2870   IRB.SetCurrentDebugLocation(EntryDebugLocation);
2871 
2872   // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2873   // debug info is broken, because only entry-block allocas are treated as
2874   // regular stack slots.
2875   auto InsBeforeB = InsBefore->getParent();
2876   assert(InsBeforeB == &F.getEntryBlock());
2877   for (auto *AI : StaticAllocasToMoveUp)
2878     if (AI->getParent() == InsBeforeB)
2879       AI->moveBefore(InsBefore);
2880 
2881   // If we have a call to llvm.localescape, keep it in the entry block.
2882   if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2883 
2884   SmallVector<ASanStackVariableDescription, 16> SVD;
2885   SVD.reserve(AllocaVec.size());
2886   for (AllocaInst *AI : AllocaVec) {
2887     ASanStackVariableDescription D = {AI->getName().data(),
2888                                       ASan.getAllocaSizeInBytes(*AI),
2889                                       0,
2890                                       AI->getAlignment(),
2891                                       AI,
2892                                       0,
2893                                       0};
2894     SVD.push_back(D);
2895   }
2896 
2897   // Minimal header size (left redzone) is 4 pointers,
2898   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2899   size_t Granularity = 1ULL << Mapping.Scale;
2900   size_t MinHeaderSize = std::max((size_t)ASan.LongSize / 2, Granularity);
2901   const ASanStackFrameLayout &L =
2902       ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
2903 
2904   // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2905   DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2906   for (auto &Desc : SVD)
2907     AllocaToSVDMap[Desc.AI] = &Desc;
2908 
2909   // Update SVD with information from lifetime intrinsics.
2910   for (const auto &APC : StaticAllocaPoisonCallVec) {
2911     assert(APC.InsBefore);
2912     assert(APC.AI);
2913     assert(ASan.isInterestingAlloca(*APC.AI));
2914     assert(APC.AI->isStaticAlloca());
2915 
2916     ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2917     Desc.LifetimeSize = Desc.Size;
2918     if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2919       if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2920         if (LifetimeLoc->getFile() == FnLoc->getFile())
2921           if (unsigned Line = LifetimeLoc->getLine())
2922             Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2923       }
2924     }
2925   }
2926 
2927   auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2928   LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
2929   uint64_t LocalStackSize = L.FrameSize;
2930   bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2931                        LocalStackSize <= kMaxStackMallocSize;
2932   bool DoDynamicAlloca = ClDynamicAllocaStack;
2933   // Don't do dynamic alloca or stack malloc if:
2934   // 1) There is inline asm: too often it makes assumptions on which registers
2935   //    are available.
2936   // 2) There is a returns_twice call (typically setjmp), which is
2937   //    optimization-hostile, and doesn't play well with introduced indirect
2938   //    register-relative calculation of local variable addresses.
2939   DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2940   DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2941 
2942   Value *StaticAlloca =
2943       DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2944 
2945   Value *FakeStack;
2946   Value *LocalStackBase;
2947   Value *LocalStackBaseAlloca;
2948   bool Deref;
2949 
2950   if (DoStackMalloc) {
2951     LocalStackBaseAlloca =
2952         IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
2953     // void *FakeStack = __asan_option_detect_stack_use_after_return
2954     //     ? __asan_stack_malloc_N(LocalStackSize)
2955     //     : nullptr;
2956     // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
2957     Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2958         kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2959     Value *UseAfterReturnIsEnabled =
2960         IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
2961                          Constant::getNullValue(IRB.getInt32Ty()));
2962     Instruction *Term =
2963         SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
2964     IRBuilder<> IRBIf(Term);
2965     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2966     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2967     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2968     Value *FakeStackValue =
2969         IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2970                          ConstantInt::get(IntptrTy, LocalStackSize));
2971     IRB.SetInsertPoint(InsBefore);
2972     IRB.SetCurrentDebugLocation(EntryDebugLocation);
2973     FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
2974                           ConstantInt::get(IntptrTy, 0));
2975 
2976     Value *NoFakeStack =
2977         IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2978     Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2979     IRBIf.SetInsertPoint(Term);
2980     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2981     Value *AllocaValue =
2982         DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2983 
2984     IRB.SetInsertPoint(InsBefore);
2985     IRB.SetCurrentDebugLocation(EntryDebugLocation);
2986     LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2987     IRB.SetCurrentDebugLocation(EntryDebugLocation);
2988     IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
2989     Deref = true;
2990   } else {
2991     // void *FakeStack = nullptr;
2992     // void *LocalStackBase = alloca(LocalStackSize);
2993     FakeStack = ConstantInt::get(IntptrTy, 0);
2994     LocalStackBase =
2995         DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
2996     LocalStackBaseAlloca = LocalStackBase;
2997     Deref = false;
2998   }
2999 
3000   // Replace Alloca instructions with base+offset.
3001   for (const auto &Desc : SVD) {
3002     AllocaInst *AI = Desc.AI;
3003     replaceDbgDeclareForAlloca(AI, LocalStackBaseAlloca, DIB, Deref,
3004                                Desc.Offset, DIExpression::NoDeref);
3005     Value *NewAllocaPtr = IRB.CreateIntToPtr(
3006         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
3007         AI->getType());
3008     AI->replaceAllUsesWith(NewAllocaPtr);
3009   }
3010 
3011   // The left-most redzone has enough space for at least 4 pointers.
3012   // Write the Magic value to redzone[0].
3013   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
3014   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
3015                   BasePlus0);
3016   // Write the frame description constant to redzone[1].
3017   Value *BasePlus1 = IRB.CreateIntToPtr(
3018       IRB.CreateAdd(LocalStackBase,
3019                     ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
3020       IntptrPtrTy);
3021   GlobalVariable *StackDescriptionGlobal =
3022       createPrivateGlobalForString(*F.getParent(), DescriptionString,
3023                                    /*AllowMerging*/ true);
3024   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
3025   IRB.CreateStore(Description, BasePlus1);
3026   // Write the PC to redzone[2].
3027   Value *BasePlus2 = IRB.CreateIntToPtr(
3028       IRB.CreateAdd(LocalStackBase,
3029                     ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
3030       IntptrPtrTy);
3031   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
3032 
3033   const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
3034 
3035   // Poison the stack red zones at the entry.
3036   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
3037   // As mask we must use most poisoned case: red zones and after scope.
3038   // As bytes we can use either the same or just red zones only.
3039   copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3040 
3041   if (!StaticAllocaPoisonCallVec.empty()) {
3042     const auto &ShadowInScope = GetShadowBytes(SVD, L);
3043 
3044     // Poison static allocas near lifetime intrinsics.
3045     for (const auto &APC : StaticAllocaPoisonCallVec) {
3046       const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3047       assert(Desc.Offset % L.Granularity == 0);
3048       size_t Begin = Desc.Offset / L.Granularity;
3049       size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
3050 
3051       IRBuilder<> IRB(APC.InsBefore);
3052       copyToShadow(ShadowAfterScope,
3053                    APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3054                    IRB, ShadowBase);
3055     }
3056   }
3057 
3058   SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
3059   SmallVector<uint8_t, 64> ShadowAfterReturn;
3060 
3061   // (Un)poison the stack before all ret instructions.
3062   for (auto Ret : RetVec) {
3063     IRBuilder<> IRBRet(Ret);
3064     // Mark the current frame as retired.
3065     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3066                        BasePlus0);
3067     if (DoStackMalloc) {
3068       assert(StackMallocIdx >= 0);
3069       // if FakeStack != 0  // LocalStackBase == FakeStack
3070       //     // In use-after-return mode, poison the whole stack frame.
3071       //     if StackMallocIdx <= 4
3072       //         // For small sizes inline the whole thing:
3073       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
3074       //         **SavedFlagPtr(FakeStack) = 0
3075       //     else
3076       //         __asan_stack_free_N(FakeStack, LocalStackSize)
3077       // else
3078       //     <This is not a fake stack; unpoison the redzones>
3079       Value *Cmp =
3080           IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
3081       TerminatorInst *ThenTerm, *ElseTerm;
3082       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3083 
3084       IRBuilder<> IRBPoison(ThenTerm);
3085       if (StackMallocIdx <= 4) {
3086         int ClassSize = kMinStackMallocSize << StackMallocIdx;
3087         ShadowAfterReturn.resize(ClassSize / L.Granularity,
3088                                  kAsanStackUseAfterReturnMagic);
3089         copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3090                      ShadowBase);
3091         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
3092             FakeStack,
3093             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3094         Value *SavedFlagPtr = IRBPoison.CreateLoad(
3095             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3096         IRBPoison.CreateStore(
3097             Constant::getNullValue(IRBPoison.getInt8Ty()),
3098             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3099       } else {
3100         // For larger frames call __asan_stack_free_*.
3101         IRBPoison.CreateCall(
3102             AsanStackFreeFunc[StackMallocIdx],
3103             {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
3104       }
3105 
3106       IRBuilder<> IRBElse(ElseTerm);
3107       copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
3108     } else {
3109       copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
3110     }
3111   }
3112 
3113   // We are done. Remove the old unused alloca instructions.
3114   for (auto AI : AllocaVec) AI->eraseFromParent();
3115 }
3116 
3117 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
3118                                          IRBuilder<> &IRB, bool DoPoison) {
3119   // For now just insert the call to ASan runtime.
3120   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3121   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
3122   IRB.CreateCall(
3123       DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3124       {AddrArg, SizeArg});
3125 }
3126 
3127 // Handling llvm.lifetime intrinsics for a given %alloca:
3128 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3129 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3130 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3131 //     could be poisoned by previous llvm.lifetime.end instruction, as the
3132 //     variable may go in and out of scope several times, e.g. in loops).
3133 // (3) if we poisoned at least one %alloca in a function,
3134 //     unpoison the whole stack frame at function exit.
3135 
3136 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
3137   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
3138     // We're interested only in allocas we can handle.
3139     return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
3140   // See if we've already calculated (or started to calculate) alloca for a
3141   // given value.
3142   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
3143   if (I != AllocaForValue.end()) return I->second;
3144   // Store 0 while we're calculating alloca for value V to avoid
3145   // infinite recursion if the value references itself.
3146   AllocaForValue[V] = nullptr;
3147   AllocaInst *Res = nullptr;
3148   if (CastInst *CI = dyn_cast<CastInst>(V))
3149     Res = findAllocaForValue(CI->getOperand(0));
3150   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
3151     for (Value *IncValue : PN->incoming_values()) {
3152       // Allow self-referencing phi-nodes.
3153       if (IncValue == PN) continue;
3154       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
3155       // AI for incoming values should exist and should all be equal.
3156       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3157         return nullptr;
3158       Res = IncValueAI;
3159     }
3160   } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3161     Res = findAllocaForValue(EP->getPointerOperand());
3162   } else {
3163     LLVM_DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V
3164                       << "\n");
3165   }
3166   if (Res) AllocaForValue[V] = Res;
3167   return Res;
3168 }
3169 
3170 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
3171   IRBuilder<> IRB(AI);
3172 
3173   const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
3174   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3175 
3176   Value *Zero = Constant::getNullValue(IntptrTy);
3177   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3178   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
3179 
3180   // Since we need to extend alloca with additional memory to locate
3181   // redzones, and OldSize is number of allocated blocks with
3182   // ElementSize size, get allocated memory size in bytes by
3183   // OldSize * ElementSize.
3184   const unsigned ElementSize =
3185       F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
3186   Value *OldSize =
3187       IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3188                     ConstantInt::get(IntptrTy, ElementSize));
3189 
3190   // PartialSize = OldSize % 32
3191   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3192 
3193   // Misalign = kAllocaRzSize - PartialSize;
3194   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3195 
3196   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3197   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3198   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3199 
3200   // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
3201   // Align is added to locate left redzone, PartialPadding for possible
3202   // partial redzone and kAllocaRzSize for right redzone respectively.
3203   Value *AdditionalChunkSize = IRB.CreateAdd(
3204       ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
3205 
3206   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3207 
3208   // Insert new alloca with new NewSize and Align params.
3209   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3210   NewAlloca->setAlignment(Align);
3211 
3212   // NewAddress = Address + Align
3213   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3214                                     ConstantInt::get(IntptrTy, Align));
3215 
3216   // Insert __asan_alloca_poison call for new created alloca.
3217   IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
3218 
3219   // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3220   // for unpoisoning stuff.
3221   IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3222 
3223   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3224 
3225   // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
3226   AI->replaceAllUsesWith(NewAddressPtr);
3227 
3228   // We are done. Erase old alloca from parent.
3229   AI->eraseFromParent();
3230 }
3231 
3232 // isSafeAccess returns true if Addr is always inbounds with respect to its
3233 // base object. For example, it is a field access or an array access with
3234 // constant inbounds index.
3235 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3236                                     Value *Addr, uint64_t TypeSize) const {
3237   SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3238   if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
3239   uint64_t Size = SizeOffset.first.getZExtValue();
3240   int64_t Offset = SizeOffset.second.getSExtValue();
3241   // Three checks are required to ensure safety:
3242   // . Offset >= 0  (since the offset is given from the base ptr)
3243   // . Size >= Offset  (unsigned)
3244   // . Size - Offset >= NeededSize  (unsigned)
3245   return Offset >= 0 && Size >= uint64_t(Offset) &&
3246          Size - uint64_t(Offset) >= TypeSize / 8;
3247 }
3248