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 uint64_t kAllocaRzSize = 32;
180 
181 // ASanAccessInfo implementation constants.
182 constexpr size_t kCompileKernelShift = 0;
183 constexpr size_t kCompileKernelMask = 0x1;
184 constexpr size_t kAccessSizeIndexShift = 1;
185 constexpr size_t kAccessSizeIndexMask = 0xf;
186 constexpr size_t kIsWriteShift = 5;
187 constexpr size_t kIsWriteMask = 0x1;
188 
189 // Command-line flags.
190 
191 static cl::opt<bool> ClEnableKasan(
192     "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
193     cl::Hidden, cl::init(false));
194 
195 static cl::opt<bool> ClRecover(
196     "asan-recover",
197     cl::desc("Enable recovery mode (continue-after-error)."),
198     cl::Hidden, cl::init(false));
199 
200 static cl::opt<bool> ClInsertVersionCheck(
201     "asan-guard-against-version-mismatch",
202     cl::desc("Guard against compiler/runtime version mismatch."),
203     cl::Hidden, cl::init(true));
204 
205 // This flag may need to be replaced with -f[no-]asan-reads.
206 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
207                                        cl::desc("instrument read instructions"),
208                                        cl::Hidden, cl::init(true));
209 
210 static cl::opt<bool> ClInstrumentWrites(
211     "asan-instrument-writes", cl::desc("instrument write instructions"),
212     cl::Hidden, cl::init(true));
213 
214 static cl::opt<bool> 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.contains("__llvm") || Section.contains("__LLVM"))
2007       return false;
2008 
2009     // Do not instrument function pointers to initialization and termination
2010     // routines: dynamic linker will not properly handle redzones.
2011     if (Section.startswith(".preinit_array") ||
2012         Section.startswith(".init_array") ||
2013         Section.startswith(".fini_array")) {
2014       return false;
2015     }
2016 
2017     // Do not instrument user-defined sections (with names resembling
2018     // valid C identifiers)
2019     if (TargetTriple.isOSBinFormatELF()) {
2020       if (llvm::all_of(Section,
2021                        [](char c) { return llvm::isAlnum(c) || c == '_'; }))
2022         return false;
2023     }
2024 
2025     // On COFF, if the section name contains '$', it is highly likely that the
2026     // user is using section sorting to create an array of globals similar to
2027     // the way initialization callbacks are registered in .init_array and
2028     // .CRT$XCU. The ATL also registers things in .ATL$__[azm]. Adding redzones
2029     // to such globals is counterproductive, because the intent is that they
2030     // will form an array, and out-of-bounds accesses are expected.
2031     // See https://github.com/google/sanitizers/issues/305
2032     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
2033     if (TargetTriple.isOSBinFormatCOFF() && Section.contains('$')) {
2034       LLVM_DEBUG(dbgs() << "Ignoring global in sorted section (contains '$'): "
2035                         << *G << "\n");
2036       return false;
2037     }
2038 
2039     if (TargetTriple.isOSBinFormatMachO()) {
2040       StringRef ParsedSegment, ParsedSection;
2041       unsigned TAA = 0, StubSize = 0;
2042       bool TAAParsed;
2043       cantFail(MCSectionMachO::ParseSectionSpecifier(
2044           Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize));
2045 
2046       // Ignore the globals from the __OBJC section. The ObjC runtime assumes
2047       // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
2048       // them.
2049       if (ParsedSegment == "__OBJC" ||
2050           (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
2051         LLVM_DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
2052         return false;
2053       }
2054       // See https://github.com/google/sanitizers/issues/32
2055       // Constant CFString instances are compiled in the following way:
2056       //  -- the string buffer is emitted into
2057       //     __TEXT,__cstring,cstring_literals
2058       //  -- the constant NSConstantString structure referencing that buffer
2059       //     is placed into __DATA,__cfstring
2060       // Therefore there's no point in placing redzones into __DATA,__cfstring.
2061       // Moreover, it causes the linker to crash on OS X 10.7
2062       if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
2063         LLVM_DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
2064         return false;
2065       }
2066       // The linker merges the contents of cstring_literals and removes the
2067       // trailing zeroes.
2068       if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
2069         LLVM_DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
2070         return false;
2071       }
2072     }
2073   }
2074 
2075   if (CompileKernel) {
2076     // Globals that prefixed by "__" are special and cannot be padded with a
2077     // redzone.
2078     if (G->getName().startswith("__"))
2079       return false;
2080   }
2081 
2082   return true;
2083 }
2084 
2085 // On Mach-O platforms, we emit global metadata in a separate section of the
2086 // binary in order to allow the linker to properly dead strip. This is only
2087 // supported on recent versions of ld64.
2088 bool ModuleAddressSanitizer::ShouldUseMachOGlobalsSection() const {
2089   if (!TargetTriple.isOSBinFormatMachO())
2090     return false;
2091 
2092   if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
2093     return true;
2094   if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
2095     return true;
2096   if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
2097     return true;
2098 
2099   return false;
2100 }
2101 
2102 StringRef ModuleAddressSanitizer::getGlobalMetadataSection() const {
2103   switch (TargetTriple.getObjectFormat()) {
2104   case Triple::COFF:  return ".ASAN$GL";
2105   case Triple::ELF:   return "asan_globals";
2106   case Triple::MachO: return "__DATA,__asan_globals,regular";
2107   case Triple::Wasm:
2108   case Triple::GOFF:
2109   case Triple::XCOFF:
2110     report_fatal_error(
2111         "ModuleAddressSanitizer not implemented for object file format");
2112   case Triple::UnknownObjectFormat:
2113     break;
2114   }
2115   llvm_unreachable("unsupported object format");
2116 }
2117 
2118 void ModuleAddressSanitizer::initializeCallbacks(Module &M) {
2119   IRBuilder<> IRB(*C);
2120 
2121   // Declare our poisoning and unpoisoning functions.
2122   AsanPoisonGlobals =
2123       M.getOrInsertFunction(kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy);
2124   AsanUnpoisonGlobals =
2125       M.getOrInsertFunction(kAsanUnpoisonGlobalsName, IRB.getVoidTy());
2126 
2127   // Declare functions that register/unregister globals.
2128   AsanRegisterGlobals = M.getOrInsertFunction(
2129       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2130   AsanUnregisterGlobals = M.getOrInsertFunction(
2131       kAsanUnregisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2132 
2133   // Declare the functions that find globals in a shared object and then invoke
2134   // the (un)register function on them.
2135   AsanRegisterImageGlobals = M.getOrInsertFunction(
2136       kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
2137   AsanUnregisterImageGlobals = M.getOrInsertFunction(
2138       kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
2139 
2140   AsanRegisterElfGlobals =
2141       M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
2142                             IntptrTy, IntptrTy, IntptrTy);
2143   AsanUnregisterElfGlobals =
2144       M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
2145                             IntptrTy, IntptrTy, IntptrTy);
2146 }
2147 
2148 // Put the metadata and the instrumented global in the same group. This ensures
2149 // that the metadata is discarded if the instrumented global is discarded.
2150 void ModuleAddressSanitizer::SetComdatForGlobalMetadata(
2151     GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
2152   Module &M = *G->getParent();
2153   Comdat *C = G->getComdat();
2154   if (!C) {
2155     if (!G->hasName()) {
2156       // If G is unnamed, it must be internal. Give it an artificial name
2157       // so we can put it in a comdat.
2158       assert(G->hasLocalLinkage());
2159       G->setName(Twine(kAsanGenPrefix) + "_anon_global");
2160     }
2161 
2162     if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
2163       std::string Name = std::string(G->getName());
2164       Name += InternalSuffix;
2165       C = M.getOrInsertComdat(Name);
2166     } else {
2167       C = M.getOrInsertComdat(G->getName());
2168     }
2169 
2170     // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
2171     // linkage to internal linkage so that a symbol table entry is emitted. This
2172     // is necessary in order to create the comdat group.
2173     if (TargetTriple.isOSBinFormatCOFF()) {
2174       C->setSelectionKind(Comdat::NoDeduplicate);
2175       if (G->hasPrivateLinkage())
2176         G->setLinkage(GlobalValue::InternalLinkage);
2177     }
2178     G->setComdat(C);
2179   }
2180 
2181   assert(G->hasComdat());
2182   Metadata->setComdat(G->getComdat());
2183 }
2184 
2185 // Create a separate metadata global and put it in the appropriate ASan
2186 // global registration section.
2187 GlobalVariable *
2188 ModuleAddressSanitizer::CreateMetadataGlobal(Module &M, Constant *Initializer,
2189                                              StringRef OriginalName) {
2190   auto Linkage = TargetTriple.isOSBinFormatMachO()
2191                      ? GlobalVariable::InternalLinkage
2192                      : GlobalVariable::PrivateLinkage;
2193   GlobalVariable *Metadata = new GlobalVariable(
2194       M, Initializer->getType(), false, Linkage, Initializer,
2195       Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
2196   Metadata->setSection(getGlobalMetadataSection());
2197   return Metadata;
2198 }
2199 
2200 Instruction *ModuleAddressSanitizer::CreateAsanModuleDtor(Module &M) {
2201   AsanDtorFunction = Function::createWithDefaultAttr(
2202       FunctionType::get(Type::getVoidTy(*C), false),
2203       GlobalValue::InternalLinkage, 0, kAsanModuleDtorName, &M);
2204   AsanDtorFunction->addFnAttr(Attribute::NoUnwind);
2205   // Ensure Dtor cannot be discarded, even if in a comdat.
2206   appendToUsed(M, {AsanDtorFunction});
2207   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
2208 
2209   return ReturnInst::Create(*C, AsanDtorBB);
2210 }
2211 
2212 void ModuleAddressSanitizer::InstrumentGlobalsCOFF(
2213     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2214     ArrayRef<Constant *> MetadataInitializers) {
2215   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2216   auto &DL = M.getDataLayout();
2217 
2218   SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2219   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2220     Constant *Initializer = MetadataInitializers[i];
2221     GlobalVariable *G = ExtendedGlobals[i];
2222     GlobalVariable *Metadata =
2223         CreateMetadataGlobal(M, Initializer, G->getName());
2224     MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2225     Metadata->setMetadata(LLVMContext::MD_associated, MD);
2226     MetadataGlobals[i] = Metadata;
2227 
2228     // The MSVC linker always inserts padding when linking incrementally. We
2229     // cope with that by aligning each struct to its size, which must be a power
2230     // of two.
2231     unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
2232     assert(isPowerOf2_32(SizeOfGlobalStruct) &&
2233            "global metadata will not be padded appropriately");
2234     Metadata->setAlignment(assumeAligned(SizeOfGlobalStruct));
2235 
2236     SetComdatForGlobalMetadata(G, Metadata, "");
2237   }
2238 
2239   // Update llvm.compiler.used, adding the new metadata globals. This is
2240   // needed so that during LTO these variables stay alive.
2241   if (!MetadataGlobals.empty())
2242     appendToCompilerUsed(M, MetadataGlobals);
2243 }
2244 
2245 void ModuleAddressSanitizer::InstrumentGlobalsELF(
2246     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2247     ArrayRef<Constant *> MetadataInitializers,
2248     const std::string &UniqueModuleId) {
2249   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2250 
2251   // Putting globals in a comdat changes the semantic and potentially cause
2252   // false negative odr violations at link time. If odr indicators are used, we
2253   // keep the comdat sections, as link time odr violations will be dectected on
2254   // the odr indicator symbols.
2255   bool UseComdatForGlobalsGC = UseOdrIndicator;
2256 
2257   SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2258   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2259     GlobalVariable *G = ExtendedGlobals[i];
2260     GlobalVariable *Metadata =
2261         CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
2262     MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2263     Metadata->setMetadata(LLVMContext::MD_associated, MD);
2264     MetadataGlobals[i] = Metadata;
2265 
2266     if (UseComdatForGlobalsGC)
2267       SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
2268   }
2269 
2270   // Update llvm.compiler.used, adding the new metadata globals. This is
2271   // needed so that during LTO these variables stay alive.
2272   if (!MetadataGlobals.empty())
2273     appendToCompilerUsed(M, MetadataGlobals);
2274 
2275   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2276   // to look up the loaded image that contains it. Second, we can store in it
2277   // whether registration has already occurred, to prevent duplicate
2278   // registration.
2279   //
2280   // Common linkage ensures that there is only one global per shared library.
2281   GlobalVariable *RegisteredFlag = new GlobalVariable(
2282       M, IntptrTy, false, GlobalVariable::CommonLinkage,
2283       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2284   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2285 
2286   // Create start and stop symbols.
2287   GlobalVariable *StartELFMetadata = new GlobalVariable(
2288       M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2289       "__start_" + getGlobalMetadataSection());
2290   StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
2291   GlobalVariable *StopELFMetadata = new GlobalVariable(
2292       M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2293       "__stop_" + getGlobalMetadataSection());
2294   StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
2295 
2296   // Create a call to register the globals with the runtime.
2297   IRB.CreateCall(AsanRegisterElfGlobals,
2298                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2299                   IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2300                   IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2301 
2302   // We also need to unregister globals at the end, e.g., when a shared library
2303   // gets closed.
2304   if (DestructorKind != AsanDtorKind::None) {
2305     IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2306     IrbDtor.CreateCall(AsanUnregisterElfGlobals,
2307                        {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2308                         IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2309                         IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2310   }
2311 }
2312 
2313 void ModuleAddressSanitizer::InstrumentGlobalsMachO(
2314     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2315     ArrayRef<Constant *> MetadataInitializers) {
2316   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2317 
2318   // On recent Mach-O platforms, use a structure which binds the liveness of
2319   // the global variable to the metadata struct. Keep the list of "Liveness" GV
2320   // created to be added to llvm.compiler.used
2321   StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
2322   SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
2323 
2324   for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2325     Constant *Initializer = MetadataInitializers[i];
2326     GlobalVariable *G = ExtendedGlobals[i];
2327     GlobalVariable *Metadata =
2328         CreateMetadataGlobal(M, Initializer, G->getName());
2329 
2330     // On recent Mach-O platforms, we emit the global metadata in a way that
2331     // allows the linker to properly strip dead globals.
2332     auto LivenessBinder =
2333         ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
2334                             ConstantExpr::getPointerCast(Metadata, IntptrTy));
2335     GlobalVariable *Liveness = new GlobalVariable(
2336         M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
2337         Twine("__asan_binder_") + G->getName());
2338     Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
2339     LivenessGlobals[i] = Liveness;
2340   }
2341 
2342   // Update llvm.compiler.used, adding the new liveness globals. This is
2343   // needed so that during LTO these variables stay alive. The alternative
2344   // would be to have the linker handling the LTO symbols, but libLTO
2345   // current API does not expose access to the section for each symbol.
2346   if (!LivenessGlobals.empty())
2347     appendToCompilerUsed(M, LivenessGlobals);
2348 
2349   // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2350   // to look up the loaded image that contains it. Second, we can store in it
2351   // whether registration has already occurred, to prevent duplicate
2352   // registration.
2353   //
2354   // common linkage ensures that there is only one global per shared library.
2355   GlobalVariable *RegisteredFlag = new GlobalVariable(
2356       M, IntptrTy, false, GlobalVariable::CommonLinkage,
2357       ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2358   RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2359 
2360   IRB.CreateCall(AsanRegisterImageGlobals,
2361                  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2362 
2363   // We also need to unregister globals at the end, e.g., when a shared library
2364   // gets closed.
2365   if (DestructorKind != AsanDtorKind::None) {
2366     IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2367     IrbDtor.CreateCall(AsanUnregisterImageGlobals,
2368                        {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2369   }
2370 }
2371 
2372 void ModuleAddressSanitizer::InstrumentGlobalsWithMetadataArray(
2373     IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2374     ArrayRef<Constant *> MetadataInitializers) {
2375   assert(ExtendedGlobals.size() == MetadataInitializers.size());
2376   unsigned N = ExtendedGlobals.size();
2377   assert(N > 0);
2378 
2379   // On platforms that don't have a custom metadata section, we emit an array
2380   // of global metadata structures.
2381   ArrayType *ArrayOfGlobalStructTy =
2382       ArrayType::get(MetadataInitializers[0]->getType(), N);
2383   auto AllGlobals = new GlobalVariable(
2384       M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
2385       ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
2386   if (Mapping.Scale > 3)
2387     AllGlobals->setAlignment(Align(1ULL << Mapping.Scale));
2388 
2389   IRB.CreateCall(AsanRegisterGlobals,
2390                  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2391                   ConstantInt::get(IntptrTy, N)});
2392 
2393   // We also need to unregister globals at the end, e.g., when a shared library
2394   // gets closed.
2395   if (DestructorKind != AsanDtorKind::None) {
2396     IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2397     IrbDtor.CreateCall(AsanUnregisterGlobals,
2398                        {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2399                         ConstantInt::get(IntptrTy, N)});
2400   }
2401 }
2402 
2403 // This function replaces all global variables with new variables that have
2404 // trailing redzones. It also creates a function that poisons
2405 // redzones and inserts this function into llvm.global_ctors.
2406 // Sets *CtorComdat to true if the global registration code emitted into the
2407 // asan constructor is comdat-compatible.
2408 bool ModuleAddressSanitizer::InstrumentGlobals(IRBuilder<> &IRB, Module &M,
2409                                                bool *CtorComdat) {
2410   *CtorComdat = false;
2411 
2412   // Build set of globals that are aliased by some GA, where
2413   // getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.
2414   SmallPtrSet<const GlobalVariable *, 16> AliasedGlobalExclusions;
2415   if (CompileKernel) {
2416     for (auto &GA : M.aliases()) {
2417       if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))
2418         AliasedGlobalExclusions.insert(GV);
2419     }
2420   }
2421 
2422   SmallVector<GlobalVariable *, 16> GlobalsToChange;
2423   for (auto &G : M.globals()) {
2424     if (!AliasedGlobalExclusions.count(&G) && shouldInstrumentGlobal(&G))
2425       GlobalsToChange.push_back(&G);
2426   }
2427 
2428   size_t n = GlobalsToChange.size();
2429   if (n == 0) {
2430     *CtorComdat = true;
2431     return false;
2432   }
2433 
2434   auto &DL = M.getDataLayout();
2435 
2436   // A global is described by a structure
2437   //   size_t beg;
2438   //   size_t size;
2439   //   size_t size_with_redzone;
2440   //   const char *name;
2441   //   const char *module_name;
2442   //   size_t has_dynamic_init;
2443   //   void *source_location;
2444   //   size_t odr_indicator;
2445   // We initialize an array of such structures and pass it to a run-time call.
2446   StructType *GlobalStructTy =
2447       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
2448                       IntptrTy, IntptrTy, IntptrTy);
2449   SmallVector<GlobalVariable *, 16> NewGlobals(n);
2450   SmallVector<Constant *, 16> Initializers(n);
2451 
2452   bool HasDynamicallyInitializedGlobals = false;
2453 
2454   // We shouldn't merge same module names, as this string serves as unique
2455   // module ID in runtime.
2456   GlobalVariable *ModuleName = createPrivateGlobalForString(
2457       M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
2458 
2459   for (size_t i = 0; i < n; i++) {
2460     GlobalVariable *G = GlobalsToChange[i];
2461 
2462     // FIXME: Metadata should be attched directly to the global directly instead
2463     // of being added to llvm.asan.globals.
2464     auto MD = GlobalsMD.get(G);
2465     StringRef NameForGlobal = G->getName();
2466     // Create string holding the global name (use global name from metadata
2467     // if it's available, otherwise just write the name of global variable).
2468     GlobalVariable *Name = createPrivateGlobalForString(
2469         M, MD.Name.empty() ? NameForGlobal : MD.Name,
2470         /*AllowMerging*/ true, kAsanGenPrefix);
2471 
2472     Type *Ty = G->getValueType();
2473     const uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
2474     const uint64_t RightRedzoneSize = getRedzoneSizeForGlobal(SizeInBytes);
2475     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2476 
2477     StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2478     Constant *NewInitializer = ConstantStruct::get(
2479         NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
2480 
2481     // Create a new global variable with enough space for a redzone.
2482     GlobalValue::LinkageTypes Linkage = G->getLinkage();
2483     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2484       Linkage = GlobalValue::InternalLinkage;
2485     GlobalVariable *NewGlobal = new GlobalVariable(
2486         M, NewTy, G->isConstant(), Linkage, NewInitializer, "", G,
2487         G->getThreadLocalMode(), G->getAddressSpace());
2488     NewGlobal->copyAttributesFrom(G);
2489     NewGlobal->setComdat(G->getComdat());
2490     NewGlobal->setAlignment(MaybeAlign(getMinRedzoneSizeForGlobal()));
2491     // Don't fold globals with redzones. ODR violation detector and redzone
2492     // poisoning implicitly creates a dependence on the global's address, so it
2493     // is no longer valid for it to be marked unnamed_addr.
2494     NewGlobal->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
2495 
2496     // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2497     if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2498         G->isConstant()) {
2499       auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2500       if (Seq && Seq->isCString())
2501         NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2502     }
2503 
2504     // Transfer the debug info and type metadata.  The payload starts at offset
2505     // zero so we can copy the metadata over as is.
2506     NewGlobal->copyMetadata(G, 0);
2507 
2508     Value *Indices2[2];
2509     Indices2[0] = IRB.getInt32(0);
2510     Indices2[1] = IRB.getInt32(0);
2511 
2512     G->replaceAllUsesWith(
2513         ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
2514     NewGlobal->takeName(G);
2515     G->eraseFromParent();
2516     NewGlobals[i] = NewGlobal;
2517 
2518     Constant *SourceLoc;
2519     if (!MD.SourceLoc.empty()) {
2520       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2521       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2522     } else {
2523       SourceLoc = ConstantInt::get(IntptrTy, 0);
2524     }
2525 
2526     Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2527     GlobalValue *InstrumentedGlobal = NewGlobal;
2528 
2529     bool CanUsePrivateAliases =
2530         TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2531         TargetTriple.isOSBinFormatWasm();
2532     if (CanUsePrivateAliases && UsePrivateAlias) {
2533       // Create local alias for NewGlobal to avoid crash on ODR between
2534       // instrumented and non-instrumented libraries.
2535       InstrumentedGlobal =
2536           GlobalAlias::create(GlobalValue::PrivateLinkage, "", NewGlobal);
2537     }
2538 
2539     // ODR should not happen for local linkage.
2540     if (NewGlobal->hasLocalLinkage()) {
2541       ODRIndicator = ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, -1),
2542                                                IRB.getInt8PtrTy());
2543     } else if (UseOdrIndicator) {
2544       // With local aliases, we need to provide another externally visible
2545       // symbol __odr_asan_XXX to detect ODR violation.
2546       auto *ODRIndicatorSym =
2547           new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2548                              Constant::getNullValue(IRB.getInt8Ty()),
2549                              kODRGenPrefix + NameForGlobal, nullptr,
2550                              NewGlobal->getThreadLocalMode());
2551 
2552       // Set meaningful attributes for indicator symbol.
2553       ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2554       ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2555       ODRIndicatorSym->setAlignment(Align(1));
2556       ODRIndicator = ODRIndicatorSym;
2557     }
2558 
2559     Constant *Initializer = ConstantStruct::get(
2560         GlobalStructTy,
2561         ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
2562         ConstantInt::get(IntptrTy, SizeInBytes),
2563         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2564         ConstantExpr::getPointerCast(Name, IntptrTy),
2565         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
2566         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
2567         ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
2568 
2569     if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
2570 
2571     LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
2572 
2573     Initializers[i] = Initializer;
2574   }
2575 
2576   // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2577   // ConstantMerge'ing them.
2578   SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2579   for (size_t i = 0; i < n; i++) {
2580     GlobalVariable *G = NewGlobals[i];
2581     if (G->getName().empty()) continue;
2582     GlobalsToAddToUsedList.push_back(G);
2583   }
2584   appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2585 
2586   std::string ELFUniqueModuleId =
2587       (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2588                                                         : "";
2589 
2590   if (!ELFUniqueModuleId.empty()) {
2591     InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2592     *CtorComdat = true;
2593   } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
2594     InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2595   } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2596     InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2597   } else {
2598     InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2599   }
2600 
2601   // Create calls for poisoning before initializers run and unpoisoning after.
2602   if (HasDynamicallyInitializedGlobals)
2603     createInitializerPoisonCalls(M, ModuleName);
2604 
2605   LLVM_DEBUG(dbgs() << M);
2606   return true;
2607 }
2608 
2609 uint64_t
2610 ModuleAddressSanitizer::getRedzoneSizeForGlobal(uint64_t SizeInBytes) const {
2611   constexpr uint64_t kMaxRZ = 1 << 18;
2612   const uint64_t MinRZ = getMinRedzoneSizeForGlobal();
2613 
2614   uint64_t RZ = 0;
2615   if (SizeInBytes <= MinRZ / 2) {
2616     // Reduce redzone size for small size objects, e.g. int, char[1]. MinRZ is
2617     // at least 32 bytes, optimize when SizeInBytes is less than or equal to
2618     // half of MinRZ.
2619     RZ = MinRZ - SizeInBytes;
2620   } else {
2621     // Calculate RZ, where MinRZ <= RZ <= MaxRZ, and RZ ~ 1/4 * SizeInBytes.
2622     RZ = std::max(MinRZ, std::min(kMaxRZ, (SizeInBytes / MinRZ / 4) * MinRZ));
2623 
2624     // Round up to multiple of MinRZ.
2625     if (SizeInBytes % MinRZ)
2626       RZ += MinRZ - (SizeInBytes % MinRZ);
2627   }
2628 
2629   assert((RZ + SizeInBytes) % MinRZ == 0);
2630 
2631   return RZ;
2632 }
2633 
2634 int ModuleAddressSanitizer::GetAsanVersion(const Module &M) const {
2635   int LongSize = M.getDataLayout().getPointerSizeInBits();
2636   bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2637   int Version = 8;
2638   // 32-bit Android is one version ahead because of the switch to dynamic
2639   // shadow.
2640   Version += (LongSize == 32 && isAndroid);
2641   return Version;
2642 }
2643 
2644 bool ModuleAddressSanitizer::instrumentModule(Module &M) {
2645   initializeCallbacks(M);
2646 
2647   // Create a module constructor. A destructor is created lazily because not all
2648   // platforms, and not all modules need it.
2649   if (CompileKernel) {
2650     // The kernel always builds with its own runtime, and therefore does not
2651     // need the init and version check calls.
2652     AsanCtorFunction = createSanitizerCtor(M, kAsanModuleCtorName);
2653   } else {
2654     std::string AsanVersion = std::to_string(GetAsanVersion(M));
2655     std::string VersionCheckName =
2656         ClInsertVersionCheck ? (kAsanVersionCheckNamePrefix + AsanVersion) : "";
2657     std::tie(AsanCtorFunction, std::ignore) =
2658         createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName,
2659                                             kAsanInitName, /*InitArgTypes=*/{},
2660                                             /*InitArgs=*/{}, VersionCheckName);
2661   }
2662 
2663   bool CtorComdat = true;
2664   if (ClGlobals) {
2665     IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2666     InstrumentGlobals(IRB, M, &CtorComdat);
2667   }
2668 
2669   const uint64_t Priority = GetCtorAndDtorPriority(TargetTriple);
2670 
2671   // Put the constructor and destructor in comdat if both
2672   // (1) global instrumentation is not TU-specific
2673   // (2) target is ELF.
2674   if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2675     AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2676     appendToGlobalCtors(M, AsanCtorFunction, Priority, AsanCtorFunction);
2677     if (AsanDtorFunction) {
2678       AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2679       appendToGlobalDtors(M, AsanDtorFunction, Priority, AsanDtorFunction);
2680     }
2681   } else {
2682     appendToGlobalCtors(M, AsanCtorFunction, Priority);
2683     if (AsanDtorFunction)
2684       appendToGlobalDtors(M, AsanDtorFunction, Priority);
2685   }
2686 
2687   return true;
2688 }
2689 
2690 void AddressSanitizer::initializeCallbacks(Module &M) {
2691   IRBuilder<> IRB(*C);
2692   // Create __asan_report* callbacks.
2693   // IsWrite, TypeSize and Exp are encoded in the function name.
2694   for (int Exp = 0; Exp < 2; Exp++) {
2695     for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2696       const std::string TypeStr = AccessIsWrite ? "store" : "load";
2697       const std::string ExpStr = Exp ? "exp_" : "";
2698       const std::string EndingStr = Recover ? "_noabort" : "";
2699 
2700       SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2701       SmallVector<Type *, 2> Args1{1, IntptrTy};
2702       if (Exp) {
2703         Type *ExpType = Type::getInt32Ty(*C);
2704         Args2.push_back(ExpType);
2705         Args1.push_back(ExpType);
2706       }
2707       AsanErrorCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2708           kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
2709           FunctionType::get(IRB.getVoidTy(), Args2, false));
2710 
2711       AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2712           ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2713           FunctionType::get(IRB.getVoidTy(), Args2, false));
2714 
2715       for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2716            AccessSizeIndex++) {
2717         const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2718         AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2719             M.getOrInsertFunction(
2720                 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2721                 FunctionType::get(IRB.getVoidTy(), Args1, false));
2722 
2723         AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2724             M.getOrInsertFunction(
2725                 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2726                 FunctionType::get(IRB.getVoidTy(), Args1, false));
2727       }
2728     }
2729   }
2730 
2731   const std::string MemIntrinCallbackPrefix =
2732       CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
2733   AsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",
2734                                       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2735                                       IRB.getInt8PtrTy(), IntptrTy);
2736   AsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy",
2737                                      IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2738                                      IRB.getInt8PtrTy(), IntptrTy);
2739   AsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",
2740                                      IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2741                                      IRB.getInt32Ty(), IntptrTy);
2742 
2743   AsanHandleNoReturnFunc =
2744       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy());
2745 
2746   AsanPtrCmpFunction =
2747       M.getOrInsertFunction(kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy);
2748   AsanPtrSubFunction =
2749       M.getOrInsertFunction(kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy);
2750   if (Mapping.InGlobal)
2751     AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2752                                            ArrayType::get(IRB.getInt8Ty(), 0));
2753 
2754   AMDGPUAddressShared = M.getOrInsertFunction(
2755       kAMDGPUAddressSharedName, IRB.getInt1Ty(), IRB.getInt8PtrTy());
2756   AMDGPUAddressPrivate = M.getOrInsertFunction(
2757       kAMDGPUAddressPrivateName, IRB.getInt1Ty(), IRB.getInt8PtrTy());
2758 }
2759 
2760 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2761   // For each NSObject descendant having a +load method, this method is invoked
2762   // by the ObjC runtime before any of the static constructors is called.
2763   // Therefore we need to instrument such methods with a call to __asan_init
2764   // at the beginning in order to initialize our runtime before any access to
2765   // the shadow memory.
2766   // We cannot just ignore these methods, because they may call other
2767   // instrumented functions.
2768   if (F.getName().find(" load]") != std::string::npos) {
2769     FunctionCallee AsanInitFunction =
2770         declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
2771     IRBuilder<> IRB(&F.front(), F.front().begin());
2772     IRB.CreateCall(AsanInitFunction, {});
2773     return true;
2774   }
2775   return false;
2776 }
2777 
2778 bool AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2779   // Generate code only when dynamic addressing is needed.
2780   if (Mapping.Offset != kDynamicShadowSentinel)
2781     return false;
2782 
2783   IRBuilder<> IRB(&F.front().front());
2784   if (Mapping.InGlobal) {
2785     if (ClWithIfuncSuppressRemat) {
2786       // An empty inline asm with input reg == output reg.
2787       // An opaque pointer-to-int cast, basically.
2788       InlineAsm *Asm = InlineAsm::get(
2789           FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2790           StringRef(""), StringRef("=r,0"),
2791           /*hasSideEffects=*/false);
2792       LocalDynamicShadow =
2793           IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2794     } else {
2795       LocalDynamicShadow =
2796           IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2797     }
2798   } else {
2799     Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2800         kAsanShadowMemoryDynamicAddress, IntptrTy);
2801     LocalDynamicShadow = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);
2802   }
2803   return true;
2804 }
2805 
2806 void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2807   // Find the one possible call to llvm.localescape and pre-mark allocas passed
2808   // to it as uninteresting. This assumes we haven't started processing allocas
2809   // yet. This check is done up front because iterating the use list in
2810   // isInterestingAlloca would be algorithmically slower.
2811   assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2812 
2813   // Try to get the declaration of llvm.localescape. If it's not in the module,
2814   // we can exit early.
2815   if (!F.getParent()->getFunction("llvm.localescape")) return;
2816 
2817   // Look for a call to llvm.localescape call in the entry block. It can't be in
2818   // any other block.
2819   for (Instruction &I : F.getEntryBlock()) {
2820     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2821     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2822       // We found a call. Mark all the allocas passed in as uninteresting.
2823       for (Value *Arg : II->args()) {
2824         AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2825         assert(AI && AI->isStaticAlloca() &&
2826                "non-static alloca arg to localescape");
2827         ProcessedAllocas[AI] = false;
2828       }
2829       break;
2830     }
2831   }
2832 }
2833 
2834 bool AddressSanitizer::suppressInstrumentationSiteForDebug(int &Instrumented) {
2835   bool ShouldInstrument =
2836       ClDebugMin < 0 || ClDebugMax < 0 ||
2837       (Instrumented >= ClDebugMin && Instrumented <= ClDebugMax);
2838   Instrumented++;
2839   return !ShouldInstrument;
2840 }
2841 
2842 bool AddressSanitizer::instrumentFunction(Function &F,
2843                                           const TargetLibraryInfo *TLI) {
2844   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2845   if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2846   if (F.getName().startswith("__asan_")) return false;
2847 
2848   bool FunctionModified = false;
2849 
2850   // If needed, insert __asan_init before checking for SanitizeAddress attr.
2851   // This function needs to be called even if the function body is not
2852   // instrumented.
2853   if (maybeInsertAsanInitAtFunctionEntry(F))
2854     FunctionModified = true;
2855 
2856   // Leave if the function doesn't need instrumentation.
2857   if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2858 
2859   LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2860 
2861   initializeCallbacks(*F.getParent());
2862 
2863   FunctionStateRAII CleanupObj(this);
2864 
2865   FunctionModified |= maybeInsertDynamicShadowAtFunctionEntry(F);
2866 
2867   // We can't instrument allocas used with llvm.localescape. Only static allocas
2868   // can be passed to that intrinsic.
2869   markEscapedLocalAllocas(F);
2870 
2871   // We want to instrument every address only once per basic block (unless there
2872   // are calls between uses).
2873   SmallPtrSet<Value *, 16> TempsToInstrument;
2874   SmallVector<InterestingMemoryOperand, 16> OperandsToInstrument;
2875   SmallVector<MemIntrinsic *, 16> IntrinToInstrument;
2876   SmallVector<Instruction *, 8> NoReturnCalls;
2877   SmallVector<BasicBlock *, 16> AllBlocks;
2878   SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2879   int NumAllocas = 0;
2880 
2881   // Fill the set of memory operations to instrument.
2882   for (auto &BB : F) {
2883     AllBlocks.push_back(&BB);
2884     TempsToInstrument.clear();
2885     int NumInsnsPerBB = 0;
2886     for (auto &Inst : BB) {
2887       if (LooksLikeCodeInBug11395(&Inst)) return false;
2888       SmallVector<InterestingMemoryOperand, 1> InterestingOperands;
2889       getInterestingMemoryOperands(&Inst, InterestingOperands);
2890 
2891       if (!InterestingOperands.empty()) {
2892         for (auto &Operand : InterestingOperands) {
2893           if (ClOpt && ClOptSameTemp) {
2894             Value *Ptr = Operand.getPtr();
2895             // If we have a mask, skip instrumentation if we've already
2896             // instrumented the full object. But don't add to TempsToInstrument
2897             // because we might get another load/store with a different mask.
2898             if (Operand.MaybeMask) {
2899               if (TempsToInstrument.count(Ptr))
2900                 continue; // We've seen this (whole) temp in the current BB.
2901             } else {
2902               if (!TempsToInstrument.insert(Ptr).second)
2903                 continue; // We've seen this temp in the current BB.
2904             }
2905           }
2906           OperandsToInstrument.push_back(Operand);
2907           NumInsnsPerBB++;
2908         }
2909       } else if (((ClInvalidPointerPairs || ClInvalidPointerCmp) &&
2910                   isInterestingPointerComparison(&Inst)) ||
2911                  ((ClInvalidPointerPairs || ClInvalidPointerSub) &&
2912                   isInterestingPointerSubtraction(&Inst))) {
2913         PointerComparisonsOrSubtracts.push_back(&Inst);
2914       } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst)) {
2915         // ok, take it.
2916         IntrinToInstrument.push_back(MI);
2917         NumInsnsPerBB++;
2918       } else {
2919         if (isa<AllocaInst>(Inst)) NumAllocas++;
2920         if (auto *CB = dyn_cast<CallBase>(&Inst)) {
2921           // A call inside BB.
2922           TempsToInstrument.clear();
2923           if (CB->doesNotReturn() && !CB->hasMetadata("nosanitize"))
2924             NoReturnCalls.push_back(CB);
2925         }
2926         if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2927           maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
2928       }
2929       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
2930     }
2931   }
2932 
2933   bool UseCalls = (ClInstrumentationWithCallsThreshold >= 0 &&
2934                    OperandsToInstrument.size() + IntrinToInstrument.size() >
2935                        (unsigned)ClInstrumentationWithCallsThreshold);
2936   const DataLayout &DL = F.getParent()->getDataLayout();
2937   ObjectSizeOpts ObjSizeOpts;
2938   ObjSizeOpts.RoundToAlign = true;
2939   ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
2940 
2941   // Instrument.
2942   int NumInstrumented = 0;
2943   for (auto &Operand : OperandsToInstrument) {
2944     if (!suppressInstrumentationSiteForDebug(NumInstrumented))
2945       instrumentMop(ObjSizeVis, Operand, UseCalls,
2946                     F.getParent()->getDataLayout());
2947     FunctionModified = true;
2948   }
2949   for (auto Inst : IntrinToInstrument) {
2950     if (!suppressInstrumentationSiteForDebug(NumInstrumented))
2951       instrumentMemIntrinsic(Inst);
2952     FunctionModified = true;
2953   }
2954 
2955   FunctionStackPoisoner FSP(F, *this);
2956   bool ChangedStack = FSP.runOnFunction();
2957 
2958   // We must unpoison the stack before NoReturn calls (throw, _exit, etc).
2959   // See e.g. https://github.com/google/sanitizers/issues/37
2960   for (auto CI : NoReturnCalls) {
2961     IRBuilder<> IRB(CI);
2962     IRB.CreateCall(AsanHandleNoReturnFunc, {});
2963   }
2964 
2965   for (auto Inst : PointerComparisonsOrSubtracts) {
2966     instrumentPointerComparisonOrSubtraction(Inst);
2967     FunctionModified = true;
2968   }
2969 
2970   if (ChangedStack || !NoReturnCalls.empty())
2971     FunctionModified = true;
2972 
2973   LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2974                     << F << "\n");
2975 
2976   return FunctionModified;
2977 }
2978 
2979 // Workaround for bug 11395: we don't want to instrument stack in functions
2980 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2981 // FIXME: remove once the bug 11395 is fixed.
2982 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2983   if (LongSize != 32) return false;
2984   CallInst *CI = dyn_cast<CallInst>(I);
2985   if (!CI || !CI->isInlineAsm()) return false;
2986   if (CI->arg_size() <= 5)
2987     return false;
2988   // We have inline assembly with quite a few arguments.
2989   return true;
2990 }
2991 
2992 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2993   IRBuilder<> IRB(*C);
2994   if (ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Always ||
2995       ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Runtime) {
2996     const char *MallocNameTemplate =
2997         ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Always
2998             ? kAsanStackMallocAlwaysNameTemplate
2999             : kAsanStackMallocNameTemplate;
3000     for (int Index = 0; Index <= kMaxAsanStackMallocSizeClass; Index++) {
3001       std::string Suffix = itostr(Index);
3002       AsanStackMallocFunc[Index] = M.getOrInsertFunction(
3003           MallocNameTemplate + Suffix, IntptrTy, IntptrTy);
3004       AsanStackFreeFunc[Index] =
3005           M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
3006                                 IRB.getVoidTy(), IntptrTy, IntptrTy);
3007     }
3008   }
3009   if (ASan.UseAfterScope) {
3010     AsanPoisonStackMemoryFunc = M.getOrInsertFunction(
3011         kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
3012     AsanUnpoisonStackMemoryFunc = M.getOrInsertFunction(
3013         kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
3014   }
3015 
3016   for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
3017     std::ostringstream Name;
3018     Name << kAsanSetShadowPrefix;
3019     Name << std::setw(2) << std::setfill('0') << std::hex << Val;
3020     AsanSetShadowFunc[Val] =
3021         M.getOrInsertFunction(Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy);
3022   }
3023 
3024   AsanAllocaPoisonFunc = M.getOrInsertFunction(
3025       kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
3026   AsanAllocasUnpoisonFunc = M.getOrInsertFunction(
3027       kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
3028 }
3029 
3030 void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
3031                                                ArrayRef<uint8_t> ShadowBytes,
3032                                                size_t Begin, size_t End,
3033                                                IRBuilder<> &IRB,
3034                                                Value *ShadowBase) {
3035   if (Begin >= End)
3036     return;
3037 
3038   const size_t LargestStoreSizeInBytes =
3039       std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
3040 
3041   const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
3042 
3043   // Poison given range in shadow using larges store size with out leading and
3044   // trailing zeros in ShadowMask. Zeros never change, so they need neither
3045   // poisoning nor up-poisoning. Still we don't mind if some of them get into a
3046   // middle of a store.
3047   for (size_t i = Begin; i < End;) {
3048     if (!ShadowMask[i]) {
3049       assert(!ShadowBytes[i]);
3050       ++i;
3051       continue;
3052     }
3053 
3054     size_t StoreSizeInBytes = LargestStoreSizeInBytes;
3055     // Fit store size into the range.
3056     while (StoreSizeInBytes > End - i)
3057       StoreSizeInBytes /= 2;
3058 
3059     // Minimize store size by trimming trailing zeros.
3060     for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
3061       while (j <= StoreSizeInBytes / 2)
3062         StoreSizeInBytes /= 2;
3063     }
3064 
3065     uint64_t Val = 0;
3066     for (size_t j = 0; j < StoreSizeInBytes; j++) {
3067       if (IsLittleEndian)
3068         Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
3069       else
3070         Val = (Val << 8) | ShadowBytes[i + j];
3071     }
3072 
3073     Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
3074     Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
3075     IRB.CreateAlignedStore(
3076         Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()),
3077         Align(1));
3078 
3079     i += StoreSizeInBytes;
3080   }
3081 }
3082 
3083 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
3084                                          ArrayRef<uint8_t> ShadowBytes,
3085                                          IRBuilder<> &IRB, Value *ShadowBase) {
3086   copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
3087 }
3088 
3089 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
3090                                          ArrayRef<uint8_t> ShadowBytes,
3091                                          size_t Begin, size_t End,
3092                                          IRBuilder<> &IRB, Value *ShadowBase) {
3093   assert(ShadowMask.size() == ShadowBytes.size());
3094   size_t Done = Begin;
3095   for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
3096     if (!ShadowMask[i]) {
3097       assert(!ShadowBytes[i]);
3098       continue;
3099     }
3100     uint8_t Val = ShadowBytes[i];
3101     if (!AsanSetShadowFunc[Val])
3102       continue;
3103 
3104     // Skip same values.
3105     for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
3106     }
3107 
3108     if (j - i >= ClMaxInlinePoisoningSize) {
3109       copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
3110       IRB.CreateCall(AsanSetShadowFunc[Val],
3111                      {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
3112                       ConstantInt::get(IntptrTy, j - i)});
3113       Done = j;
3114     }
3115   }
3116 
3117   copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
3118 }
3119 
3120 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
3121 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
3122 static int StackMallocSizeClass(uint64_t LocalStackSize) {
3123   assert(LocalStackSize <= kMaxStackMallocSize);
3124   uint64_t MaxSize = kMinStackMallocSize;
3125   for (int i = 0;; i++, MaxSize *= 2)
3126     if (LocalStackSize <= MaxSize) return i;
3127   llvm_unreachable("impossible LocalStackSize");
3128 }
3129 
3130 void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
3131   Instruction *CopyInsertPoint = &F.front().front();
3132   if (CopyInsertPoint == ASan.LocalDynamicShadow) {
3133     // Insert after the dynamic shadow location is determined
3134     CopyInsertPoint = CopyInsertPoint->getNextNode();
3135     assert(CopyInsertPoint);
3136   }
3137   IRBuilder<> IRB(CopyInsertPoint);
3138   const DataLayout &DL = F.getParent()->getDataLayout();
3139   for (Argument &Arg : F.args()) {
3140     if (Arg.hasByValAttr()) {
3141       Type *Ty = Arg.getParamByValType();
3142       const Align Alignment =
3143           DL.getValueOrABITypeAlignment(Arg.getParamAlign(), Ty);
3144 
3145       AllocaInst *AI = IRB.CreateAlloca(
3146           Ty, nullptr,
3147           (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
3148               ".byval");
3149       AI->setAlignment(Alignment);
3150       Arg.replaceAllUsesWith(AI);
3151 
3152       uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3153       IRB.CreateMemCpy(AI, Alignment, &Arg, Alignment, AllocSize);
3154     }
3155   }
3156 }
3157 
3158 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
3159                                           Value *ValueIfTrue,
3160                                           Instruction *ThenTerm,
3161                                           Value *ValueIfFalse) {
3162   PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
3163   BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
3164   PHI->addIncoming(ValueIfFalse, CondBlock);
3165   BasicBlock *ThenBlock = ThenTerm->getParent();
3166   PHI->addIncoming(ValueIfTrue, ThenBlock);
3167   return PHI;
3168 }
3169 
3170 Value *FunctionStackPoisoner::createAllocaForLayout(
3171     IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
3172   AllocaInst *Alloca;
3173   if (Dynamic) {
3174     Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
3175                               ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
3176                               "MyAlloca");
3177   } else {
3178     Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
3179                               nullptr, "MyAlloca");
3180     assert(Alloca->isStaticAlloca());
3181   }
3182   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
3183   uint64_t FrameAlignment = std::max(L.FrameAlignment, uint64_t(ClRealignStack));
3184   Alloca->setAlignment(Align(FrameAlignment));
3185   return IRB.CreatePointerCast(Alloca, IntptrTy);
3186 }
3187 
3188 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
3189   BasicBlock &FirstBB = *F.begin();
3190   IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
3191   DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
3192   IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
3193   DynamicAllocaLayout->setAlignment(Align(32));
3194 }
3195 
3196 void FunctionStackPoisoner::processDynamicAllocas() {
3197   if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
3198     assert(DynamicAllocaPoisonCallVec.empty());
3199     return;
3200   }
3201 
3202   // Insert poison calls for lifetime intrinsics for dynamic allocas.
3203   for (const auto &APC : DynamicAllocaPoisonCallVec) {
3204     assert(APC.InsBefore);
3205     assert(APC.AI);
3206     assert(ASan.isInterestingAlloca(*APC.AI));
3207     assert(!APC.AI->isStaticAlloca());
3208 
3209     IRBuilder<> IRB(APC.InsBefore);
3210     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
3211     // Dynamic allocas will be unpoisoned unconditionally below in
3212     // unpoisonDynamicAllocas.
3213     // Flag that we need unpoison static allocas.
3214   }
3215 
3216   // Handle dynamic allocas.
3217   createDynamicAllocasInitStorage();
3218   for (auto &AI : DynamicAllocaVec)
3219     handleDynamicAllocaCall(AI);
3220   unpoisonDynamicAllocas();
3221 }
3222 
3223 /// Collect instructions in the entry block after \p InsBefore which initialize
3224 /// permanent storage for a function argument. These instructions must remain in
3225 /// the entry block so that uninitialized values do not appear in backtraces. An
3226 /// added benefit is that this conserves spill slots. This does not move stores
3227 /// before instrumented / "interesting" allocas.
3228 static void findStoresToUninstrumentedArgAllocas(
3229     AddressSanitizer &ASan, Instruction &InsBefore,
3230     SmallVectorImpl<Instruction *> &InitInsts) {
3231   Instruction *Start = InsBefore.getNextNonDebugInstruction();
3232   for (Instruction *It = Start; It; It = It->getNextNonDebugInstruction()) {
3233     // Argument initialization looks like:
3234     // 1) store <Argument>, <Alloca> OR
3235     // 2) <CastArgument> = cast <Argument> to ...
3236     //    store <CastArgument> to <Alloca>
3237     // Do not consider any other kind of instruction.
3238     //
3239     // Note: This covers all known cases, but may not be exhaustive. An
3240     // alternative to pattern-matching stores is to DFS over all Argument uses:
3241     // this might be more general, but is probably much more complicated.
3242     if (isa<AllocaInst>(It) || isa<CastInst>(It))
3243       continue;
3244     if (auto *Store = dyn_cast<StoreInst>(It)) {
3245       // The store destination must be an alloca that isn't interesting for
3246       // ASan to instrument. These are moved up before InsBefore, and they're
3247       // not interesting because allocas for arguments can be mem2reg'd.
3248       auto *Alloca = dyn_cast<AllocaInst>(Store->getPointerOperand());
3249       if (!Alloca || ASan.isInterestingAlloca(*Alloca))
3250         continue;
3251 
3252       Value *Val = Store->getValueOperand();
3253       bool IsDirectArgInit = isa<Argument>(Val);
3254       bool IsArgInitViaCast =
3255           isa<CastInst>(Val) &&
3256           isa<Argument>(cast<CastInst>(Val)->getOperand(0)) &&
3257           // Check that the cast appears directly before the store. Otherwise
3258           // moving the cast before InsBefore may break the IR.
3259           Val == It->getPrevNonDebugInstruction();
3260       bool IsArgInit = IsDirectArgInit || IsArgInitViaCast;
3261       if (!IsArgInit)
3262         continue;
3263 
3264       if (IsArgInitViaCast)
3265         InitInsts.push_back(cast<Instruction>(Val));
3266       InitInsts.push_back(Store);
3267       continue;
3268     }
3269 
3270     // Do not reorder past unknown instructions: argument initialization should
3271     // only involve casts and stores.
3272     return;
3273   }
3274 }
3275 
3276 void FunctionStackPoisoner::processStaticAllocas() {
3277   if (AllocaVec.empty()) {
3278     assert(StaticAllocaPoisonCallVec.empty());
3279     return;
3280   }
3281 
3282   int StackMallocIdx = -1;
3283   DebugLoc EntryDebugLocation;
3284   if (auto SP = F.getSubprogram())
3285     EntryDebugLocation =
3286         DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
3287 
3288   Instruction *InsBefore = AllocaVec[0];
3289   IRBuilder<> IRB(InsBefore);
3290 
3291   // Make sure non-instrumented allocas stay in the entry block. Otherwise,
3292   // debug info is broken, because only entry-block allocas are treated as
3293   // regular stack slots.
3294   auto InsBeforeB = InsBefore->getParent();
3295   assert(InsBeforeB == &F.getEntryBlock());
3296   for (auto *AI : StaticAllocasToMoveUp)
3297     if (AI->getParent() == InsBeforeB)
3298       AI->moveBefore(InsBefore);
3299 
3300   // Move stores of arguments into entry-block allocas as well. This prevents
3301   // extra stack slots from being generated (to house the argument values until
3302   // they can be stored into the allocas). This also prevents uninitialized
3303   // values from being shown in backtraces.
3304   SmallVector<Instruction *, 8> ArgInitInsts;
3305   findStoresToUninstrumentedArgAllocas(ASan, *InsBefore, ArgInitInsts);
3306   for (Instruction *ArgInitInst : ArgInitInsts)
3307     ArgInitInst->moveBefore(InsBefore);
3308 
3309   // If we have a call to llvm.localescape, keep it in the entry block.
3310   if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
3311 
3312   SmallVector<ASanStackVariableDescription, 16> SVD;
3313   SVD.reserve(AllocaVec.size());
3314   for (AllocaInst *AI : AllocaVec) {
3315     ASanStackVariableDescription D = {AI->getName().data(),
3316                                       ASan.getAllocaSizeInBytes(*AI),
3317                                       0,
3318                                       AI->getAlignment(),
3319                                       AI,
3320                                       0,
3321                                       0};
3322     SVD.push_back(D);
3323   }
3324 
3325   // Minimal header size (left redzone) is 4 pointers,
3326   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
3327   uint64_t Granularity = 1ULL << Mapping.Scale;
3328   uint64_t MinHeaderSize = std::max((uint64_t)ASan.LongSize / 2, Granularity);
3329   const ASanStackFrameLayout &L =
3330       ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
3331 
3332   // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
3333   DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
3334   for (auto &Desc : SVD)
3335     AllocaToSVDMap[Desc.AI] = &Desc;
3336 
3337   // Update SVD with information from lifetime intrinsics.
3338   for (const auto &APC : StaticAllocaPoisonCallVec) {
3339     assert(APC.InsBefore);
3340     assert(APC.AI);
3341     assert(ASan.isInterestingAlloca(*APC.AI));
3342     assert(APC.AI->isStaticAlloca());
3343 
3344     ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3345     Desc.LifetimeSize = Desc.Size;
3346     if (const DILocation *FnLoc = EntryDebugLocation.get()) {
3347       if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
3348         if (LifetimeLoc->getFile() == FnLoc->getFile())
3349           if (unsigned Line = LifetimeLoc->getLine())
3350             Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
3351       }
3352     }
3353   }
3354 
3355   auto DescriptionString = ComputeASanStackFrameDescription(SVD);
3356   LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
3357   uint64_t LocalStackSize = L.FrameSize;
3358   bool DoStackMalloc =
3359       ASan.UseAfterReturn != AsanDetectStackUseAfterReturnMode::Never &&
3360       !ASan.CompileKernel && LocalStackSize <= kMaxStackMallocSize;
3361   bool DoDynamicAlloca = ClDynamicAllocaStack;
3362   // Don't do dynamic alloca or stack malloc if:
3363   // 1) There is inline asm: too often it makes assumptions on which registers
3364   //    are available.
3365   // 2) There is a returns_twice call (typically setjmp), which is
3366   //    optimization-hostile, and doesn't play well with introduced indirect
3367   //    register-relative calculation of local variable addresses.
3368   DoDynamicAlloca &= !HasInlineAsm && !HasReturnsTwiceCall;
3369   DoStackMalloc &= !HasInlineAsm && !HasReturnsTwiceCall;
3370 
3371   Value *StaticAlloca =
3372       DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
3373 
3374   Value *FakeStack;
3375   Value *LocalStackBase;
3376   Value *LocalStackBaseAlloca;
3377   uint8_t DIExprFlags = DIExpression::ApplyOffset;
3378 
3379   if (DoStackMalloc) {
3380     LocalStackBaseAlloca =
3381         IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
3382     if (ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Runtime) {
3383       // void *FakeStack = __asan_option_detect_stack_use_after_return
3384       //     ? __asan_stack_malloc_N(LocalStackSize)
3385       //     : nullptr;
3386       // void *LocalStackBase = (FakeStack) ? FakeStack :
3387       //                        alloca(LocalStackSize);
3388       Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
3389           kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
3390       Value *UseAfterReturnIsEnabled = IRB.CreateICmpNE(
3391           IRB.CreateLoad(IRB.getInt32Ty(), OptionDetectUseAfterReturn),
3392           Constant::getNullValue(IRB.getInt32Ty()));
3393       Instruction *Term =
3394           SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
3395       IRBuilder<> IRBIf(Term);
3396       StackMallocIdx = StackMallocSizeClass(LocalStackSize);
3397       assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
3398       Value *FakeStackValue =
3399           IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
3400                            ConstantInt::get(IntptrTy, LocalStackSize));
3401       IRB.SetInsertPoint(InsBefore);
3402       FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
3403                             ConstantInt::get(IntptrTy, 0));
3404     } else {
3405       // assert(ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode:Always)
3406       // void *FakeStack = __asan_stack_malloc_N(LocalStackSize);
3407       // void *LocalStackBase = (FakeStack) ? FakeStack :
3408       //                        alloca(LocalStackSize);
3409       StackMallocIdx = StackMallocSizeClass(LocalStackSize);
3410       FakeStack = IRB.CreateCall(AsanStackMallocFunc[StackMallocIdx],
3411                                  ConstantInt::get(IntptrTy, LocalStackSize));
3412     }
3413     Value *NoFakeStack =
3414         IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
3415     Instruction *Term =
3416         SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
3417     IRBuilder<> IRBIf(Term);
3418     Value *AllocaValue =
3419         DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
3420 
3421     IRB.SetInsertPoint(InsBefore);
3422     LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
3423     IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
3424     DIExprFlags |= DIExpression::DerefBefore;
3425   } else {
3426     // void *FakeStack = nullptr;
3427     // void *LocalStackBase = alloca(LocalStackSize);
3428     FakeStack = ConstantInt::get(IntptrTy, 0);
3429     LocalStackBase =
3430         DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
3431     LocalStackBaseAlloca = LocalStackBase;
3432   }
3433 
3434   // It shouldn't matter whether we pass an `alloca` or a `ptrtoint` as the
3435   // dbg.declare address opereand, but passing a `ptrtoint` seems to confuse
3436   // later passes and can result in dropped variable coverage in debug info.
3437   Value *LocalStackBaseAllocaPtr =
3438       isa<PtrToIntInst>(LocalStackBaseAlloca)
3439           ? cast<PtrToIntInst>(LocalStackBaseAlloca)->getPointerOperand()
3440           : LocalStackBaseAlloca;
3441   assert(isa<AllocaInst>(LocalStackBaseAllocaPtr) &&
3442          "Variable descriptions relative to ASan stack base will be dropped");
3443 
3444   // Replace Alloca instructions with base+offset.
3445   for (const auto &Desc : SVD) {
3446     AllocaInst *AI = Desc.AI;
3447     replaceDbgDeclare(AI, LocalStackBaseAllocaPtr, DIB, DIExprFlags,
3448                       Desc.Offset);
3449     Value *NewAllocaPtr = IRB.CreateIntToPtr(
3450         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
3451         AI->getType());
3452     AI->replaceAllUsesWith(NewAllocaPtr);
3453   }
3454 
3455   // The left-most redzone has enough space for at least 4 pointers.
3456   // Write the Magic value to redzone[0].
3457   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
3458   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
3459                   BasePlus0);
3460   // Write the frame description constant to redzone[1].
3461   Value *BasePlus1 = IRB.CreateIntToPtr(
3462       IRB.CreateAdd(LocalStackBase,
3463                     ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
3464       IntptrPtrTy);
3465   GlobalVariable *StackDescriptionGlobal =
3466       createPrivateGlobalForString(*F.getParent(), DescriptionString,
3467                                    /*AllowMerging*/ true, kAsanGenPrefix);
3468   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
3469   IRB.CreateStore(Description, BasePlus1);
3470   // Write the PC to redzone[2].
3471   Value *BasePlus2 = IRB.CreateIntToPtr(
3472       IRB.CreateAdd(LocalStackBase,
3473                     ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
3474       IntptrPtrTy);
3475   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
3476 
3477   const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
3478 
3479   // Poison the stack red zones at the entry.
3480   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
3481   // As mask we must use most poisoned case: red zones and after scope.
3482   // As bytes we can use either the same or just red zones only.
3483   copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3484 
3485   if (!StaticAllocaPoisonCallVec.empty()) {
3486     const auto &ShadowInScope = GetShadowBytes(SVD, L);
3487 
3488     // Poison static allocas near lifetime intrinsics.
3489     for (const auto &APC : StaticAllocaPoisonCallVec) {
3490       const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3491       assert(Desc.Offset % L.Granularity == 0);
3492       size_t Begin = Desc.Offset / L.Granularity;
3493       size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
3494 
3495       IRBuilder<> IRB(APC.InsBefore);
3496       copyToShadow(ShadowAfterScope,
3497                    APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3498                    IRB, ShadowBase);
3499     }
3500   }
3501 
3502   SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
3503   SmallVector<uint8_t, 64> ShadowAfterReturn;
3504 
3505   // (Un)poison the stack before all ret instructions.
3506   for (Instruction *Ret : RetVec) {
3507     IRBuilder<> IRBRet(Ret);
3508     // Mark the current frame as retired.
3509     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3510                        BasePlus0);
3511     if (DoStackMalloc) {
3512       assert(StackMallocIdx >= 0);
3513       // if FakeStack != 0  // LocalStackBase == FakeStack
3514       //     // In use-after-return mode, poison the whole stack frame.
3515       //     if StackMallocIdx <= 4
3516       //         // For small sizes inline the whole thing:
3517       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
3518       //         **SavedFlagPtr(FakeStack) = 0
3519       //     else
3520       //         __asan_stack_free_N(FakeStack, LocalStackSize)
3521       // else
3522       //     <This is not a fake stack; unpoison the redzones>
3523       Value *Cmp =
3524           IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
3525       Instruction *ThenTerm, *ElseTerm;
3526       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3527 
3528       IRBuilder<> IRBPoison(ThenTerm);
3529       if (StackMallocIdx <= 4) {
3530         int ClassSize = kMinStackMallocSize << StackMallocIdx;
3531         ShadowAfterReturn.resize(ClassSize / L.Granularity,
3532                                  kAsanStackUseAfterReturnMagic);
3533         copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3534                      ShadowBase);
3535         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
3536             FakeStack,
3537             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3538         Value *SavedFlagPtr = IRBPoison.CreateLoad(
3539             IntptrTy, IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3540         IRBPoison.CreateStore(
3541             Constant::getNullValue(IRBPoison.getInt8Ty()),
3542             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3543       } else {
3544         // For larger frames call __asan_stack_free_*.
3545         IRBPoison.CreateCall(
3546             AsanStackFreeFunc[StackMallocIdx],
3547             {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
3548       }
3549 
3550       IRBuilder<> IRBElse(ElseTerm);
3551       copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
3552     } else {
3553       copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
3554     }
3555   }
3556 
3557   // We are done. Remove the old unused alloca instructions.
3558   for (auto AI : AllocaVec) AI->eraseFromParent();
3559 }
3560 
3561 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
3562                                          IRBuilder<> &IRB, bool DoPoison) {
3563   // For now just insert the call to ASan runtime.
3564   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3565   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
3566   IRB.CreateCall(
3567       DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3568       {AddrArg, SizeArg});
3569 }
3570 
3571 // Handling llvm.lifetime intrinsics for a given %alloca:
3572 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3573 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3574 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3575 //     could be poisoned by previous llvm.lifetime.end instruction, as the
3576 //     variable may go in and out of scope several times, e.g. in loops).
3577 // (3) if we poisoned at least one %alloca in a function,
3578 //     unpoison the whole stack frame at function exit.
3579 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
3580   IRBuilder<> IRB(AI);
3581 
3582   const uint64_t Alignment = std::max(kAllocaRzSize, AI->getAlignment());
3583   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3584 
3585   Value *Zero = Constant::getNullValue(IntptrTy);
3586   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3587   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
3588 
3589   // Since we need to extend alloca with additional memory to locate
3590   // redzones, and OldSize is number of allocated blocks with
3591   // ElementSize size, get allocated memory size in bytes by
3592   // OldSize * ElementSize.
3593   const unsigned ElementSize =
3594       F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
3595   Value *OldSize =
3596       IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3597                     ConstantInt::get(IntptrTy, ElementSize));
3598 
3599   // PartialSize = OldSize % 32
3600   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3601 
3602   // Misalign = kAllocaRzSize - PartialSize;
3603   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3604 
3605   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3606   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3607   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3608 
3609   // AdditionalChunkSize = Alignment + PartialPadding + kAllocaRzSize
3610   // Alignment is added to locate left redzone, PartialPadding for possible
3611   // partial redzone and kAllocaRzSize for right redzone respectively.
3612   Value *AdditionalChunkSize = IRB.CreateAdd(
3613       ConstantInt::get(IntptrTy, Alignment + kAllocaRzSize), PartialPadding);
3614 
3615   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3616 
3617   // Insert new alloca with new NewSize and Alignment params.
3618   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3619   NewAlloca->setAlignment(Align(Alignment));
3620 
3621   // NewAddress = Address + Alignment
3622   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3623                                     ConstantInt::get(IntptrTy, Alignment));
3624 
3625   // Insert __asan_alloca_poison call for new created alloca.
3626   IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
3627 
3628   // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3629   // for unpoisoning stuff.
3630   IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3631 
3632   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3633 
3634   // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
3635   AI->replaceAllUsesWith(NewAddressPtr);
3636 
3637   // We are done. Erase old alloca from parent.
3638   AI->eraseFromParent();
3639 }
3640 
3641 // isSafeAccess returns true if Addr is always inbounds with respect to its
3642 // base object. For example, it is a field access or an array access with
3643 // constant inbounds index.
3644 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3645                                     Value *Addr, uint64_t TypeSize) const {
3646   SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3647   if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
3648   uint64_t Size = SizeOffset.first.getZExtValue();
3649   int64_t Offset = SizeOffset.second.getSExtValue();
3650   // Three checks are required to ensure safety:
3651   // . Offset >= 0  (since the offset is given from the base ptr)
3652   // . Size >= Offset  (unsigned)
3653   // . Size - Offset >= NeededSize  (unsigned)
3654   return Offset >= 0 && Size >= uint64_t(Offset) &&
3655          Size - uint64_t(Offset) >= TypeSize / 8;
3656 }
3657