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