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