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