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