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