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