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