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