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