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