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