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