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