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