OSDN Git Service

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