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