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