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