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