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