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