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