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 =
2085       Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
2086                        GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
2087   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
2088 
2089   return ReturnInst::Create(*C, AsanDtorBB);
2090 }
2091 
2092 void ModuleAddressSanitizer::InstrumentGlobalsCOFF(
2093     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2094     ArrayRef<Constant *> MetadataInitializers) {
2095   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2096   auto &DL = M.getDataLayout();
2097 
2098   SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2099   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2100     Constant *Initializer = MetadataInitializers[i];
2101     GlobalVariable *G = ExtendedGlobals[i];
2102     GlobalVariable *Metadata =
2103         CreateMetadataGlobal(M, Initializer, G->getName());
2104     MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2105     Metadata->setMetadata(LLVMContext::MD_associated, MD);
2106     MetadataGlobals[i] = Metadata;
2107 
2108     // The MSVC linker always inserts padding when linking incrementally. We
2109     // cope with that by aligning each struct to its size, which must be a power
2110     // of two.
2111     unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
2112     assert(isPowerOf2_32(SizeOfGlobalStruct) &&
2113            "global metadata will not be padded appropriately");
2114     Metadata->setAlignment(assumeAligned(SizeOfGlobalStruct));
2115 
2116     SetComdatForGlobalMetadata(G, Metadata, "");
2117   }
2118 
2119   // Update llvm.compiler.used, adding the new metadata globals. This is
2120   // needed so that during LTO these variables stay alive.
2121   if (!MetadataGlobals.empty())
2122     appendToCompilerUsed(M, MetadataGlobals);
2123 }
2124 
2125 void ModuleAddressSanitizer::InstrumentGlobalsELF(
2126     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2127     ArrayRef<Constant *> MetadataInitializers,
2128     const std::string &UniqueModuleId) {
2129   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2130 
2131   // Putting globals in a comdat changes the semantic and potentially cause
2132   // false negative odr violations at link time. If odr indicators are used, we
2133   // keep the comdat sections, as link time odr violations will be dectected on
2134   // the odr indicator symbols.
2135   bool UseComdatForGlobalsGC = UseOdrIndicator;
2136 
2137   SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2138   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2139     GlobalVariable *G = ExtendedGlobals[i];
2140     GlobalVariable *Metadata =
2141         CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
2142     MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2143     Metadata->setMetadata(LLVMContext::MD_associated, MD);
2144     MetadataGlobals[i] = Metadata;
2145 
2146     if (UseComdatForGlobalsGC)
2147       SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
2148   }
2149 
2150   // Update llvm.compiler.used, adding the new metadata globals. This is
2151   // needed so that during LTO these variables stay alive.
2152   if (!MetadataGlobals.empty())
2153     appendToCompilerUsed(M, MetadataGlobals);
2154 
2155   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2156   // to look up the loaded image that contains it. Second, we can store in it
2157   // whether registration has already occurred, to prevent duplicate
2158   // registration.
2159   //
2160   // Common linkage ensures that there is only one global per shared library.
2161   GlobalVariable *RegisteredFlag = new GlobalVariable(
2162       M, IntptrTy, false, GlobalVariable::CommonLinkage,
2163       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2164   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2165 
2166   // Create start and stop symbols.
2167   GlobalVariable *StartELFMetadata = new GlobalVariable(
2168       M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2169       "__start_" + getGlobalMetadataSection());
2170   StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
2171   GlobalVariable *StopELFMetadata = new GlobalVariable(
2172       M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2173       "__stop_" + getGlobalMetadataSection());
2174   StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
2175 
2176   // Create a call to register the globals with the runtime.
2177   IRB.CreateCall(AsanRegisterElfGlobals,
2178                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2179                   IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2180                   IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2181 
2182   // We also need to unregister globals at the end, e.g., when a shared library
2183   // gets closed.
2184   if (DestructorKind != AsanDtorKind::None) {
2185     IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2186     IrbDtor.CreateCall(AsanUnregisterElfGlobals,
2187                        {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2188                         IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2189                         IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2190   }
2191 }
2192 
2193 void ModuleAddressSanitizer::InstrumentGlobalsMachO(
2194     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2195     ArrayRef<Constant *> MetadataInitializers) {
2196   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2197 
2198   // On recent Mach-O platforms, use a structure which binds the liveness of
2199   // the global variable to the metadata struct. Keep the list of "Liveness" GV
2200   // created to be added to llvm.compiler.used
2201   StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
2202   SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
2203 
2204   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2205     Constant *Initializer = MetadataInitializers[i];
2206     GlobalVariable *G = ExtendedGlobals[i];
2207     GlobalVariable *Metadata =
2208         CreateMetadataGlobal(M, Initializer, G->getName());
2209 
2210     // On recent Mach-O platforms, we emit the global metadata in a way that
2211     // allows the linker to properly strip dead globals.
2212     auto LivenessBinder =
2213         ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
2214                             ConstantExpr::getPointerCast(Metadata, IntptrTy));
2215     GlobalVariable *Liveness = new GlobalVariable(
2216         M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
2217         Twine("__asan_binder_") + G->getName());
2218     Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
2219     LivenessGlobals[i] = Liveness;
2220   }
2221 
2222   // Update llvm.compiler.used, adding the new liveness globals. This is
2223   // needed so that during LTO these variables stay alive. The alternative
2224   // would be to have the linker handling the LTO symbols, but libLTO
2225   // current API does not expose access to the section for each symbol.
2226   if (!LivenessGlobals.empty())
2227     appendToCompilerUsed(M, LivenessGlobals);
2228 
2229   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2230   // to look up the loaded image that contains it. Second, we can store in it
2231   // whether registration has already occurred, to prevent duplicate
2232   // registration.
2233   //
2234   // common linkage ensures that there is only one global per shared library.
2235   GlobalVariable *RegisteredFlag = new GlobalVariable(
2236       M, IntptrTy, false, GlobalVariable::CommonLinkage,
2237       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2238   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2239 
2240   IRB.CreateCall(AsanRegisterImageGlobals,
2241                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2242 
2243   // We also need to unregister globals at the end, e.g., when a shared library
2244   // gets closed.
2245   if (DestructorKind != AsanDtorKind::None) {
2246     IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2247     IrbDtor.CreateCall(AsanUnregisterImageGlobals,
2248                        {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2249   }
2250 }
2251 
2252 void ModuleAddressSanitizer::InstrumentGlobalsWithMetadataArray(
2253     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2254     ArrayRef<Constant *> MetadataInitializers) {
2255   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2256   unsigned N = ExtendedGlobals.size();
2257   assert(N > 0);
2258 
2259   // On platforms that don't have a custom metadata section, we emit an array
2260   // of global metadata structures.
2261   ArrayType *ArrayOfGlobalStructTy =
2262       ArrayType::get(MetadataInitializers[0]->getType(), N);
2263   auto AllGlobals = new GlobalVariable(
2264       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
2265       ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
2266   if (Mapping.Scale > 3)
2267     AllGlobals->setAlignment(Align(1ULL << Mapping.Scale));
2268 
2269   IRB.CreateCall(AsanRegisterGlobals,
2270                  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2271                   ConstantInt::get(IntptrTy, N)});
2272 
2273   // We also need to unregister globals at the end, e.g., when a shared library
2274   // gets closed.
2275   if (DestructorKind != AsanDtorKind::None) {
2276     IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2277     IrbDtor.CreateCall(AsanUnregisterGlobals,
2278                        {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2279                         ConstantInt::get(IntptrTy, N)});
2280   }
2281 }
2282 
2283 // This function replaces all global variables with new variables that have
2284 // trailing redzones. It also creates a function that poisons
2285 // redzones and inserts this function into llvm.global_ctors.
2286 // Sets *CtorComdat to true if the global registration code emitted into the
2287 // asan constructor is comdat-compatible.
2288 bool ModuleAddressSanitizer::InstrumentGlobals(IRBuilder<> &IRB, Module &M,
2289                                                bool *CtorComdat) {
2290   *CtorComdat = false;
2291 
2292   // Build set of globals that are aliased by some GA, where
2293   // getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.
2294   SmallPtrSet<const GlobalVariable *, 16> AliasedGlobalExclusions;
2295   if (CompileKernel) {
2296     for (auto &GA : M.aliases()) {
2297       if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))
2298         AliasedGlobalExclusions.insert(GV);
2299     }
2300   }
2301 
2302   SmallVector<GlobalVariable *, 16> GlobalsToChange;
2303   for (auto &G : M.globals()) {
2304     if (!AliasedGlobalExclusions.count(&G) && shouldInstrumentGlobal(&G))
2305       GlobalsToChange.push_back(&G);
2306   }
2307 
2308   size_t n = GlobalsToChange.size();
2309   if (n == 0) {
2310     *CtorComdat = true;
2311     return false;
2312   }
2313 
2314   auto &DL = M.getDataLayout();
2315 
2316   // A global is described by a structure
2317   //   size_t beg;
2318   //   size_t size;
2319   //   size_t size_with_redzone;
2320   //   const char *name;
2321   //   const char *module_name;
2322   //   size_t has_dynamic_init;
2323   //   void *source_location;
2324   //   size_t odr_indicator;
2325   // We initialize an array of such structures and pass it to a run-time call.
2326   StructType *GlobalStructTy =
2327       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
2328                       IntptrTy, IntptrTy, IntptrTy);
2329   SmallVector<GlobalVariable *, 16> NewGlobals(n);
2330   SmallVector<Constant *, 16> Initializers(n);
2331 
2332   bool HasDynamicallyInitializedGlobals = false;
2333 
2334   // We shouldn't merge same module names, as this string serves as unique
2335   // module ID in runtime.
2336   GlobalVariable *ModuleName = createPrivateGlobalForString(
2337       M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
2338 
2339   for (size_t i = 0; i < n; i++) {
2340     GlobalVariable *G = GlobalsToChange[i];
2341 
2342     // FIXME: Metadata should be attched directly to the global directly instead
2343     // of being added to llvm.asan.globals.
2344     auto MD = GlobalsMD.get(G);
2345     StringRef NameForGlobal = G->getName();
2346     // Create string holding the global name (use global name from metadata
2347     // if it's available, otherwise just write the name of global variable).
2348     GlobalVariable *Name = createPrivateGlobalForString(
2349         M, MD.Name.empty() ? NameForGlobal : MD.Name,
2350         /*AllowMerging*/ true, kAsanGenPrefix);
2351 
2352     Type *Ty = G->getValueType();
2353     const uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
2354     const uint64_t RightRedzoneSize = getRedzoneSizeForGlobal(SizeInBytes);
2355     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2356 
2357     StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2358     Constant *NewInitializer = ConstantStruct::get(
2359         NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
2360 
2361     // Create a new global variable with enough space for a redzone.
2362     GlobalValue::LinkageTypes Linkage = G->getLinkage();
2363     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2364       Linkage = GlobalValue::InternalLinkage;
2365     GlobalVariable *NewGlobal =
2366         new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2367                            "", G, G->getThreadLocalMode());
2368     NewGlobal->copyAttributesFrom(G);
2369     NewGlobal->setComdat(G->getComdat());
2370     NewGlobal->setAlignment(MaybeAlign(getMinRedzoneSizeForGlobal()));
2371     // Don't fold globals with redzones. ODR violation detector and redzone
2372     // poisoning implicitly creates a dependence on the global's address, so it
2373     // is no longer valid for it to be marked unnamed_addr.
2374     NewGlobal->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
2375 
2376     // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2377     if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2378         G->isConstant()) {
2379       auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2380       if (Seq && Seq->isCString())
2381         NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2382     }
2383 
2384     // Transfer the debug info and type metadata.  The payload starts at offset
2385     // zero so we can copy the metadata over as is.
2386     NewGlobal->copyMetadata(G, 0);
2387 
2388     Value *Indices2[2];
2389     Indices2[0] = IRB.getInt32(0);
2390     Indices2[1] = IRB.getInt32(0);
2391 
2392     G->replaceAllUsesWith(
2393         ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
2394     NewGlobal->takeName(G);
2395     G->eraseFromParent();
2396     NewGlobals[i] = NewGlobal;
2397 
2398     Constant *SourceLoc;
2399     if (!MD.SourceLoc.empty()) {
2400       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2401       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2402     } else {
2403       SourceLoc = ConstantInt::get(IntptrTy, 0);
2404     }
2405 
2406     Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2407     GlobalValue *InstrumentedGlobal = NewGlobal;
2408 
2409     bool CanUsePrivateAliases =
2410         TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2411         TargetTriple.isOSBinFormatWasm();
2412     if (CanUsePrivateAliases && UsePrivateAlias) {
2413       // Create local alias for NewGlobal to avoid crash on ODR between
2414       // instrumented and non-instrumented libraries.
2415       InstrumentedGlobal =
2416           GlobalAlias::create(GlobalValue::PrivateLinkage, "", NewGlobal);
2417     }
2418 
2419     // ODR should not happen for local linkage.
2420     if (NewGlobal->hasLocalLinkage()) {
2421       ODRIndicator = ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, -1),
2422                                                IRB.getInt8PtrTy());
2423     } else if (UseOdrIndicator) {
2424       // With local aliases, we need to provide another externally visible
2425       // symbol __odr_asan_XXX to detect ODR violation.
2426       auto *ODRIndicatorSym =
2427           new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2428                              Constant::getNullValue(IRB.getInt8Ty()),
2429                              kODRGenPrefix + NameForGlobal, nullptr,
2430                              NewGlobal->getThreadLocalMode());
2431 
2432       // Set meaningful attributes for indicator symbol.
2433       ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2434       ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2435       ODRIndicatorSym->setAlignment(Align(1));
2436       ODRIndicator = ODRIndicatorSym;
2437     }
2438 
2439     Constant *Initializer = ConstantStruct::get(
2440         GlobalStructTy,
2441         ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
2442         ConstantInt::get(IntptrTy, SizeInBytes),
2443         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2444         ConstantExpr::getPointerCast(Name, IntptrTy),
2445         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
2446         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
2447         ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
2448 
2449     if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
2450 
2451     LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
2452 
2453     Initializers[i] = Initializer;
2454   }
2455 
2456   // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2457   // ConstantMerge'ing them.
2458   SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2459   for (size_t i = 0; i < n; i++) {
2460     GlobalVariable *G = NewGlobals[i];
2461     if (G->getName().empty()) continue;
2462     GlobalsToAddToUsedList.push_back(G);
2463   }
2464   appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2465 
2466   std::string ELFUniqueModuleId =
2467       (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2468                                                         : "";
2469 
2470   if (!ELFUniqueModuleId.empty()) {
2471     InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2472     *CtorComdat = true;
2473   } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
2474     InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2475   } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2476     InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2477   } else {
2478     InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2479   }
2480 
2481   // Create calls for poisoning before initializers run and unpoisoning after.
2482   if (HasDynamicallyInitializedGlobals)
2483     createInitializerPoisonCalls(M, ModuleName);
2484 
2485   LLVM_DEBUG(dbgs() << M);
2486   return true;
2487 }
2488 
2489 uint64_t
2490 ModuleAddressSanitizer::getRedzoneSizeForGlobal(uint64_t SizeInBytes) const {
2491   constexpr uint64_t kMaxRZ = 1 << 18;
2492   const uint64_t MinRZ = getMinRedzoneSizeForGlobal();
2493 
2494   // Calculate RZ, where MinRZ <= RZ <= MaxRZ, and RZ ~ 1/4 * SizeInBytes.
2495   uint64_t RZ =
2496       std::max(MinRZ, std::min(kMaxRZ, (SizeInBytes / MinRZ / 4) * MinRZ));
2497 
2498   // Round up to multiple of MinRZ.
2499   if (SizeInBytes % MinRZ)
2500     RZ += MinRZ - (SizeInBytes % MinRZ);
2501   assert((RZ + SizeInBytes) % MinRZ == 0);
2502 
2503   return RZ;
2504 }
2505 
2506 int ModuleAddressSanitizer::GetAsanVersion(const Module &M) const {
2507   int LongSize = M.getDataLayout().getPointerSizeInBits();
2508   bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2509   int Version = 8;
2510   // 32-bit Android is one version ahead because of the switch to dynamic
2511   // shadow.
2512   Version += (LongSize == 32 && isAndroid);
2513   return Version;
2514 }
2515 
2516 bool ModuleAddressSanitizer::instrumentModule(Module &M) {
2517   initializeCallbacks(M);
2518 
2519   // Create a module constructor. A destructor is created lazily because not all
2520   // platforms, and not all modules need it.
2521   if (CompileKernel) {
2522     // The kernel always builds with its own runtime, and therefore does not
2523     // need the init and version check calls.
2524     AsanCtorFunction = createSanitizerCtor(M, kAsanModuleCtorName);
2525   } else {
2526     std::string AsanVersion = std::to_string(GetAsanVersion(M));
2527     std::string VersionCheckName =
2528         ClInsertVersionCheck ? (kAsanVersionCheckNamePrefix + AsanVersion) : "";
2529     std::tie(AsanCtorFunction, std::ignore) =
2530         createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName,
2531                                             kAsanInitName, /*InitArgTypes=*/{},
2532                                             /*InitArgs=*/{}, VersionCheckName);
2533   }
2534 
2535   bool CtorComdat = true;
2536   if (ClGlobals) {
2537     IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2538     InstrumentGlobals(IRB, M, &CtorComdat);
2539   }
2540 
2541   const uint64_t Priority = GetCtorAndDtorPriority(TargetTriple);
2542 
2543   // Put the constructor and destructor in comdat if both
2544   // (1) global instrumentation is not TU-specific
2545   // (2) target is ELF.
2546   if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2547     AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2548     appendToGlobalCtors(M, AsanCtorFunction, Priority, AsanCtorFunction);
2549     if (AsanDtorFunction) {
2550       AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2551       appendToGlobalDtors(M, AsanDtorFunction, Priority, AsanDtorFunction);
2552     }
2553   } else {
2554     appendToGlobalCtors(M, AsanCtorFunction, Priority);
2555     if (AsanDtorFunction)
2556       appendToGlobalDtors(M, AsanDtorFunction, Priority);
2557   }
2558 
2559   return true;
2560 }
2561 
2562 void AddressSanitizer::initializeCallbacks(Module &M) {
2563   IRBuilder<> IRB(*C);
2564   // Create __asan_report* callbacks.
2565   // IsWrite, TypeSize and Exp are encoded in the function name.
2566   for (int Exp = 0; Exp < 2; Exp++) {
2567     for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2568       const std::string TypeStr = AccessIsWrite ? "store" : "load";
2569       const std::string ExpStr = Exp ? "exp_" : "";
2570       const std::string EndingStr = Recover ? "_noabort" : "";
2571 
2572       SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2573       SmallVector<Type *, 2> Args1{1, IntptrTy};
2574       if (Exp) {
2575         Type *ExpType = Type::getInt32Ty(*C);
2576         Args2.push_back(ExpType);
2577         Args1.push_back(ExpType);
2578       }
2579       AsanErrorCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2580           kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
2581           FunctionType::get(IRB.getVoidTy(), Args2, false));
2582 
2583       AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2584           ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2585           FunctionType::get(IRB.getVoidTy(), Args2, false));
2586 
2587       for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2588            AccessSizeIndex++) {
2589         const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2590         AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2591             M.getOrInsertFunction(
2592                 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2593                 FunctionType::get(IRB.getVoidTy(), Args1, false));
2594 
2595         AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2596             M.getOrInsertFunction(
2597                 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2598                 FunctionType::get(IRB.getVoidTy(), Args1, false));
2599       }
2600     }
2601   }
2602 
2603   const std::string MemIntrinCallbackPrefix =
2604       CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
2605   AsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",
2606                                       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2607                                       IRB.getInt8PtrTy(), IntptrTy);
2608   AsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy",
2609                                      IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2610                                      IRB.getInt8PtrTy(), IntptrTy);
2611   AsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",
2612                                      IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2613                                      IRB.getInt32Ty(), IntptrTy);
2614 
2615   AsanHandleNoReturnFunc =
2616       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy());
2617 
2618   AsanPtrCmpFunction =
2619       M.getOrInsertFunction(kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy);
2620   AsanPtrSubFunction =
2621       M.getOrInsertFunction(kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy);
2622   if (Mapping.InGlobal)
2623     AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2624                                            ArrayType::get(IRB.getInt8Ty(), 0));
2625 }
2626 
2627 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2628   // For each NSObject descendant having a +load method, this method is invoked
2629   // by the ObjC runtime before any of the static constructors is called.
2630   // Therefore we need to instrument such methods with a call to __asan_init
2631   // at the beginning in order to initialize our runtime before any access to
2632   // the shadow memory.
2633   // We cannot just ignore these methods, because they may call other
2634   // instrumented functions.
2635   if (F.getName().find(" load]") != std::string::npos) {
2636     FunctionCallee AsanInitFunction =
2637         declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
2638     IRBuilder<> IRB(&F.front(), F.front().begin());
2639     IRB.CreateCall(AsanInitFunction, {});
2640     return true;
2641   }
2642   return false;
2643 }
2644 
2645 bool AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2646   // Generate code only when dynamic addressing is needed.
2647   if (Mapping.Offset != kDynamicShadowSentinel)
2648     return false;
2649 
2650   IRBuilder<> IRB(&F.front().front());
2651   if (Mapping.InGlobal) {
2652     if (ClWithIfuncSuppressRemat) {
2653       // An empty inline asm with input reg == output reg.
2654       // An opaque pointer-to-int cast, basically.
2655       InlineAsm *Asm = InlineAsm::get(
2656           FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2657           StringRef(""), StringRef("=r,0"),
2658           /*hasSideEffects=*/false);
2659       LocalDynamicShadow =
2660           IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2661     } else {
2662       LocalDynamicShadow =
2663           IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2664     }
2665   } else {
2666     Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2667         kAsanShadowMemoryDynamicAddress, IntptrTy);
2668     LocalDynamicShadow = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);
2669   }
2670   return true;
2671 }
2672 
2673 void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2674   // Find the one possible call to llvm.localescape and pre-mark allocas passed
2675   // to it as uninteresting. This assumes we haven't started processing allocas
2676   // yet. This check is done up front because iterating the use list in
2677   // isInterestingAlloca would be algorithmically slower.
2678   assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2679 
2680   // Try to get the declaration of llvm.localescape. If it's not in the module,
2681   // we can exit early.
2682   if (!F.getParent()->getFunction("llvm.localescape")) return;
2683 
2684   // Look for a call to llvm.localescape call in the entry block. It can't be in
2685   // any other block.
2686   for (Instruction &I : F.getEntryBlock()) {
2687     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2688     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2689       // We found a call. Mark all the allocas passed in as uninteresting.
2690       for (Value *Arg : II->arg_operands()) {
2691         AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2692         assert(AI && AI->isStaticAlloca() &&
2693                "non-static alloca arg to localescape");
2694         ProcessedAllocas[AI] = false;
2695       }
2696       break;
2697     }
2698   }
2699 }
2700 
2701 bool AddressSanitizer::suppressInstrumentationSiteForDebug(int &Instrumented) {
2702   bool ShouldInstrument =
2703       ClDebugMin < 0 || ClDebugMax < 0 ||
2704       (Instrumented >= ClDebugMin && Instrumented <= ClDebugMax);
2705   Instrumented++;
2706   return !ShouldInstrument;
2707 }
2708 
2709 bool AddressSanitizer::instrumentFunction(Function &F,
2710                                           const TargetLibraryInfo *TLI) {
2711   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2712   if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2713   if (F.getName().startswith("__asan_")) return false;
2714 
2715   bool FunctionModified = false;
2716 
2717   // If needed, insert __asan_init before checking for SanitizeAddress attr.
2718   // This function needs to be called even if the function body is not
2719   // instrumented.
2720   if (maybeInsertAsanInitAtFunctionEntry(F))
2721     FunctionModified = true;
2722 
2723   // Leave if the function doesn't need instrumentation.
2724   if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2725 
2726   LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2727 
2728   initializeCallbacks(*F.getParent());
2729 
2730   FunctionStateRAII CleanupObj(this);
2731 
2732   FunctionModified |= maybeInsertDynamicShadowAtFunctionEntry(F);
2733 
2734   // We can't instrument allocas used with llvm.localescape. Only static allocas
2735   // can be passed to that intrinsic.
2736   markEscapedLocalAllocas(F);
2737 
2738   // We want to instrument every address only once per basic block (unless there
2739   // are calls between uses).
2740   SmallPtrSet<Value *, 16> TempsToInstrument;
2741   SmallVector<InterestingMemoryOperand, 16> OperandsToInstrument;
2742   SmallVector<MemIntrinsic *, 16> IntrinToInstrument;
2743   SmallVector<Instruction *, 8> NoReturnCalls;
2744   SmallVector<BasicBlock *, 16> AllBlocks;
2745   SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2746   int NumAllocas = 0;
2747 
2748   // Fill the set of memory operations to instrument.
2749   for (auto &BB : F) {
2750     AllBlocks.push_back(&BB);
2751     TempsToInstrument.clear();
2752     int NumInsnsPerBB = 0;
2753     for (auto &Inst : BB) {
2754       if (LooksLikeCodeInBug11395(&Inst)) return false;
2755       SmallVector<InterestingMemoryOperand, 1> InterestingOperands;
2756       getInterestingMemoryOperands(&Inst, InterestingOperands);
2757 
2758       if (!InterestingOperands.empty()) {
2759         for (auto &Operand : InterestingOperands) {
2760           if (ClOpt && ClOptSameTemp) {
2761             Value *Ptr = Operand.getPtr();
2762             // If we have a mask, skip instrumentation if we've already
2763             // instrumented the full object. But don't add to TempsToInstrument
2764             // because we might get another load/store with a different mask.
2765             if (Operand.MaybeMask) {
2766               if (TempsToInstrument.count(Ptr))
2767                 continue; // We've seen this (whole) temp in the current BB.
2768             } else {
2769               if (!TempsToInstrument.insert(Ptr).second)
2770                 continue; // We've seen this temp in the current BB.
2771             }
2772           }
2773           OperandsToInstrument.push_back(Operand);
2774           NumInsnsPerBB++;
2775         }
2776       } else if (((ClInvalidPointerPairs || ClInvalidPointerCmp) &&
2777                   isInterestingPointerComparison(&Inst)) ||
2778                  ((ClInvalidPointerPairs || ClInvalidPointerSub) &&
2779                   isInterestingPointerSubtraction(&Inst))) {
2780         PointerComparisonsOrSubtracts.push_back(&Inst);
2781       } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst)) {
2782         // ok, take it.
2783         IntrinToInstrument.push_back(MI);
2784         NumInsnsPerBB++;
2785       } else {
2786         if (isa<AllocaInst>(Inst)) NumAllocas++;
2787         if (auto *CB = dyn_cast<CallBase>(&Inst)) {
2788           // A call inside BB.
2789           TempsToInstrument.clear();
2790           if (CB->doesNotReturn() && !CB->hasMetadata("nosanitize"))
2791             NoReturnCalls.push_back(CB);
2792         }
2793         if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2794           maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
2795       }
2796       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
2797     }
2798   }
2799 
2800   bool UseCalls = (ClInstrumentationWithCallsThreshold >= 0 &&
2801                    OperandsToInstrument.size() + IntrinToInstrument.size() >
2802                        (unsigned)ClInstrumentationWithCallsThreshold);
2803   const DataLayout &DL = F.getParent()->getDataLayout();
2804   ObjectSizeOpts ObjSizeOpts;
2805   ObjSizeOpts.RoundToAlign = true;
2806   ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
2807 
2808   // Instrument.
2809   int NumInstrumented = 0;
2810   for (auto &Operand : OperandsToInstrument) {
2811     if (!suppressInstrumentationSiteForDebug(NumInstrumented))
2812       instrumentMop(ObjSizeVis, Operand, UseCalls,
2813                     F.getParent()->getDataLayout());
2814     FunctionModified = true;
2815   }
2816   for (auto Inst : IntrinToInstrument) {
2817     if (!suppressInstrumentationSiteForDebug(NumInstrumented))
2818       instrumentMemIntrinsic(Inst);
2819     FunctionModified = true;
2820   }
2821 
2822   FunctionStackPoisoner FSP(F, *this);
2823   bool ChangedStack = FSP.runOnFunction();
2824 
2825   // We must unpoison the stack before NoReturn calls (throw, _exit, etc).
2826   // See e.g. https://github.com/google/sanitizers/issues/37
2827   for (auto CI : NoReturnCalls) {
2828     IRBuilder<> IRB(CI);
2829     IRB.CreateCall(AsanHandleNoReturnFunc, {});
2830   }
2831 
2832   for (auto Inst : PointerComparisonsOrSubtracts) {
2833     instrumentPointerComparisonOrSubtraction(Inst);
2834     FunctionModified = true;
2835   }
2836 
2837   if (ChangedStack || !NoReturnCalls.empty())
2838     FunctionModified = true;
2839 
2840   LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2841                     << F << "\n");
2842 
2843   return FunctionModified;
2844 }
2845 
2846 // Workaround for bug 11395: we don't want to instrument stack in functions
2847 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2848 // FIXME: remove once the bug 11395 is fixed.
2849 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2850   if (LongSize != 32) return false;
2851   CallInst *CI = dyn_cast<CallInst>(I);
2852   if (!CI || !CI->isInlineAsm()) return false;
2853   if (CI->getNumArgOperands() <= 5) return false;
2854   // We have inline assembly with quite a few arguments.
2855   return true;
2856 }
2857 
2858 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2859   IRBuilder<> IRB(*C);
2860   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2861     std::string Suffix = itostr(i);
2862     AsanStackMallocFunc[i] = M.getOrInsertFunction(
2863         kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy);
2864     AsanStackFreeFunc[i] =
2865         M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2866                               IRB.getVoidTy(), IntptrTy, IntptrTy);
2867   }
2868   if (ASan.UseAfterScope) {
2869     AsanPoisonStackMemoryFunc = M.getOrInsertFunction(
2870         kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2871     AsanUnpoisonStackMemoryFunc = M.getOrInsertFunction(
2872         kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2873   }
2874 
2875   for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2876     std::ostringstream Name;
2877     Name << kAsanSetShadowPrefix;
2878     Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2879     AsanSetShadowFunc[Val] =
2880         M.getOrInsertFunction(Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy);
2881   }
2882 
2883   AsanAllocaPoisonFunc = M.getOrInsertFunction(
2884       kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
2885   AsanAllocasUnpoisonFunc = M.getOrInsertFunction(
2886       kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
2887 }
2888 
2889 void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2890                                                ArrayRef<uint8_t> ShadowBytes,
2891                                                size_t Begin, size_t End,
2892                                                IRBuilder<> &IRB,
2893                                                Value *ShadowBase) {
2894   if (Begin >= End)
2895     return;
2896 
2897   const size_t LargestStoreSizeInBytes =
2898       std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2899 
2900   const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2901 
2902   // Poison given range in shadow using larges store size with out leading and
2903   // trailing zeros in ShadowMask. Zeros never change, so they need neither
2904   // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2905   // middle of a store.
2906   for (size_t i = Begin; i < End;) {
2907     if (!ShadowMask[i]) {
2908       assert(!ShadowBytes[i]);
2909       ++i;
2910       continue;
2911     }
2912 
2913     size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2914     // Fit store size into the range.
2915     while (StoreSizeInBytes > End - i)
2916       StoreSizeInBytes /= 2;
2917 
2918     // Minimize store size by trimming trailing zeros.
2919     for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2920       while (j <= StoreSizeInBytes / 2)
2921         StoreSizeInBytes /= 2;
2922     }
2923 
2924     uint64_t Val = 0;
2925     for (size_t j = 0; j < StoreSizeInBytes; j++) {
2926       if (IsLittleEndian)
2927         Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2928       else
2929         Val = (Val << 8) | ShadowBytes[i + j];
2930     }
2931 
2932     Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2933     Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
2934     IRB.CreateAlignedStore(
2935         Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()),
2936         Align(1));
2937 
2938     i += StoreSizeInBytes;
2939   }
2940 }
2941 
2942 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2943                                          ArrayRef<uint8_t> ShadowBytes,
2944                                          IRBuilder<> &IRB, Value *ShadowBase) {
2945   copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2946 }
2947 
2948 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2949                                          ArrayRef<uint8_t> ShadowBytes,
2950                                          size_t Begin, size_t End,
2951                                          IRBuilder<> &IRB, Value *ShadowBase) {
2952   assert(ShadowMask.size() == ShadowBytes.size());
2953   size_t Done = Begin;
2954   for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2955     if (!ShadowMask[i]) {
2956       assert(!ShadowBytes[i]);
2957       continue;
2958     }
2959     uint8_t Val = ShadowBytes[i];
2960     if (!AsanSetShadowFunc[Val])
2961       continue;
2962 
2963     // Skip same values.
2964     for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
2965     }
2966 
2967     if (j - i >= ClMaxInlinePoisoningSize) {
2968       copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
2969       IRB.CreateCall(AsanSetShadowFunc[Val],
2970                      {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2971                       ConstantInt::get(IntptrTy, j - i)});
2972       Done = j;
2973     }
2974   }
2975 
2976   copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
2977 }
2978 
2979 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
2980 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2981 static int StackMallocSizeClass(uint64_t LocalStackSize) {
2982   assert(LocalStackSize <= kMaxStackMallocSize);
2983   uint64_t MaxSize = kMinStackMallocSize;
2984   for (int i = 0;; i++, MaxSize *= 2)
2985     if (LocalStackSize <= MaxSize) return i;
2986   llvm_unreachable("impossible LocalStackSize");
2987 }
2988 
2989 void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
2990   Instruction *CopyInsertPoint = &F.front().front();
2991   if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2992     // Insert after the dynamic shadow location is determined
2993     CopyInsertPoint = CopyInsertPoint->getNextNode();
2994     assert(CopyInsertPoint);
2995   }
2996   IRBuilder<> IRB(CopyInsertPoint);
2997   const DataLayout &DL = F.getParent()->getDataLayout();
2998   for (Argument &Arg : F.args()) {
2999     if (Arg.hasByValAttr()) {
3000       Type *Ty = Arg.getParamByValType();
3001       const Align Alignment =
3002           DL.getValueOrABITypeAlignment(Arg.getParamAlign(), Ty);
3003 
3004       AllocaInst *AI = IRB.CreateAlloca(
3005           Ty, nullptr,
3006           (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
3007               ".byval");
3008       AI->setAlignment(Alignment);
3009       Arg.replaceAllUsesWith(AI);
3010 
3011       uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3012       IRB.CreateMemCpy(AI, Alignment, &Arg, Alignment, AllocSize);
3013     }
3014   }
3015 }
3016 
3017 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
3018                                           Value *ValueIfTrue,
3019                                           Instruction *ThenTerm,
3020                                           Value *ValueIfFalse) {
3021   PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
3022   BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
3023   PHI->addIncoming(ValueIfFalse, CondBlock);
3024   BasicBlock *ThenBlock = ThenTerm->getParent();
3025   PHI->addIncoming(ValueIfTrue, ThenBlock);
3026   return PHI;
3027 }
3028 
3029 Value *FunctionStackPoisoner::createAllocaForLayout(
3030     IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
3031   AllocaInst *Alloca;
3032   if (Dynamic) {
3033     Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
3034                               ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
3035                               "MyAlloca");
3036   } else {
3037     Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
3038                               nullptr, "MyAlloca");
3039     assert(Alloca->isStaticAlloca());
3040   }
3041   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
3042   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
3043   Alloca->setAlignment(Align(FrameAlignment));
3044   return IRB.CreatePointerCast(Alloca, IntptrTy);
3045 }
3046 
3047 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
3048   BasicBlock &FirstBB = *F.begin();
3049   IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
3050   DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
3051   IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
3052   DynamicAllocaLayout->setAlignment(Align(32));
3053 }
3054 
3055 void FunctionStackPoisoner::processDynamicAllocas() {
3056   if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
3057     assert(DynamicAllocaPoisonCallVec.empty());
3058     return;
3059   }
3060 
3061   // Insert poison calls for lifetime intrinsics for dynamic allocas.
3062   for (const auto &APC : DynamicAllocaPoisonCallVec) {
3063     assert(APC.InsBefore);
3064     assert(APC.AI);
3065     assert(ASan.isInterestingAlloca(*APC.AI));
3066     assert(!APC.AI->isStaticAlloca());
3067 
3068     IRBuilder<> IRB(APC.InsBefore);
3069     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
3070     // Dynamic allocas will be unpoisoned unconditionally below in
3071     // unpoisonDynamicAllocas.
3072     // Flag that we need unpoison static allocas.
3073   }
3074 
3075   // Handle dynamic allocas.
3076   createDynamicAllocasInitStorage();
3077   for (auto &AI : DynamicAllocaVec)
3078     handleDynamicAllocaCall(AI);
3079   unpoisonDynamicAllocas();
3080 }
3081 
3082 /// Collect instructions in the entry block after \p InsBefore which initialize
3083 /// permanent storage for a function argument. These instructions must remain in
3084 /// the entry block so that uninitialized values do not appear in backtraces. An
3085 /// added benefit is that this conserves spill slots. This does not move stores
3086 /// before instrumented / "interesting" allocas.
3087 static void findStoresToUninstrumentedArgAllocas(
3088     AddressSanitizer &ASan, Instruction &InsBefore,
3089     SmallVectorImpl<Instruction *> &InitInsts) {
3090   Instruction *Start = InsBefore.getNextNonDebugInstruction();
3091   for (Instruction *It = Start; It; It = It->getNextNonDebugInstruction()) {
3092     // Argument initialization looks like:
3093     // 1) store <Argument>, <Alloca> OR
3094     // 2) <CastArgument> = cast <Argument> to ...
3095     //    store <CastArgument> to <Alloca>
3096     // Do not consider any other kind of instruction.
3097     //
3098     // Note: This covers all known cases, but may not be exhaustive. An
3099     // alternative to pattern-matching stores is to DFS over all Argument uses:
3100     // this might be more general, but is probably much more complicated.
3101     if (isa<AllocaInst>(It) || isa<CastInst>(It))
3102       continue;
3103     if (auto *Store = dyn_cast<StoreInst>(It)) {
3104       // The store destination must be an alloca that isn't interesting for
3105       // ASan to instrument. These are moved up before InsBefore, and they're
3106       // not interesting because allocas for arguments can be mem2reg'd.
3107       auto *Alloca = dyn_cast<AllocaInst>(Store->getPointerOperand());
3108       if (!Alloca || ASan.isInterestingAlloca(*Alloca))
3109         continue;
3110 
3111       Value *Val = Store->getValueOperand();
3112       bool IsDirectArgInit = isa<Argument>(Val);
3113       bool IsArgInitViaCast =
3114           isa<CastInst>(Val) &&
3115           isa<Argument>(cast<CastInst>(Val)->getOperand(0)) &&
3116           // Check that the cast appears directly before the store. Otherwise
3117           // moving the cast before InsBefore may break the IR.
3118           Val == It->getPrevNonDebugInstruction();
3119       bool IsArgInit = IsDirectArgInit || IsArgInitViaCast;
3120       if (!IsArgInit)
3121         continue;
3122 
3123       if (IsArgInitViaCast)
3124         InitInsts.push_back(cast<Instruction>(Val));
3125       InitInsts.push_back(Store);
3126       continue;
3127     }
3128 
3129     // Do not reorder past unknown instructions: argument initialization should
3130     // only involve casts and stores.
3131     return;
3132   }
3133 }
3134 
3135 void FunctionStackPoisoner::processStaticAllocas() {
3136   if (AllocaVec.empty()) {
3137     assert(StaticAllocaPoisonCallVec.empty());
3138     return;
3139   }
3140 
3141   int StackMallocIdx = -1;
3142   DebugLoc EntryDebugLocation;
3143   if (auto SP = F.getSubprogram())
3144     EntryDebugLocation =
3145         DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
3146 
3147   Instruction *InsBefore = AllocaVec[0];
3148   IRBuilder<> IRB(InsBefore);
3149 
3150   // Make sure non-instrumented allocas stay in the entry block. Otherwise,
3151   // debug info is broken, because only entry-block allocas are treated as
3152   // regular stack slots.
3153   auto InsBeforeB = InsBefore->getParent();
3154   assert(InsBeforeB == &F.getEntryBlock());
3155   for (auto *AI : StaticAllocasToMoveUp)
3156     if (AI->getParent() == InsBeforeB)
3157       AI->moveBefore(InsBefore);
3158 
3159   // Move stores of arguments into entry-block allocas as well. This prevents
3160   // extra stack slots from being generated (to house the argument values until
3161   // they can be stored into the allocas). This also prevents uninitialized
3162   // values from being shown in backtraces.
3163   SmallVector<Instruction *, 8> ArgInitInsts;
3164   findStoresToUninstrumentedArgAllocas(ASan, *InsBefore, ArgInitInsts);
3165   for (Instruction *ArgInitInst : ArgInitInsts)
3166     ArgInitInst->moveBefore(InsBefore);
3167 
3168   // If we have a call to llvm.localescape, keep it in the entry block.
3169   if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
3170 
3171   SmallVector<ASanStackVariableDescription, 16> SVD;
3172   SVD.reserve(AllocaVec.size());
3173   for (AllocaInst *AI : AllocaVec) {
3174     ASanStackVariableDescription D = {AI->getName().data(),
3175                                       ASan.getAllocaSizeInBytes(*AI),
3176                                       0,
3177                                       AI->getAlignment(),
3178                                       AI,
3179                                       0,
3180                                       0};
3181     SVD.push_back(D);
3182   }
3183 
3184   // Minimal header size (left redzone) is 4 pointers,
3185   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
3186   size_t Granularity = 1ULL << Mapping.Scale;
3187   size_t MinHeaderSize = std::max((size_t)ASan.LongSize / 2, Granularity);
3188   const ASanStackFrameLayout &L =
3189       ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
3190 
3191   // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
3192   DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
3193   for (auto &Desc : SVD)
3194     AllocaToSVDMap[Desc.AI] = &Desc;
3195 
3196   // Update SVD with information from lifetime intrinsics.
3197   for (const auto &APC : StaticAllocaPoisonCallVec) {
3198     assert(APC.InsBefore);
3199     assert(APC.AI);
3200     assert(ASan.isInterestingAlloca(*APC.AI));
3201     assert(APC.AI->isStaticAlloca());
3202 
3203     ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3204     Desc.LifetimeSize = Desc.Size;
3205     if (const DILocation *FnLoc = EntryDebugLocation.get()) {
3206       if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
3207         if (LifetimeLoc->getFile() == FnLoc->getFile())
3208           if (unsigned Line = LifetimeLoc->getLine())
3209             Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
3210       }
3211     }
3212   }
3213 
3214   auto DescriptionString = ComputeASanStackFrameDescription(SVD);
3215   LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
3216   uint64_t LocalStackSize = L.FrameSize;
3217   bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
3218                        LocalStackSize <= kMaxStackMallocSize;
3219   bool DoDynamicAlloca = ClDynamicAllocaStack;
3220   // Don't do dynamic alloca or stack malloc if:
3221   // 1) There is inline asm: too often it makes assumptions on which registers
3222   //    are available.
3223   // 2) There is a returns_twice call (typically setjmp), which is
3224   //    optimization-hostile, and doesn't play well with introduced indirect
3225   //    register-relative calculation of local variable addresses.
3226   DoDynamicAlloca &= !HasInlineAsm && !HasReturnsTwiceCall;
3227   DoStackMalloc &= !HasInlineAsm && !HasReturnsTwiceCall;
3228 
3229   Value *StaticAlloca =
3230       DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
3231 
3232   Value *FakeStack;
3233   Value *LocalStackBase;
3234   Value *LocalStackBaseAlloca;
3235   uint8_t DIExprFlags = DIExpression::ApplyOffset;
3236 
3237   if (DoStackMalloc) {
3238     LocalStackBaseAlloca =
3239         IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
3240     // void *FakeStack = __asan_option_detect_stack_use_after_return
3241     //     ? __asan_stack_malloc_N(LocalStackSize)
3242     //     : nullptr;
3243     // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
3244     Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
3245         kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
3246     Value *UseAfterReturnIsEnabled = IRB.CreateICmpNE(
3247         IRB.CreateLoad(IRB.getInt32Ty(), OptionDetectUseAfterReturn),
3248         Constant::getNullValue(IRB.getInt32Ty()));
3249     Instruction *Term =
3250         SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
3251     IRBuilder<> IRBIf(Term);
3252     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
3253     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
3254     Value *FakeStackValue =
3255         IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
3256                          ConstantInt::get(IntptrTy, LocalStackSize));
3257     IRB.SetInsertPoint(InsBefore);
3258     FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
3259                           ConstantInt::get(IntptrTy, 0));
3260 
3261     Value *NoFakeStack =
3262         IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
3263     Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
3264     IRBIf.SetInsertPoint(Term);
3265     Value *AllocaValue =
3266         DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
3267 
3268     IRB.SetInsertPoint(InsBefore);
3269     LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
3270     IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
3271     DIExprFlags |= DIExpression::DerefBefore;
3272   } else {
3273     // void *FakeStack = nullptr;
3274     // void *LocalStackBase = alloca(LocalStackSize);
3275     FakeStack = ConstantInt::get(IntptrTy, 0);
3276     LocalStackBase =
3277         DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
3278     LocalStackBaseAlloca = LocalStackBase;
3279   }
3280 
3281   // It shouldn't matter whether we pass an `alloca` or a `ptrtoint` as the
3282   // dbg.declare address opereand, but passing a `ptrtoint` seems to confuse
3283   // later passes and can result in dropped variable coverage in debug info.
3284   Value *LocalStackBaseAllocaPtr =
3285       isa<PtrToIntInst>(LocalStackBaseAlloca)
3286           ? cast<PtrToIntInst>(LocalStackBaseAlloca)->getPointerOperand()
3287           : LocalStackBaseAlloca;
3288   assert(isa<AllocaInst>(LocalStackBaseAllocaPtr) &&
3289          "Variable descriptions relative to ASan stack base will be dropped");
3290 
3291   // Replace Alloca instructions with base+offset.
3292   for (const auto &Desc : SVD) {
3293     AllocaInst *AI = Desc.AI;
3294     replaceDbgDeclare(AI, LocalStackBaseAllocaPtr, DIB, DIExprFlags,
3295                       Desc.Offset);
3296     Value *NewAllocaPtr = IRB.CreateIntToPtr(
3297         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
3298         AI->getType());
3299     AI->replaceAllUsesWith(NewAllocaPtr);
3300   }
3301 
3302   // The left-most redzone has enough space for at least 4 pointers.
3303   // Write the Magic value to redzone[0].
3304   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
3305   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
3306                   BasePlus0);
3307   // Write the frame description constant to redzone[1].
3308   Value *BasePlus1 = IRB.CreateIntToPtr(
3309       IRB.CreateAdd(LocalStackBase,
3310                     ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
3311       IntptrPtrTy);
3312   GlobalVariable *StackDescriptionGlobal =
3313       createPrivateGlobalForString(*F.getParent(), DescriptionString,
3314                                    /*AllowMerging*/ true, kAsanGenPrefix);
3315   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
3316   IRB.CreateStore(Description, BasePlus1);
3317   // Write the PC to redzone[2].
3318   Value *BasePlus2 = IRB.CreateIntToPtr(
3319       IRB.CreateAdd(LocalStackBase,
3320                     ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
3321       IntptrPtrTy);
3322   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
3323 
3324   const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
3325 
3326   // Poison the stack red zones at the entry.
3327   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
3328   // As mask we must use most poisoned case: red zones and after scope.
3329   // As bytes we can use either the same or just red zones only.
3330   copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3331 
3332   if (!StaticAllocaPoisonCallVec.empty()) {
3333     const auto &ShadowInScope = GetShadowBytes(SVD, L);
3334 
3335     // Poison static allocas near lifetime intrinsics.
3336     for (const auto &APC : StaticAllocaPoisonCallVec) {
3337       const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3338       assert(Desc.Offset % L.Granularity == 0);
3339       size_t Begin = Desc.Offset / L.Granularity;
3340       size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
3341 
3342       IRBuilder<> IRB(APC.InsBefore);
3343       copyToShadow(ShadowAfterScope,
3344                    APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3345                    IRB, ShadowBase);
3346     }
3347   }
3348 
3349   SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
3350   SmallVector<uint8_t, 64> ShadowAfterReturn;
3351 
3352   // (Un)poison the stack before all ret instructions.
3353   for (Instruction *Ret : RetVec) {
3354     IRBuilder<> IRBRet(Ret);
3355     // Mark the current frame as retired.
3356     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3357                        BasePlus0);
3358     if (DoStackMalloc) {
3359       assert(StackMallocIdx >= 0);
3360       // if FakeStack != 0  // LocalStackBase == FakeStack
3361       //     // In use-after-return mode, poison the whole stack frame.
3362       //     if StackMallocIdx <= 4
3363       //         // For small sizes inline the whole thing:
3364       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
3365       //         **SavedFlagPtr(FakeStack) = 0
3366       //     else
3367       //         __asan_stack_free_N(FakeStack, LocalStackSize)
3368       // else
3369       //     <This is not a fake stack; unpoison the redzones>
3370       Value *Cmp =
3371           IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
3372       Instruction *ThenTerm, *ElseTerm;
3373       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3374 
3375       IRBuilder<> IRBPoison(ThenTerm);
3376       if (StackMallocIdx <= 4) {
3377         int ClassSize = kMinStackMallocSize << StackMallocIdx;
3378         ShadowAfterReturn.resize(ClassSize / L.Granularity,
3379                                  kAsanStackUseAfterReturnMagic);
3380         copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3381                      ShadowBase);
3382         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
3383             FakeStack,
3384             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3385         Value *SavedFlagPtr = IRBPoison.CreateLoad(
3386             IntptrTy, IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3387         IRBPoison.CreateStore(
3388             Constant::getNullValue(IRBPoison.getInt8Ty()),
3389             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3390       } else {
3391         // For larger frames call __asan_stack_free_*.
3392         IRBPoison.CreateCall(
3393             AsanStackFreeFunc[StackMallocIdx],
3394             {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
3395       }
3396 
3397       IRBuilder<> IRBElse(ElseTerm);
3398       copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
3399     } else {
3400       copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
3401     }
3402   }
3403 
3404   // We are done. Remove the old unused alloca instructions.
3405   for (auto AI : AllocaVec) AI->eraseFromParent();
3406 }
3407 
3408 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
3409                                          IRBuilder<> &IRB, bool DoPoison) {
3410   // For now just insert the call to ASan runtime.
3411   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3412   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
3413   IRB.CreateCall(
3414       DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3415       {AddrArg, SizeArg});
3416 }
3417 
3418 // Handling llvm.lifetime intrinsics for a given %alloca:
3419 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3420 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3421 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3422 //     could be poisoned by previous llvm.lifetime.end instruction, as the
3423 //     variable may go in and out of scope several times, e.g. in loops).
3424 // (3) if we poisoned at least one %alloca in a function,
3425 //     unpoison the whole stack frame at function exit.
3426 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
3427   IRBuilder<> IRB(AI);
3428 
3429   const unsigned Alignment = std::max(kAllocaRzSize, AI->getAlignment());
3430   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3431 
3432   Value *Zero = Constant::getNullValue(IntptrTy);
3433   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3434   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
3435 
3436   // Since we need to extend alloca with additional memory to locate
3437   // redzones, and OldSize is number of allocated blocks with
3438   // ElementSize size, get allocated memory size in bytes by
3439   // OldSize * ElementSize.
3440   const unsigned ElementSize =
3441       F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
3442   Value *OldSize =
3443       IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3444                     ConstantInt::get(IntptrTy, ElementSize));
3445 
3446   // PartialSize = OldSize % 32
3447   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3448 
3449   // Misalign = kAllocaRzSize - PartialSize;
3450   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3451 
3452   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3453   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3454   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3455 
3456   // AdditionalChunkSize = Alignment + PartialPadding + kAllocaRzSize
3457   // Alignment is added to locate left redzone, PartialPadding for possible
3458   // partial redzone and kAllocaRzSize for right redzone respectively.
3459   Value *AdditionalChunkSize = IRB.CreateAdd(
3460       ConstantInt::get(IntptrTy, Alignment + kAllocaRzSize), PartialPadding);
3461 
3462   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3463 
3464   // Insert new alloca with new NewSize and Alignment params.
3465   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3466   NewAlloca->setAlignment(Align(Alignment));
3467 
3468   // NewAddress = Address + Alignment
3469   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3470                                     ConstantInt::get(IntptrTy, Alignment));
3471 
3472   // Insert __asan_alloca_poison call for new created alloca.
3473   IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
3474 
3475   // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3476   // for unpoisoning stuff.
3477   IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3478 
3479   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3480 
3481   // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
3482   AI->replaceAllUsesWith(NewAddressPtr);
3483 
3484   // We are done. Erase old alloca from parent.
3485   AI->eraseFromParent();
3486 }
3487 
3488 // isSafeAccess returns true if Addr is always inbounds with respect to its
3489 // base object. For example, it is a field access or an array access with
3490 // constant inbounds index.
3491 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3492                                     Value *Addr, uint64_t TypeSize) const {
3493   SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3494   if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
3495   uint64_t Size = SizeOffset.first.getZExtValue();
3496   int64_t Offset = SizeOffset.second.getSExtValue();
3497   // Three checks are required to ensure safety:
3498   // . Offset >= 0  (since the offset is given from the base ptr)
3499   // . Size >= Offset  (unsigned)
3500   // . Size - Offset >= NeededSize  (unsigned)
3501   return Offset >= 0 && Size >= uint64_t(Offset) &&
3502          Size - uint64_t(Offset) >= TypeSize / 8;
3503 }
3504