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