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