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