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::XCOFF:
2114   case Triple::DXContainer:
2115     report_fatal_error(
2116         "ModuleAddressSanitizer not implemented for object file format");
2117   case Triple::UnknownObjectFormat:
2118     break;
2119   }
2120   llvm_unreachable("unsupported object format");
2121 }
2122 
2123 void ModuleAddressSanitizer::initializeCallbacks(Module &M) {
2124   IRBuilder<> IRB(*C);
2125 
2126   // Declare our poisoning and unpoisoning functions.
2127   AsanPoisonGlobals =
2128       M.getOrInsertFunction(kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy);
2129   AsanUnpoisonGlobals =
2130       M.getOrInsertFunction(kAsanUnpoisonGlobalsName, IRB.getVoidTy());
2131 
2132   // Declare functions that register/unregister globals.
2133   AsanRegisterGlobals = M.getOrInsertFunction(
2134       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2135   AsanUnregisterGlobals = M.getOrInsertFunction(
2136       kAsanUnregisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2137 
2138   // Declare the functions that find globals in a shared object and then invoke
2139   // the (un)register function on them.
2140   AsanRegisterImageGlobals = M.getOrInsertFunction(
2141       kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
2142   AsanUnregisterImageGlobals = M.getOrInsertFunction(
2143       kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
2144 
2145   AsanRegisterElfGlobals =
2146       M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
2147                             IntptrTy, IntptrTy, IntptrTy);
2148   AsanUnregisterElfGlobals =
2149       M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
2150                             IntptrTy, IntptrTy, IntptrTy);
2151 }
2152 
2153 // Put the metadata and the instrumented global in the same group. This ensures
2154 // that the metadata is discarded if the instrumented global is discarded.
2155 void ModuleAddressSanitizer::SetComdatForGlobalMetadata(
2156     GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
2157   Module &M = *G->getParent();
2158   Comdat *C = G->getComdat();
2159   if (!C) {
2160     if (!G->hasName()) {
2161       // If G is unnamed, it must be internal. Give it an artificial name
2162       // so we can put it in a comdat.
2163       assert(G->hasLocalLinkage());
2164       G->setName(Twine(kAsanGenPrefix) + "_anon_global");
2165     }
2166 
2167     if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
2168       std::string Name = std::string(G->getName());
2169       Name += InternalSuffix;
2170       C = M.getOrInsertComdat(Name);
2171     } else {
2172       C = M.getOrInsertComdat(G->getName());
2173     }
2174 
2175     // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
2176     // linkage to internal linkage so that a symbol table entry is emitted. This
2177     // is necessary in order to create the comdat group.
2178     if (TargetTriple.isOSBinFormatCOFF()) {
2179       C->setSelectionKind(Comdat::NoDeduplicate);
2180       if (G->hasPrivateLinkage())
2181         G->setLinkage(GlobalValue::InternalLinkage);
2182     }
2183     G->setComdat(C);
2184   }
2185 
2186   assert(G->hasComdat());
2187   Metadata->setComdat(G->getComdat());
2188 }
2189 
2190 // Create a separate metadata global and put it in the appropriate ASan
2191 // global registration section.
2192 GlobalVariable *
2193 ModuleAddressSanitizer::CreateMetadataGlobal(Module &M, Constant *Initializer,
2194                                              StringRef OriginalName) {
2195   auto Linkage = TargetTriple.isOSBinFormatMachO()
2196                      ? GlobalVariable::InternalLinkage
2197                      : GlobalVariable::PrivateLinkage;
2198   GlobalVariable *Metadata = new GlobalVariable(
2199       M, Initializer->getType(), false, Linkage, Initializer,
2200       Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
2201   Metadata->setSection(getGlobalMetadataSection());
2202   return Metadata;
2203 }
2204 
2205 Instruction *ModuleAddressSanitizer::CreateAsanModuleDtor(Module &M) {
2206   AsanDtorFunction = Function::createWithDefaultAttr(
2207       FunctionType::get(Type::getVoidTy(*C), false),
2208       GlobalValue::InternalLinkage, 0, kAsanModuleDtorName, &M);
2209   AsanDtorFunction->addFnAttr(Attribute::NoUnwind);
2210   // Ensure Dtor cannot be discarded, even if in a comdat.
2211   appendToUsed(M, {AsanDtorFunction});
2212   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
2213 
2214   return ReturnInst::Create(*C, AsanDtorBB);
2215 }
2216 
2217 void ModuleAddressSanitizer::InstrumentGlobalsCOFF(
2218     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2219     ArrayRef<Constant *> MetadataInitializers) {
2220   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2221   auto &DL = M.getDataLayout();
2222 
2223   SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2224   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2225     Constant *Initializer = MetadataInitializers[i];
2226     GlobalVariable *G = ExtendedGlobals[i];
2227     GlobalVariable *Metadata =
2228         CreateMetadataGlobal(M, Initializer, G->getName());
2229     MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2230     Metadata->setMetadata(LLVMContext::MD_associated, MD);
2231     MetadataGlobals[i] = Metadata;
2232 
2233     // The MSVC linker always inserts padding when linking incrementally. We
2234     // cope with that by aligning each struct to its size, which must be a power
2235     // of two.
2236     unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
2237     assert(isPowerOf2_32(SizeOfGlobalStruct) &&
2238            "global metadata will not be padded appropriately");
2239     Metadata->setAlignment(assumeAligned(SizeOfGlobalStruct));
2240 
2241     SetComdatForGlobalMetadata(G, Metadata, "");
2242   }
2243 
2244   // Update llvm.compiler.used, adding the new metadata globals. This is
2245   // needed so that during LTO these variables stay alive.
2246   if (!MetadataGlobals.empty())
2247     appendToCompilerUsed(M, MetadataGlobals);
2248 }
2249 
2250 void ModuleAddressSanitizer::InstrumentGlobalsELF(
2251     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2252     ArrayRef<Constant *> MetadataInitializers,
2253     const std::string &UniqueModuleId) {
2254   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2255 
2256   // Putting globals in a comdat changes the semantic and potentially cause
2257   // false negative odr violations at link time. If odr indicators are used, we
2258   // keep the comdat sections, as link time odr violations will be dectected on
2259   // the odr indicator symbols.
2260   bool UseComdatForGlobalsGC = UseOdrIndicator;
2261 
2262   SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2263   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2264     GlobalVariable *G = ExtendedGlobals[i];
2265     GlobalVariable *Metadata =
2266         CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
2267     MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2268     Metadata->setMetadata(LLVMContext::MD_associated, MD);
2269     MetadataGlobals[i] = Metadata;
2270 
2271     if (UseComdatForGlobalsGC)
2272       SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
2273   }
2274 
2275   // Update llvm.compiler.used, adding the new metadata globals. This is
2276   // needed so that during LTO these variables stay alive.
2277   if (!MetadataGlobals.empty())
2278     appendToCompilerUsed(M, MetadataGlobals);
2279 
2280   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2281   // to look up the loaded image that contains it. Second, we can store in it
2282   // whether registration has already occurred, to prevent duplicate
2283   // registration.
2284   //
2285   // Common linkage ensures that there is only one global per shared library.
2286   GlobalVariable *RegisteredFlag = new GlobalVariable(
2287       M, IntptrTy, false, GlobalVariable::CommonLinkage,
2288       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2289   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2290 
2291   // Create start and stop symbols.
2292   GlobalVariable *StartELFMetadata = new GlobalVariable(
2293       M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2294       "__start_" + getGlobalMetadataSection());
2295   StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
2296   GlobalVariable *StopELFMetadata = new GlobalVariable(
2297       M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2298       "__stop_" + getGlobalMetadataSection());
2299   StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
2300 
2301   // Create a call to register the globals with the runtime.
2302   IRB.CreateCall(AsanRegisterElfGlobals,
2303                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2304                   IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2305                   IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2306 
2307   // We also need to unregister globals at the end, e.g., when a shared library
2308   // gets closed.
2309   if (DestructorKind != AsanDtorKind::None) {
2310     IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2311     IrbDtor.CreateCall(AsanUnregisterElfGlobals,
2312                        {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2313                         IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2314                         IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2315   }
2316 }
2317 
2318 void ModuleAddressSanitizer::InstrumentGlobalsMachO(
2319     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2320     ArrayRef<Constant *> MetadataInitializers) {
2321   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2322 
2323   // On recent Mach-O platforms, use a structure which binds the liveness of
2324   // the global variable to the metadata struct. Keep the list of "Liveness" GV
2325   // created to be added to llvm.compiler.used
2326   StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
2327   SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
2328 
2329   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2330     Constant *Initializer = MetadataInitializers[i];
2331     GlobalVariable *G = ExtendedGlobals[i];
2332     GlobalVariable *Metadata =
2333         CreateMetadataGlobal(M, Initializer, G->getName());
2334 
2335     // On recent Mach-O platforms, we emit the global metadata in a way that
2336     // allows the linker to properly strip dead globals.
2337     auto LivenessBinder =
2338         ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
2339                             ConstantExpr::getPointerCast(Metadata, IntptrTy));
2340     GlobalVariable *Liveness = new GlobalVariable(
2341         M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
2342         Twine("__asan_binder_") + G->getName());
2343     Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
2344     LivenessGlobals[i] = Liveness;
2345   }
2346 
2347   // Update llvm.compiler.used, adding the new liveness globals. This is
2348   // needed so that during LTO these variables stay alive. The alternative
2349   // would be to have the linker handling the LTO symbols, but libLTO
2350   // current API does not expose access to the section for each symbol.
2351   if (!LivenessGlobals.empty())
2352     appendToCompilerUsed(M, LivenessGlobals);
2353 
2354   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2355   // to look up the loaded image that contains it. Second, we can store in it
2356   // whether registration has already occurred, to prevent duplicate
2357   // registration.
2358   //
2359   // common linkage ensures that there is only one global per shared library.
2360   GlobalVariable *RegisteredFlag = new GlobalVariable(
2361       M, IntptrTy, false, GlobalVariable::CommonLinkage,
2362       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2363   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2364 
2365   IRB.CreateCall(AsanRegisterImageGlobals,
2366                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2367 
2368   // We also need to unregister globals at the end, e.g., when a shared library
2369   // gets closed.
2370   if (DestructorKind != AsanDtorKind::None) {
2371     IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2372     IrbDtor.CreateCall(AsanUnregisterImageGlobals,
2373                        {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2374   }
2375 }
2376 
2377 void ModuleAddressSanitizer::InstrumentGlobalsWithMetadataArray(
2378     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2379     ArrayRef<Constant *> MetadataInitializers) {
2380   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2381   unsigned N = ExtendedGlobals.size();
2382   assert(N > 0);
2383 
2384   // On platforms that don't have a custom metadata section, we emit an array
2385   // of global metadata structures.
2386   ArrayType *ArrayOfGlobalStructTy =
2387       ArrayType::get(MetadataInitializers[0]->getType(), N);
2388   auto AllGlobals = new GlobalVariable(
2389       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
2390       ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
2391   if (Mapping.Scale > 3)
2392     AllGlobals->setAlignment(Align(1ULL << Mapping.Scale));
2393 
2394   IRB.CreateCall(AsanRegisterGlobals,
2395                  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2396                   ConstantInt::get(IntptrTy, N)});
2397 
2398   // We also need to unregister globals at the end, e.g., when a shared library
2399   // gets closed.
2400   if (DestructorKind != AsanDtorKind::None) {
2401     IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2402     IrbDtor.CreateCall(AsanUnregisterGlobals,
2403                        {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2404                         ConstantInt::get(IntptrTy, N)});
2405   }
2406 }
2407 
2408 // This function replaces all global variables with new variables that have
2409 // trailing redzones. It also creates a function that poisons
2410 // redzones and inserts this function into llvm.global_ctors.
2411 // Sets *CtorComdat to true if the global registration code emitted into the
2412 // asan constructor is comdat-compatible.
2413 bool ModuleAddressSanitizer::InstrumentGlobals(IRBuilder<> &IRB, Module &M,
2414                                                bool *CtorComdat) {
2415   *CtorComdat = false;
2416 
2417   // Build set of globals that are aliased by some GA, where
2418   // getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.
2419   SmallPtrSet<const GlobalVariable *, 16> AliasedGlobalExclusions;
2420   if (CompileKernel) {
2421     for (auto &GA : M.aliases()) {
2422       if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))
2423         AliasedGlobalExclusions.insert(GV);
2424     }
2425   }
2426 
2427   SmallVector<GlobalVariable *, 16> GlobalsToChange;
2428   for (auto &G : M.globals()) {
2429     if (!AliasedGlobalExclusions.count(&G) && shouldInstrumentGlobal(&G))
2430       GlobalsToChange.push_back(&G);
2431   }
2432 
2433   size_t n = GlobalsToChange.size();
2434   if (n == 0) {
2435     *CtorComdat = true;
2436     return false;
2437   }
2438 
2439   auto &DL = M.getDataLayout();
2440 
2441   // A global is described by a structure
2442   //   size_t beg;
2443   //   size_t size;
2444   //   size_t size_with_redzone;
2445   //   const char *name;
2446   //   const char *module_name;
2447   //   size_t has_dynamic_init;
2448   //   void *source_location;
2449   //   size_t odr_indicator;
2450   // We initialize an array of such structures and pass it to a run-time call.
2451   StructType *GlobalStructTy =
2452       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
2453                       IntptrTy, IntptrTy, IntptrTy);
2454   SmallVector<GlobalVariable *, 16> NewGlobals(n);
2455   SmallVector<Constant *, 16> Initializers(n);
2456 
2457   bool HasDynamicallyInitializedGlobals = false;
2458 
2459   // We shouldn't merge same module names, as this string serves as unique
2460   // module ID in runtime.
2461   GlobalVariable *ModuleName = createPrivateGlobalForString(
2462       M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
2463 
2464   for (size_t i = 0; i < n; i++) {
2465     GlobalVariable *G = GlobalsToChange[i];
2466 
2467     // FIXME: Metadata should be attched directly to the global directly instead
2468     // of being added to llvm.asan.globals.
2469     auto MD = GlobalsMD.get(G);
2470     StringRef NameForGlobal = G->getName();
2471     // Create string holding the global name (use global name from metadata
2472     // if it's available, otherwise just write the name of global variable).
2473     GlobalVariable *Name = createPrivateGlobalForString(
2474         M, MD.Name.empty() ? NameForGlobal : MD.Name,
2475         /*AllowMerging*/ true, kAsanGenPrefix);
2476 
2477     Type *Ty = G->getValueType();
2478     const uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
2479     const uint64_t RightRedzoneSize = getRedzoneSizeForGlobal(SizeInBytes);
2480     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2481 
2482     StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2483     Constant *NewInitializer = ConstantStruct::get(
2484         NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
2485 
2486     // Create a new global variable with enough space for a redzone.
2487     GlobalValue::LinkageTypes Linkage = G->getLinkage();
2488     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2489       Linkage = GlobalValue::InternalLinkage;
2490     GlobalVariable *NewGlobal = new GlobalVariable(
2491         M, NewTy, G->isConstant(), Linkage, NewInitializer, "", G,
2492         G->getThreadLocalMode(), G->getAddressSpace());
2493     NewGlobal->copyAttributesFrom(G);
2494     NewGlobal->setComdat(G->getComdat());
2495     NewGlobal->setAlignment(MaybeAlign(getMinRedzoneSizeForGlobal()));
2496     // Don't fold globals with redzones. ODR violation detector and redzone
2497     // poisoning implicitly creates a dependence on the global's address, so it
2498     // is no longer valid for it to be marked unnamed_addr.
2499     NewGlobal->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
2500 
2501     // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2502     if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2503         G->isConstant()) {
2504       auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2505       if (Seq && Seq->isCString())
2506         NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2507     }
2508 
2509     // Transfer the debug info and type metadata.  The payload starts at offset
2510     // zero so we can copy the metadata over as is.
2511     NewGlobal->copyMetadata(G, 0);
2512 
2513     Value *Indices2[2];
2514     Indices2[0] = IRB.getInt32(0);
2515     Indices2[1] = IRB.getInt32(0);
2516 
2517     G->replaceAllUsesWith(
2518         ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
2519     NewGlobal->takeName(G);
2520     G->eraseFromParent();
2521     NewGlobals[i] = NewGlobal;
2522 
2523     Constant *SourceLoc;
2524     if (!MD.SourceLoc.empty()) {
2525       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2526       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2527     } else {
2528       SourceLoc = ConstantInt::get(IntptrTy, 0);
2529     }
2530 
2531     Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2532     GlobalValue *InstrumentedGlobal = NewGlobal;
2533 
2534     bool CanUsePrivateAliases =
2535         TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2536         TargetTriple.isOSBinFormatWasm();
2537     if (CanUsePrivateAliases && UsePrivateAlias) {
2538       // Create local alias for NewGlobal to avoid crash on ODR between
2539       // instrumented and non-instrumented libraries.
2540       InstrumentedGlobal =
2541           GlobalAlias::create(GlobalValue::PrivateLinkage, "", NewGlobal);
2542     }
2543 
2544     // ODR should not happen for local linkage.
2545     if (NewGlobal->hasLocalLinkage()) {
2546       ODRIndicator = ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, -1),
2547                                                IRB.getInt8PtrTy());
2548     } else if (UseOdrIndicator) {
2549       // With local aliases, we need to provide another externally visible
2550       // symbol __odr_asan_XXX to detect ODR violation.
2551       auto *ODRIndicatorSym =
2552           new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2553                              Constant::getNullValue(IRB.getInt8Ty()),
2554                              kODRGenPrefix + NameForGlobal, nullptr,
2555                              NewGlobal->getThreadLocalMode());
2556 
2557       // Set meaningful attributes for indicator symbol.
2558       ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2559       ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2560       ODRIndicatorSym->setAlignment(Align(1));
2561       ODRIndicator = ODRIndicatorSym;
2562     }
2563 
2564     Constant *Initializer = ConstantStruct::get(
2565         GlobalStructTy,
2566         ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
2567         ConstantInt::get(IntptrTy, SizeInBytes),
2568         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2569         ConstantExpr::getPointerCast(Name, IntptrTy),
2570         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
2571         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
2572         ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
2573 
2574     if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
2575 
2576     LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
2577 
2578     Initializers[i] = Initializer;
2579   }
2580 
2581   // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2582   // ConstantMerge'ing them.
2583   SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2584   for (size_t i = 0; i < n; i++) {
2585     GlobalVariable *G = NewGlobals[i];
2586     if (G->getName().empty()) continue;
2587     GlobalsToAddToUsedList.push_back(G);
2588   }
2589   appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2590 
2591   std::string ELFUniqueModuleId =
2592       (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2593                                                         : "";
2594 
2595   if (!ELFUniqueModuleId.empty()) {
2596     InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2597     *CtorComdat = true;
2598   } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
2599     InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2600   } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2601     InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2602   } else {
2603     InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2604   }
2605 
2606   // Create calls for poisoning before initializers run and unpoisoning after.
2607   if (HasDynamicallyInitializedGlobals)
2608     createInitializerPoisonCalls(M, ModuleName);
2609 
2610   LLVM_DEBUG(dbgs() << M);
2611   return true;
2612 }
2613 
2614 uint64_t
2615 ModuleAddressSanitizer::getRedzoneSizeForGlobal(uint64_t SizeInBytes) const {
2616   constexpr uint64_t kMaxRZ = 1 << 18;
2617   const uint64_t MinRZ = getMinRedzoneSizeForGlobal();
2618 
2619   uint64_t RZ = 0;
2620   if (SizeInBytes <= MinRZ / 2) {
2621     // Reduce redzone size for small size objects, e.g. int, char[1]. MinRZ is
2622     // at least 32 bytes, optimize when SizeInBytes is less than or equal to
2623     // half of MinRZ.
2624     RZ = MinRZ - SizeInBytes;
2625   } else {
2626     // Calculate RZ, where MinRZ <= RZ <= MaxRZ, and RZ ~ 1/4 * SizeInBytes.
2627     RZ = std::max(MinRZ, std::min(kMaxRZ, (SizeInBytes / MinRZ / 4) * MinRZ));
2628 
2629     // Round up to multiple of MinRZ.
2630     if (SizeInBytes % MinRZ)
2631       RZ += MinRZ - (SizeInBytes % MinRZ);
2632   }
2633 
2634   assert((RZ + SizeInBytes) % MinRZ == 0);
2635 
2636   return RZ;
2637 }
2638 
2639 int ModuleAddressSanitizer::GetAsanVersion(const Module &M) const {
2640   int LongSize = M.getDataLayout().getPointerSizeInBits();
2641   bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2642   int Version = 8;
2643   // 32-bit Android is one version ahead because of the switch to dynamic
2644   // shadow.
2645   Version += (LongSize == 32 && isAndroid);
2646   return Version;
2647 }
2648 
2649 bool ModuleAddressSanitizer::instrumentModule(Module &M) {
2650   initializeCallbacks(M);
2651 
2652   // Create a module constructor. A destructor is created lazily because not all
2653   // platforms, and not all modules need it.
2654   if (CompileKernel) {
2655     // The kernel always builds with its own runtime, and therefore does not
2656     // need the init and version check calls.
2657     AsanCtorFunction = createSanitizerCtor(M, kAsanModuleCtorName);
2658   } else {
2659     std::string AsanVersion = std::to_string(GetAsanVersion(M));
2660     std::string VersionCheckName =
2661         ClInsertVersionCheck ? (kAsanVersionCheckNamePrefix + AsanVersion) : "";
2662     std::tie(AsanCtorFunction, std::ignore) =
2663         createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName,
2664                                             kAsanInitName, /*InitArgTypes=*/{},
2665                                             /*InitArgs=*/{}, VersionCheckName);
2666   }
2667 
2668   bool CtorComdat = true;
2669   if (ClGlobals) {
2670     IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2671     InstrumentGlobals(IRB, M, &CtorComdat);
2672   }
2673 
2674   const uint64_t Priority = GetCtorAndDtorPriority(TargetTriple);
2675 
2676   // Put the constructor and destructor in comdat if both
2677   // (1) global instrumentation is not TU-specific
2678   // (2) target is ELF.
2679   if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2680     AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2681     appendToGlobalCtors(M, AsanCtorFunction, Priority, AsanCtorFunction);
2682     if (AsanDtorFunction) {
2683       AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2684       appendToGlobalDtors(M, AsanDtorFunction, Priority, AsanDtorFunction);
2685     }
2686   } else {
2687     appendToGlobalCtors(M, AsanCtorFunction, Priority);
2688     if (AsanDtorFunction)
2689       appendToGlobalDtors(M, AsanDtorFunction, Priority);
2690   }
2691 
2692   return true;
2693 }
2694 
2695 void AddressSanitizer::initializeCallbacks(Module &M) {
2696   IRBuilder<> IRB(*C);
2697   // Create __asan_report* callbacks.
2698   // IsWrite, TypeSize and Exp are encoded in the function name.
2699   for (int Exp = 0; Exp < 2; Exp++) {
2700     for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2701       const std::string TypeStr = AccessIsWrite ? "store" : "load";
2702       const std::string ExpStr = Exp ? "exp_" : "";
2703       const std::string EndingStr = Recover ? "_noabort" : "";
2704 
2705       SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2706       SmallVector<Type *, 2> Args1{1, IntptrTy};
2707       if (Exp) {
2708         Type *ExpType = Type::getInt32Ty(*C);
2709         Args2.push_back(ExpType);
2710         Args1.push_back(ExpType);
2711       }
2712       AsanErrorCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2713           kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
2714           FunctionType::get(IRB.getVoidTy(), Args2, false));
2715 
2716       AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2717           ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2718           FunctionType::get(IRB.getVoidTy(), Args2, false));
2719 
2720       for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2721            AccessSizeIndex++) {
2722         const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2723         AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2724             M.getOrInsertFunction(
2725                 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2726                 FunctionType::get(IRB.getVoidTy(), Args1, false));
2727 
2728         AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2729             M.getOrInsertFunction(
2730                 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2731                 FunctionType::get(IRB.getVoidTy(), Args1, false));
2732       }
2733     }
2734   }
2735 
2736   const std::string MemIntrinCallbackPrefix =
2737       (CompileKernel && !ClKasanMemIntrinCallbackPrefix)
2738           ? std::string("")
2739           : ClMemoryAccessCallbackPrefix;
2740   AsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",
2741                                       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2742                                       IRB.getInt8PtrTy(), IntptrTy);
2743   AsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy",
2744                                      IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2745                                      IRB.getInt8PtrTy(), IntptrTy);
2746   AsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",
2747                                      IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2748                                      IRB.getInt32Ty(), IntptrTy);
2749 
2750   AsanHandleNoReturnFunc =
2751       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy());
2752 
2753   AsanPtrCmpFunction =
2754       M.getOrInsertFunction(kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy);
2755   AsanPtrSubFunction =
2756       M.getOrInsertFunction(kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy);
2757   if (Mapping.InGlobal)
2758     AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2759                                            ArrayType::get(IRB.getInt8Ty(), 0));
2760 
2761   AMDGPUAddressShared = M.getOrInsertFunction(
2762       kAMDGPUAddressSharedName, IRB.getInt1Ty(), IRB.getInt8PtrTy());
2763   AMDGPUAddressPrivate = M.getOrInsertFunction(
2764       kAMDGPUAddressPrivateName, IRB.getInt1Ty(), IRB.getInt8PtrTy());
2765 }
2766 
2767 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2768   // For each NSObject descendant having a +load method, this method is invoked
2769   // by the ObjC runtime before any of the static constructors is called.
2770   // Therefore we need to instrument such methods with a call to __asan_init
2771   // at the beginning in order to initialize our runtime before any access to
2772   // the shadow memory.
2773   // We cannot just ignore these methods, because they may call other
2774   // instrumented functions.
2775   if (F.getName().find(" load]") != std::string::npos) {
2776     FunctionCallee AsanInitFunction =
2777         declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
2778     IRBuilder<> IRB(&F.front(), F.front().begin());
2779     IRB.CreateCall(AsanInitFunction, {});
2780     return true;
2781   }
2782   return false;
2783 }
2784 
2785 bool AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2786   // Generate code only when dynamic addressing is needed.
2787   if (Mapping.Offset != kDynamicShadowSentinel)
2788     return false;
2789 
2790   IRBuilder<> IRB(&F.front().front());
2791   if (Mapping.InGlobal) {
2792     if (ClWithIfuncSuppressRemat) {
2793       // An empty inline asm with input reg == output reg.
2794       // An opaque pointer-to-int cast, basically.
2795       InlineAsm *Asm = InlineAsm::get(
2796           FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2797           StringRef(""), StringRef("=r,0"),
2798           /*hasSideEffects=*/false);
2799       LocalDynamicShadow =
2800           IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2801     } else {
2802       LocalDynamicShadow =
2803           IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2804     }
2805   } else {
2806     Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2807         kAsanShadowMemoryDynamicAddress, IntptrTy);
2808     LocalDynamicShadow = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);
2809   }
2810   return true;
2811 }
2812 
2813 void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2814   // Find the one possible call to llvm.localescape and pre-mark allocas passed
2815   // to it as uninteresting. This assumes we haven't started processing allocas
2816   // yet. This check is done up front because iterating the use list in
2817   // isInterestingAlloca would be algorithmically slower.
2818   assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2819 
2820   // Try to get the declaration of llvm.localescape. If it's not in the module,
2821   // we can exit early.
2822   if (!F.getParent()->getFunction("llvm.localescape")) return;
2823 
2824   // Look for a call to llvm.localescape call in the entry block. It can't be in
2825   // any other block.
2826   for (Instruction &I : F.getEntryBlock()) {
2827     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2828     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2829       // We found a call. Mark all the allocas passed in as uninteresting.
2830       for (Value *Arg : II->args()) {
2831         AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2832         assert(AI && AI->isStaticAlloca() &&
2833                "non-static alloca arg to localescape");
2834         ProcessedAllocas[AI] = false;
2835       }
2836       break;
2837     }
2838   }
2839 }
2840 
2841 bool AddressSanitizer::suppressInstrumentationSiteForDebug(int &Instrumented) {
2842   bool ShouldInstrument =
2843       ClDebugMin < 0 || ClDebugMax < 0 ||
2844       (Instrumented >= ClDebugMin && Instrumented <= ClDebugMax);
2845   Instrumented++;
2846   return !ShouldInstrument;
2847 }
2848 
2849 bool AddressSanitizer::instrumentFunction(Function &F,
2850                                           const TargetLibraryInfo *TLI) {
2851   if (F.empty())
2852     return false;
2853   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2854   if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2855   if (F.getName().startswith("__asan_")) return false;
2856 
2857   bool FunctionModified = false;
2858 
2859   // If needed, insert __asan_init before checking for SanitizeAddress attr.
2860   // This function needs to be called even if the function body is not
2861   // instrumented.
2862   if (maybeInsertAsanInitAtFunctionEntry(F))
2863     FunctionModified = true;
2864 
2865   // Leave if the function doesn't need instrumentation.
2866   if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2867 
2868   if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
2869     return FunctionModified;
2870 
2871   LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2872 
2873   initializeCallbacks(*F.getParent());
2874 
2875   FunctionStateRAII CleanupObj(this);
2876 
2877   FunctionModified |= maybeInsertDynamicShadowAtFunctionEntry(F);
2878 
2879   // We can't instrument allocas used with llvm.localescape. Only static allocas
2880   // can be passed to that intrinsic.
2881   markEscapedLocalAllocas(F);
2882 
2883   // We want to instrument every address only once per basic block (unless there
2884   // are calls between uses).
2885   SmallPtrSet<Value *, 16> TempsToInstrument;
2886   SmallVector<InterestingMemoryOperand, 16> OperandsToInstrument;
2887   SmallVector<MemIntrinsic *, 16> IntrinToInstrument;
2888   SmallVector<Instruction *, 8> NoReturnCalls;
2889   SmallVector<BasicBlock *, 16> AllBlocks;
2890   SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2891 
2892   // Fill the set of memory operations to instrument.
2893   for (auto &BB : F) {
2894     AllBlocks.push_back(&BB);
2895     TempsToInstrument.clear();
2896     int NumInsnsPerBB = 0;
2897     for (auto &Inst : BB) {
2898       if (LooksLikeCodeInBug11395(&Inst)) return false;
2899       SmallVector<InterestingMemoryOperand, 1> InterestingOperands;
2900       getInterestingMemoryOperands(&Inst, InterestingOperands);
2901 
2902       if (!InterestingOperands.empty()) {
2903         for (auto &Operand : InterestingOperands) {
2904           if (ClOpt && ClOptSameTemp) {
2905             Value *Ptr = Operand.getPtr();
2906             // If we have a mask, skip instrumentation if we've already
2907             // instrumented the full object. But don't add to TempsToInstrument
2908             // because we might get another load/store with a different mask.
2909             if (Operand.MaybeMask) {
2910               if (TempsToInstrument.count(Ptr))
2911                 continue; // We've seen this (whole) temp in the current BB.
2912             } else {
2913               if (!TempsToInstrument.insert(Ptr).second)
2914                 continue; // We've seen this temp in the current BB.
2915             }
2916           }
2917           OperandsToInstrument.push_back(Operand);
2918           NumInsnsPerBB++;
2919         }
2920       } else if (((ClInvalidPointerPairs || ClInvalidPointerCmp) &&
2921                   isInterestingPointerComparison(&Inst)) ||
2922                  ((ClInvalidPointerPairs || ClInvalidPointerSub) &&
2923                   isInterestingPointerSubtraction(&Inst))) {
2924         PointerComparisonsOrSubtracts.push_back(&Inst);
2925       } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst)) {
2926         // ok, take it.
2927         IntrinToInstrument.push_back(MI);
2928         NumInsnsPerBB++;
2929       } else {
2930         if (auto *CB = dyn_cast<CallBase>(&Inst)) {
2931           // A call inside BB.
2932           TempsToInstrument.clear();
2933           if (CB->doesNotReturn() && !CB->hasMetadata("nosanitize"))
2934             NoReturnCalls.push_back(CB);
2935         }
2936         if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2937           maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
2938       }
2939       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
2940     }
2941   }
2942 
2943   bool UseCalls = (ClInstrumentationWithCallsThreshold >= 0 &&
2944                    OperandsToInstrument.size() + IntrinToInstrument.size() >
2945                        (unsigned)ClInstrumentationWithCallsThreshold);
2946   const DataLayout &DL = F.getParent()->getDataLayout();
2947   ObjectSizeOpts ObjSizeOpts;
2948   ObjSizeOpts.RoundToAlign = true;
2949   ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
2950 
2951   // Instrument.
2952   int NumInstrumented = 0;
2953   for (auto &Operand : OperandsToInstrument) {
2954     if (!suppressInstrumentationSiteForDebug(NumInstrumented))
2955       instrumentMop(ObjSizeVis, Operand, UseCalls,
2956                     F.getParent()->getDataLayout());
2957     FunctionModified = true;
2958   }
2959   for (auto Inst : IntrinToInstrument) {
2960     if (!suppressInstrumentationSiteForDebug(NumInstrumented))
2961       instrumentMemIntrinsic(Inst);
2962     FunctionModified = true;
2963   }
2964 
2965   FunctionStackPoisoner FSP(F, *this);
2966   bool ChangedStack = FSP.runOnFunction();
2967 
2968   // We must unpoison the stack before NoReturn calls (throw, _exit, etc).
2969   // See e.g. https://github.com/google/sanitizers/issues/37
2970   for (auto CI : NoReturnCalls) {
2971     IRBuilder<> IRB(CI);
2972     IRB.CreateCall(AsanHandleNoReturnFunc, {});
2973   }
2974 
2975   for (auto Inst : PointerComparisonsOrSubtracts) {
2976     instrumentPointerComparisonOrSubtraction(Inst);
2977     FunctionModified = true;
2978   }
2979 
2980   if (ChangedStack || !NoReturnCalls.empty())
2981     FunctionModified = true;
2982 
2983   LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2984                     << F << "\n");
2985 
2986   return FunctionModified;
2987 }
2988 
2989 // Workaround for bug 11395: we don't want to instrument stack in functions
2990 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2991 // FIXME: remove once the bug 11395 is fixed.
2992 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2993   if (LongSize != 32) return false;
2994   CallInst *CI = dyn_cast<CallInst>(I);
2995   if (!CI || !CI->isInlineAsm()) return false;
2996   if (CI->arg_size() <= 5)
2997     return false;
2998   // We have inline assembly with quite a few arguments.
2999   return true;
3000 }
3001 
3002 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
3003   IRBuilder<> IRB(*C);
3004   if (ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Always ||
3005       ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Runtime) {
3006     const char *MallocNameTemplate =
3007         ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Always
3008             ? kAsanStackMallocAlwaysNameTemplate
3009             : kAsanStackMallocNameTemplate;
3010     for (int Index = 0; Index <= kMaxAsanStackMallocSizeClass; Index++) {
3011       std::string Suffix = itostr(Index);
3012       AsanStackMallocFunc[Index] = M.getOrInsertFunction(
3013           MallocNameTemplate + Suffix, IntptrTy, IntptrTy);
3014       AsanStackFreeFunc[Index] =
3015           M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
3016                                 IRB.getVoidTy(), IntptrTy, IntptrTy);
3017     }
3018   }
3019   if (ASan.UseAfterScope) {
3020     AsanPoisonStackMemoryFunc = M.getOrInsertFunction(
3021         kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
3022     AsanUnpoisonStackMemoryFunc = M.getOrInsertFunction(
3023         kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
3024   }
3025 
3026   for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
3027     std::ostringstream Name;
3028     Name << kAsanSetShadowPrefix;
3029     Name << std::setw(2) << std::setfill('0') << std::hex << Val;
3030     AsanSetShadowFunc[Val] =
3031         M.getOrInsertFunction(Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy);
3032   }
3033 
3034   AsanAllocaPoisonFunc = M.getOrInsertFunction(
3035       kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
3036   AsanAllocasUnpoisonFunc = M.getOrInsertFunction(
3037       kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
3038 }
3039 
3040 void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
3041                                                ArrayRef<uint8_t> ShadowBytes,
3042                                                size_t Begin, size_t End,
3043                                                IRBuilder<> &IRB,
3044                                                Value *ShadowBase) {
3045   if (Begin >= End)
3046     return;
3047 
3048   const size_t LargestStoreSizeInBytes =
3049       std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
3050 
3051   const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
3052 
3053   // Poison given range in shadow using larges store size with out leading and
3054   // trailing zeros in ShadowMask. Zeros never change, so they need neither
3055   // poisoning nor up-poisoning. Still we don't mind if some of them get into a
3056   // middle of a store.
3057   for (size_t i = Begin; i < End;) {
3058     if (!ShadowMask[i]) {
3059       assert(!ShadowBytes[i]);
3060       ++i;
3061       continue;
3062     }
3063 
3064     size_t StoreSizeInBytes = LargestStoreSizeInBytes;
3065     // Fit store size into the range.
3066     while (StoreSizeInBytes > End - i)
3067       StoreSizeInBytes /= 2;
3068 
3069     // Minimize store size by trimming trailing zeros.
3070     for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
3071       while (j <= StoreSizeInBytes / 2)
3072         StoreSizeInBytes /= 2;
3073     }
3074 
3075     uint64_t Val = 0;
3076     for (size_t j = 0; j < StoreSizeInBytes; j++) {
3077       if (IsLittleEndian)
3078         Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
3079       else
3080         Val = (Val << 8) | ShadowBytes[i + j];
3081     }
3082 
3083     Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
3084     Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
3085     IRB.CreateAlignedStore(
3086         Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()),
3087         Align(1));
3088 
3089     i += StoreSizeInBytes;
3090   }
3091 }
3092 
3093 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
3094                                          ArrayRef<uint8_t> ShadowBytes,
3095                                          IRBuilder<> &IRB, Value *ShadowBase) {
3096   copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
3097 }
3098 
3099 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
3100                                          ArrayRef<uint8_t> ShadowBytes,
3101                                          size_t Begin, size_t End,
3102                                          IRBuilder<> &IRB, Value *ShadowBase) {
3103   assert(ShadowMask.size() == ShadowBytes.size());
3104   size_t Done = Begin;
3105   for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
3106     if (!ShadowMask[i]) {
3107       assert(!ShadowBytes[i]);
3108       continue;
3109     }
3110     uint8_t Val = ShadowBytes[i];
3111     if (!AsanSetShadowFunc[Val])
3112       continue;
3113 
3114     // Skip same values.
3115     for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
3116     }
3117 
3118     if (j - i >= ClMaxInlinePoisoningSize) {
3119       copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
3120       IRB.CreateCall(AsanSetShadowFunc[Val],
3121                      {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
3122                       ConstantInt::get(IntptrTy, j - i)});
3123       Done = j;
3124     }
3125   }
3126 
3127   copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
3128 }
3129 
3130 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
3131 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
3132 static int StackMallocSizeClass(uint64_t LocalStackSize) {
3133   assert(LocalStackSize <= kMaxStackMallocSize);
3134   uint64_t MaxSize = kMinStackMallocSize;
3135   for (int i = 0;; i++, MaxSize *= 2)
3136     if (LocalStackSize <= MaxSize) return i;
3137   llvm_unreachable("impossible LocalStackSize");
3138 }
3139 
3140 void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
3141   Instruction *CopyInsertPoint = &F.front().front();
3142   if (CopyInsertPoint == ASan.LocalDynamicShadow) {
3143     // Insert after the dynamic shadow location is determined
3144     CopyInsertPoint = CopyInsertPoint->getNextNode();
3145     assert(CopyInsertPoint);
3146   }
3147   IRBuilder<> IRB(CopyInsertPoint);
3148   const DataLayout &DL = F.getParent()->getDataLayout();
3149   for (Argument &Arg : F.args()) {
3150     if (Arg.hasByValAttr()) {
3151       Type *Ty = Arg.getParamByValType();
3152       const Align Alignment =
3153           DL.getValueOrABITypeAlignment(Arg.getParamAlign(), Ty);
3154 
3155       AllocaInst *AI = IRB.CreateAlloca(
3156           Ty, nullptr,
3157           (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
3158               ".byval");
3159       AI->setAlignment(Alignment);
3160       Arg.replaceAllUsesWith(AI);
3161 
3162       uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3163       IRB.CreateMemCpy(AI, Alignment, &Arg, Alignment, AllocSize);
3164     }
3165   }
3166 }
3167 
3168 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
3169                                           Value *ValueIfTrue,
3170                                           Instruction *ThenTerm,
3171                                           Value *ValueIfFalse) {
3172   PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
3173   BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
3174   PHI->addIncoming(ValueIfFalse, CondBlock);
3175   BasicBlock *ThenBlock = ThenTerm->getParent();
3176   PHI->addIncoming(ValueIfTrue, ThenBlock);
3177   return PHI;
3178 }
3179 
3180 Value *FunctionStackPoisoner::createAllocaForLayout(
3181     IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
3182   AllocaInst *Alloca;
3183   if (Dynamic) {
3184     Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
3185                               ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
3186                               "MyAlloca");
3187   } else {
3188     Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
3189                               nullptr, "MyAlloca");
3190     assert(Alloca->isStaticAlloca());
3191   }
3192   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
3193   uint64_t FrameAlignment = std::max(L.FrameAlignment, uint64_t(ClRealignStack));
3194   Alloca->setAlignment(Align(FrameAlignment));
3195   return IRB.CreatePointerCast(Alloca, IntptrTy);
3196 }
3197 
3198 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
3199   BasicBlock &FirstBB = *F.begin();
3200   IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
3201   DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
3202   IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
3203   DynamicAllocaLayout->setAlignment(Align(32));
3204 }
3205 
3206 void FunctionStackPoisoner::processDynamicAllocas() {
3207   if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
3208     assert(DynamicAllocaPoisonCallVec.empty());
3209     return;
3210   }
3211 
3212   // Insert poison calls for lifetime intrinsics for dynamic allocas.
3213   for (const auto &APC : DynamicAllocaPoisonCallVec) {
3214     assert(APC.InsBefore);
3215     assert(APC.AI);
3216     assert(ASan.isInterestingAlloca(*APC.AI));
3217     assert(!APC.AI->isStaticAlloca());
3218 
3219     IRBuilder<> IRB(APC.InsBefore);
3220     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
3221     // Dynamic allocas will be unpoisoned unconditionally below in
3222     // unpoisonDynamicAllocas.
3223     // Flag that we need unpoison static allocas.
3224   }
3225 
3226   // Handle dynamic allocas.
3227   createDynamicAllocasInitStorage();
3228   for (auto &AI : DynamicAllocaVec)
3229     handleDynamicAllocaCall(AI);
3230   unpoisonDynamicAllocas();
3231 }
3232 
3233 /// Collect instructions in the entry block after \p InsBefore which initialize
3234 /// permanent storage for a function argument. These instructions must remain in
3235 /// the entry block so that uninitialized values do not appear in backtraces. An
3236 /// added benefit is that this conserves spill slots. This does not move stores
3237 /// before instrumented / "interesting" allocas.
3238 static void findStoresToUninstrumentedArgAllocas(
3239     AddressSanitizer &ASan, Instruction &InsBefore,
3240     SmallVectorImpl<Instruction *> &InitInsts) {
3241   Instruction *Start = InsBefore.getNextNonDebugInstruction();
3242   for (Instruction *It = Start; It; It = It->getNextNonDebugInstruction()) {
3243     // Argument initialization looks like:
3244     // 1) store <Argument>, <Alloca> OR
3245     // 2) <CastArgument> = cast <Argument> to ...
3246     //    store <CastArgument> to <Alloca>
3247     // Do not consider any other kind of instruction.
3248     //
3249     // Note: This covers all known cases, but may not be exhaustive. An
3250     // alternative to pattern-matching stores is to DFS over all Argument uses:
3251     // this might be more general, but is probably much more complicated.
3252     if (isa<AllocaInst>(It) || isa<CastInst>(It))
3253       continue;
3254     if (auto *Store = dyn_cast<StoreInst>(It)) {
3255       // The store destination must be an alloca that isn't interesting for
3256       // ASan to instrument. These are moved up before InsBefore, and they're
3257       // not interesting because allocas for arguments can be mem2reg'd.
3258       auto *Alloca = dyn_cast<AllocaInst>(Store->getPointerOperand());
3259       if (!Alloca || ASan.isInterestingAlloca(*Alloca))
3260         continue;
3261 
3262       Value *Val = Store->getValueOperand();
3263       bool IsDirectArgInit = isa<Argument>(Val);
3264       bool IsArgInitViaCast =
3265           isa<CastInst>(Val) &&
3266           isa<Argument>(cast<CastInst>(Val)->getOperand(0)) &&
3267           // Check that the cast appears directly before the store. Otherwise
3268           // moving the cast before InsBefore may break the IR.
3269           Val == It->getPrevNonDebugInstruction();
3270       bool IsArgInit = IsDirectArgInit || IsArgInitViaCast;
3271       if (!IsArgInit)
3272         continue;
3273 
3274       if (IsArgInitViaCast)
3275         InitInsts.push_back(cast<Instruction>(Val));
3276       InitInsts.push_back(Store);
3277       continue;
3278     }
3279 
3280     // Do not reorder past unknown instructions: argument initialization should
3281     // only involve casts and stores.
3282     return;
3283   }
3284 }
3285 
3286 void FunctionStackPoisoner::processStaticAllocas() {
3287   if (AllocaVec.empty()) {
3288     assert(StaticAllocaPoisonCallVec.empty());
3289     return;
3290   }
3291 
3292   int StackMallocIdx = -1;
3293   DebugLoc EntryDebugLocation;
3294   if (auto SP = F.getSubprogram())
3295     EntryDebugLocation =
3296         DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
3297 
3298   Instruction *InsBefore = AllocaVec[0];
3299   IRBuilder<> IRB(InsBefore);
3300 
3301   // Make sure non-instrumented allocas stay in the entry block. Otherwise,
3302   // debug info is broken, because only entry-block allocas are treated as
3303   // regular stack slots.
3304   auto InsBeforeB = InsBefore->getParent();
3305   assert(InsBeforeB == &F.getEntryBlock());
3306   for (auto *AI : StaticAllocasToMoveUp)
3307     if (AI->getParent() == InsBeforeB)
3308       AI->moveBefore(InsBefore);
3309 
3310   // Move stores of arguments into entry-block allocas as well. This prevents
3311   // extra stack slots from being generated (to house the argument values until
3312   // they can be stored into the allocas). This also prevents uninitialized
3313   // values from being shown in backtraces.
3314   SmallVector<Instruction *, 8> ArgInitInsts;
3315   findStoresToUninstrumentedArgAllocas(ASan, *InsBefore, ArgInitInsts);
3316   for (Instruction *ArgInitInst : ArgInitInsts)
3317     ArgInitInst->moveBefore(InsBefore);
3318 
3319   // If we have a call to llvm.localescape, keep it in the entry block.
3320   if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
3321 
3322   SmallVector<ASanStackVariableDescription, 16> SVD;
3323   SVD.reserve(AllocaVec.size());
3324   for (AllocaInst *AI : AllocaVec) {
3325     ASanStackVariableDescription D = {AI->getName().data(),
3326                                       ASan.getAllocaSizeInBytes(*AI),
3327                                       0,
3328                                       AI->getAlignment(),
3329                                       AI,
3330                                       0,
3331                                       0};
3332     SVD.push_back(D);
3333   }
3334 
3335   // Minimal header size (left redzone) is 4 pointers,
3336   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
3337   uint64_t Granularity = 1ULL << Mapping.Scale;
3338   uint64_t MinHeaderSize = std::max((uint64_t)ASan.LongSize / 2, Granularity);
3339   const ASanStackFrameLayout &L =
3340       ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
3341 
3342   // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
3343   DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
3344   for (auto &Desc : SVD)
3345     AllocaToSVDMap[Desc.AI] = &Desc;
3346 
3347   // Update SVD with information from lifetime intrinsics.
3348   for (const auto &APC : StaticAllocaPoisonCallVec) {
3349     assert(APC.InsBefore);
3350     assert(APC.AI);
3351     assert(ASan.isInterestingAlloca(*APC.AI));
3352     assert(APC.AI->isStaticAlloca());
3353 
3354     ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3355     Desc.LifetimeSize = Desc.Size;
3356     if (const DILocation *FnLoc = EntryDebugLocation.get()) {
3357       if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
3358         if (LifetimeLoc->getFile() == FnLoc->getFile())
3359           if (unsigned Line = LifetimeLoc->getLine())
3360             Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
3361       }
3362     }
3363   }
3364 
3365   auto DescriptionString = ComputeASanStackFrameDescription(SVD);
3366   LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
3367   uint64_t LocalStackSize = L.FrameSize;
3368   bool DoStackMalloc =
3369       ASan.UseAfterReturn != AsanDetectStackUseAfterReturnMode::Never &&
3370       !ASan.CompileKernel && LocalStackSize <= kMaxStackMallocSize;
3371   bool DoDynamicAlloca = ClDynamicAllocaStack;
3372   // Don't do dynamic alloca or stack malloc if:
3373   // 1) There is inline asm: too often it makes assumptions on which registers
3374   //    are available.
3375   // 2) There is a returns_twice call (typically setjmp), which is
3376   //    optimization-hostile, and doesn't play well with introduced indirect
3377   //    register-relative calculation of local variable addresses.
3378   DoDynamicAlloca &= !HasInlineAsm && !HasReturnsTwiceCall;
3379   DoStackMalloc &= !HasInlineAsm && !HasReturnsTwiceCall;
3380 
3381   Value *StaticAlloca =
3382       DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
3383 
3384   Value *FakeStack;
3385   Value *LocalStackBase;
3386   Value *LocalStackBaseAlloca;
3387   uint8_t DIExprFlags = DIExpression::ApplyOffset;
3388 
3389   if (DoStackMalloc) {
3390     LocalStackBaseAlloca =
3391         IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
3392     if (ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Runtime) {
3393       // void *FakeStack = __asan_option_detect_stack_use_after_return
3394       //     ? __asan_stack_malloc_N(LocalStackSize)
3395       //     : nullptr;
3396       // void *LocalStackBase = (FakeStack) ? FakeStack :
3397       //                        alloca(LocalStackSize);
3398       Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
3399           kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
3400       Value *UseAfterReturnIsEnabled = IRB.CreateICmpNE(
3401           IRB.CreateLoad(IRB.getInt32Ty(), OptionDetectUseAfterReturn),
3402           Constant::getNullValue(IRB.getInt32Ty()));
3403       Instruction *Term =
3404           SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
3405       IRBuilder<> IRBIf(Term);
3406       StackMallocIdx = StackMallocSizeClass(LocalStackSize);
3407       assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
3408       Value *FakeStackValue =
3409           IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
3410                            ConstantInt::get(IntptrTy, LocalStackSize));
3411       IRB.SetInsertPoint(InsBefore);
3412       FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
3413                             ConstantInt::get(IntptrTy, 0));
3414     } else {
3415       // assert(ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode:Always)
3416       // void *FakeStack = __asan_stack_malloc_N(LocalStackSize);
3417       // void *LocalStackBase = (FakeStack) ? FakeStack :
3418       //                        alloca(LocalStackSize);
3419       StackMallocIdx = StackMallocSizeClass(LocalStackSize);
3420       FakeStack = IRB.CreateCall(AsanStackMallocFunc[StackMallocIdx],
3421                                  ConstantInt::get(IntptrTy, LocalStackSize));
3422     }
3423     Value *NoFakeStack =
3424         IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
3425     Instruction *Term =
3426         SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
3427     IRBuilder<> IRBIf(Term);
3428     Value *AllocaValue =
3429         DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
3430 
3431     IRB.SetInsertPoint(InsBefore);
3432     LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
3433     IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
3434     DIExprFlags |= DIExpression::DerefBefore;
3435   } else {
3436     // void *FakeStack = nullptr;
3437     // void *LocalStackBase = alloca(LocalStackSize);
3438     FakeStack = ConstantInt::get(IntptrTy, 0);
3439     LocalStackBase =
3440         DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
3441     LocalStackBaseAlloca = LocalStackBase;
3442   }
3443 
3444   // It shouldn't matter whether we pass an `alloca` or a `ptrtoint` as the
3445   // dbg.declare address opereand, but passing a `ptrtoint` seems to confuse
3446   // later passes and can result in dropped variable coverage in debug info.
3447   Value *LocalStackBaseAllocaPtr =
3448       isa<PtrToIntInst>(LocalStackBaseAlloca)
3449           ? cast<PtrToIntInst>(LocalStackBaseAlloca)->getPointerOperand()
3450           : LocalStackBaseAlloca;
3451   assert(isa<AllocaInst>(LocalStackBaseAllocaPtr) &&
3452          "Variable descriptions relative to ASan stack base will be dropped");
3453 
3454   // Replace Alloca instructions with base+offset.
3455   for (const auto &Desc : SVD) {
3456     AllocaInst *AI = Desc.AI;
3457     replaceDbgDeclare(AI, LocalStackBaseAllocaPtr, DIB, DIExprFlags,
3458                       Desc.Offset);
3459     Value *NewAllocaPtr = IRB.CreateIntToPtr(
3460         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
3461         AI->getType());
3462     AI->replaceAllUsesWith(NewAllocaPtr);
3463   }
3464 
3465   // The left-most redzone has enough space for at least 4 pointers.
3466   // Write the Magic value to redzone[0].
3467   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
3468   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
3469                   BasePlus0);
3470   // Write the frame description constant to redzone[1].
3471   Value *BasePlus1 = IRB.CreateIntToPtr(
3472       IRB.CreateAdd(LocalStackBase,
3473                     ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
3474       IntptrPtrTy);
3475   GlobalVariable *StackDescriptionGlobal =
3476       createPrivateGlobalForString(*F.getParent(), DescriptionString,
3477                                    /*AllowMerging*/ true, kAsanGenPrefix);
3478   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
3479   IRB.CreateStore(Description, BasePlus1);
3480   // Write the PC to redzone[2].
3481   Value *BasePlus2 = IRB.CreateIntToPtr(
3482       IRB.CreateAdd(LocalStackBase,
3483                     ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
3484       IntptrPtrTy);
3485   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
3486 
3487   const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
3488 
3489   // Poison the stack red zones at the entry.
3490   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
3491   // As mask we must use most poisoned case: red zones and after scope.
3492   // As bytes we can use either the same or just red zones only.
3493   copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3494 
3495   if (!StaticAllocaPoisonCallVec.empty()) {
3496     const auto &ShadowInScope = GetShadowBytes(SVD, L);
3497 
3498     // Poison static allocas near lifetime intrinsics.
3499     for (const auto &APC : StaticAllocaPoisonCallVec) {
3500       const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3501       assert(Desc.Offset % L.Granularity == 0);
3502       size_t Begin = Desc.Offset / L.Granularity;
3503       size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
3504 
3505       IRBuilder<> IRB(APC.InsBefore);
3506       copyToShadow(ShadowAfterScope,
3507                    APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3508                    IRB, ShadowBase);
3509     }
3510   }
3511 
3512   SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
3513   SmallVector<uint8_t, 64> ShadowAfterReturn;
3514 
3515   // (Un)poison the stack before all ret instructions.
3516   for (Instruction *Ret : RetVec) {
3517     IRBuilder<> IRBRet(Ret);
3518     // Mark the current frame as retired.
3519     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3520                        BasePlus0);
3521     if (DoStackMalloc) {
3522       assert(StackMallocIdx >= 0);
3523       // if FakeStack != 0  // LocalStackBase == FakeStack
3524       //     // In use-after-return mode, poison the whole stack frame.
3525       //     if StackMallocIdx <= 4
3526       //         // For small sizes inline the whole thing:
3527       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
3528       //         **SavedFlagPtr(FakeStack) = 0
3529       //     else
3530       //         __asan_stack_free_N(FakeStack, LocalStackSize)
3531       // else
3532       //     <This is not a fake stack; unpoison the redzones>
3533       Value *Cmp =
3534           IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
3535       Instruction *ThenTerm, *ElseTerm;
3536       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3537 
3538       IRBuilder<> IRBPoison(ThenTerm);
3539       if (StackMallocIdx <= 4) {
3540         int ClassSize = kMinStackMallocSize << StackMallocIdx;
3541         ShadowAfterReturn.resize(ClassSize / L.Granularity,
3542                                  kAsanStackUseAfterReturnMagic);
3543         copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3544                      ShadowBase);
3545         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
3546             FakeStack,
3547             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3548         Value *SavedFlagPtr = IRBPoison.CreateLoad(
3549             IntptrTy, IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3550         IRBPoison.CreateStore(
3551             Constant::getNullValue(IRBPoison.getInt8Ty()),
3552             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3553       } else {
3554         // For larger frames call __asan_stack_free_*.
3555         IRBPoison.CreateCall(
3556             AsanStackFreeFunc[StackMallocIdx],
3557             {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
3558       }
3559 
3560       IRBuilder<> IRBElse(ElseTerm);
3561       copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
3562     } else {
3563       copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
3564     }
3565   }
3566 
3567   // We are done. Remove the old unused alloca instructions.
3568   for (auto AI : AllocaVec) AI->eraseFromParent();
3569 }
3570 
3571 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
3572                                          IRBuilder<> &IRB, bool DoPoison) {
3573   // For now just insert the call to ASan runtime.
3574   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3575   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
3576   IRB.CreateCall(
3577       DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3578       {AddrArg, SizeArg});
3579 }
3580 
3581 // Handling llvm.lifetime intrinsics for a given %alloca:
3582 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3583 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3584 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3585 //     could be poisoned by previous llvm.lifetime.end instruction, as the
3586 //     variable may go in and out of scope several times, e.g. in loops).
3587 // (3) if we poisoned at least one %alloca in a function,
3588 //     unpoison the whole stack frame at function exit.
3589 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
3590   IRBuilder<> IRB(AI);
3591 
3592   const uint64_t Alignment = std::max(kAllocaRzSize, AI->getAlignment());
3593   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3594 
3595   Value *Zero = Constant::getNullValue(IntptrTy);
3596   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3597   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
3598 
3599   // Since we need to extend alloca with additional memory to locate
3600   // redzones, and OldSize is number of allocated blocks with
3601   // ElementSize size, get allocated memory size in bytes by
3602   // OldSize * ElementSize.
3603   const unsigned ElementSize =
3604       F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
3605   Value *OldSize =
3606       IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3607                     ConstantInt::get(IntptrTy, ElementSize));
3608 
3609   // PartialSize = OldSize % 32
3610   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3611 
3612   // Misalign = kAllocaRzSize - PartialSize;
3613   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3614 
3615   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3616   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3617   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3618 
3619   // AdditionalChunkSize = Alignment + PartialPadding + kAllocaRzSize
3620   // Alignment is added to locate left redzone, PartialPadding for possible
3621   // partial redzone and kAllocaRzSize for right redzone respectively.
3622   Value *AdditionalChunkSize = IRB.CreateAdd(
3623       ConstantInt::get(IntptrTy, Alignment + kAllocaRzSize), PartialPadding);
3624 
3625   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3626 
3627   // Insert new alloca with new NewSize and Alignment params.
3628   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3629   NewAlloca->setAlignment(Align(Alignment));
3630 
3631   // NewAddress = Address + Alignment
3632   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3633                                     ConstantInt::get(IntptrTy, Alignment));
3634 
3635   // Insert __asan_alloca_poison call for new created alloca.
3636   IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
3637 
3638   // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3639   // for unpoisoning stuff.
3640   IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3641 
3642   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3643 
3644   // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
3645   AI->replaceAllUsesWith(NewAddressPtr);
3646 
3647   // We are done. Erase old alloca from parent.
3648   AI->eraseFromParent();
3649 }
3650 
3651 // isSafeAccess returns true if Addr is always inbounds with respect to its
3652 // base object. For example, it is a field access or an array access with
3653 // constant inbounds index.
3654 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3655                                     Value *Addr, uint64_t TypeSize) const {
3656   SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3657   if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
3658   uint64_t Size = SizeOffset.first.getZExtValue();
3659   int64_t Offset = SizeOffset.second.getSExtValue();
3660   // Three checks are required to ensure safety:
3661   // . Offset >= 0  (since the offset is given from the base ptr)
3662   // . Size >= Offset  (unsigned)
3663   // . Size - Offset >= NeededSize  (unsigned)
3664   return Offset >= 0 && Size >= uint64_t(Offset) &&
3665          Size - uint64_t(Offset) >= TypeSize / 8;
3666 }
3667