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