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