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