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