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