LLVM  7.0.0svn
AddressSanitizer.cpp
Go to the documentation of this file.
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"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
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"
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"
67 #include "llvm/Support/Debug.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 =
97 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
98 static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
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.
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 
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 
201  "asan-instrument-writes", cl::desc("instrument write instructions"),
202  cl::Hidden, cl::init(true));
203 
205  "asan-instrument-atomics",
206  cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
207  cl::init(true));
208 
210  "asan-always-slow-path",
211  cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
212  cl::init(false));
213 
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 
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.
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));
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 
273  "asan-detect-invalid-pointer-pair",
274  cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
275  cl::init(false));
276 
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 
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 
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 
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 
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 
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 
333  "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
334  cl::Hidden, cl::init(false));
335 
337  "asan-stack-dynamic-alloca",
338  cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
339  cl::init(true));
340 
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;
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 =
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;
613  }
614 
615  StringRef getPassName() const override {
616  return "AddressSanitizerFunctionPass";
617  }
618 
619  void getAnalysisUsage(AnalysisUsage &AU) const override {
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 =
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 
832  SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
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) {
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.
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 
1067  AddressSanitizer, "asan",
1068  "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1069  false)
1073  AddressSanitizer, "asan",
1074  "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1075  false)
1076 
1078  bool Recover,
1079  bool UseAfterScope) {
1080  assert(!CompileKernel || Recover);
1081  return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
1082 }
1083 
1085 
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);
1102  return Res;
1103 }
1104 
1105 // Create a constant for Str so that we can pass it to the run-time lib.
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,
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.
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);
1132  return GV;
1133 }
1134 
1135 /// Check if \p G has been created by a trusted compiler pass.
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.
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.
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.
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)) &&
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.
1420 
1421  if (ClOpt && ClOptGlobals) {
1422  // If initialization order checking is disabled, a simple access to a
1423  // dynamically initialized global is always valid.
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.
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 
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  // Two problems with thread-locals:
1659  // - The address of the main thread's copy can't be computed at link-time.
1660  // - Need to poison all copies, not just the main thread's one.
1661  if (G->isThreadLocal()) return false;
1662  // For now, just ignore this Global if the alignment is large.
1663  if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1664 
1665  // If we know this global is defined only in this module (external or static),
1666  // we can instrument it.
1670  // For targets that support comdats, we can instrument ODR globals in
1671  // comdats. We simply add our global metadata to the group and hope that an
1672  // instrumented global is selected.
1673  // FIXME: This should work on ELF, enable it there too.
1674  if (!TargetTriple.isOSBinFormatCOFF())
1675  return false;
1678  return false;
1679  if (!G->hasComdat())
1680  return false;
1681  }
1682 
1683  // If a comdat is present, it must have a selection kind that implies ODR
1684  // semantics: no duplicates, any, or exact match.
1685  if (Comdat *C = G->getComdat()) {
1686  switch (C->getSelectionKind()) {
1687  case Comdat::Any:
1688  case Comdat::ExactMatch:
1689  case Comdat::NoDuplicates:
1690  break;
1691  case Comdat::Largest:
1692  case Comdat::SameSize:
1693  return false;
1694  }
1695  }
1696 
1697  if (G->hasSection()) {
1698  StringRef Section = G->getSection();
1699 
1700  // Globals from llvm.metadata aren't emitted, do not instrument them.
1701  if (Section == "llvm.metadata") return false;
1702  // Do not instrument globals from special LLVM sections.
1703  if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
1704 
1705  // Do not instrument function pointers to initialization and termination
1706  // routines: dynamic linker will not properly handle redzones.
1707  if (Section.startswith(".preinit_array") ||
1708  Section.startswith(".init_array") ||
1709  Section.startswith(".fini_array")) {
1710  return false;
1711  }
1712 
1713  // On COFF, if the section name contains '$', it is highly likely that the
1714  // user is using section sorting to create an array of globals similar to
1715  // the way initialization callbacks are registered in .init_array and
1716  // .CRT$XCU. The ATL also registers things in .ATL$__[azm]. Adding redzones
1717  // to such globals is counterproductive, because the intent is that they
1718  // will form an array, and out-of-bounds accesses are expected.
1719  // See https://github.com/google/sanitizers/issues/305
1720  // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1721  if (TargetTriple.isOSBinFormatCOFF() && Section.contains('$')) {
1722  LLVM_DEBUG(dbgs() << "Ignoring global in sorted section (contains '$'): "
1723  << *G << "\n");
1724  return false;
1725  }
1726 
1727  if (TargetTriple.isOSBinFormatMachO()) {
1728  StringRef ParsedSegment, ParsedSection;
1729  unsigned TAA = 0, StubSize = 0;
1730  bool TAAParsed;
1731  std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1732  Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1733  assert(ErrorCode.empty() && "Invalid section specifier.");
1734 
1735  // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1736  // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1737  // them.
1738  if (ParsedSegment == "__OBJC" ||
1739  (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1740  LLVM_DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1741  return false;
1742  }
1743  // See https://github.com/google/sanitizers/issues/32
1744  // Constant CFString instances are compiled in the following way:
1745  // -- the string buffer is emitted into
1746  // __TEXT,__cstring,cstring_literals
1747  // -- the constant NSConstantString structure referencing that buffer
1748  // is placed into __DATA,__cfstring
1749  // Therefore there's no point in placing redzones into __DATA,__cfstring.
1750  // Moreover, it causes the linker to crash on OS X 10.7
1751  if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1752  LLVM_DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1753  return false;
1754  }
1755  // The linker merges the contents of cstring_literals and removes the
1756  // trailing zeroes.
1757  if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1758  LLVM_DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1759  return false;
1760  }
1761  }
1762  }
1763 
1764  return true;
1765 }
1766 
1767 // On Mach-O platforms, we emit global metadata in a separate section of the
1768 // binary in order to allow the linker to properly dead strip. This is only
1769 // supported on recent versions of ld64.
1770 bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1771  if (!TargetTriple.isOSBinFormatMachO())
1772  return false;
1773 
1774  if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1775  return true;
1776  if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
1777  return true;
1778  if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1779  return true;
1780 
1781  return false;
1782 }
1783 
1784 StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1785  switch (TargetTriple.getObjectFormat()) {
1786  case Triple::COFF: return ".ASAN$GL";
1787  case Triple::ELF: return "asan_globals";
1788  case Triple::MachO: return "__DATA,__asan_globals,regular";
1789  default: break;
1790  }
1791  llvm_unreachable("unsupported object format");
1792 }
1793 
1794 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1795  IRBuilder<> IRB(*C);
1796 
1797  // Declare our poisoning and unpoisoning functions.
1799  kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
1800  AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1801  AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1802  kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
1803  AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1804 
1805  // Declare functions that register/unregister globals.
1806  AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1807  kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
1808  AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1809  AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1810  M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1811  IntptrTy, IntptrTy));
1812  AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1813 
1814  // Declare the functions that find globals in a shared object and then invoke
1815  // the (un)register function on them.
1816  AsanRegisterImageGlobals =
1818  kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
1819  AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
1820 
1821  AsanUnregisterImageGlobals =
1823  kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
1824  AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
1825 
1826  AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1827  M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1828  IntptrTy, IntptrTy, IntptrTy));
1829  AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1830 
1831  AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1832  M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1833  IntptrTy, IntptrTy, IntptrTy));
1834  AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
1835 }
1836 
1837 // Put the metadata and the instrumented global in the same group. This ensures
1838 // that the metadata is discarded if the instrumented global is discarded.
1839 void AddressSanitizerModule::SetComdatForGlobalMetadata(
1840  GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
1841  Module &M = *G->getParent();
1842  Comdat *C = G->getComdat();
1843  if (!C) {
1844  if (!G->hasName()) {
1845  // If G is unnamed, it must be internal. Give it an artificial name
1846  // so we can put it in a comdat.
1847  assert(G->hasLocalLinkage());
1848  G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1849  }
1850 
1851  if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1852  std::string Name = G->getName();
1853  Name += InternalSuffix;
1854  C = M.getOrInsertComdat(Name);
1855  } else {
1856  C = M.getOrInsertComdat(G->getName());
1857  }
1858 
1859  // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
1860  // linkage to internal linkage so that a symbol table entry is emitted. This
1861  // is necessary in order to create the comdat group.
1862  if (TargetTriple.isOSBinFormatCOFF()) {
1864  if (G->hasPrivateLinkage())
1866  }
1867  G->setComdat(C);
1868  }
1869 
1870  assert(G->hasComdat());
1871  Metadata->setComdat(G->getComdat());
1872 }
1873 
1874 // Create a separate metadata global and put it in the appropriate ASan
1875 // global registration section.
1877 AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1878  StringRef OriginalName) {
1879  auto Linkage = TargetTriple.isOSBinFormatMachO()
1882  GlobalVariable *Metadata = new GlobalVariable(
1883  M, Initializer->getType(), false, Linkage, Initializer,
1884  Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
1885  Metadata->setSection(getGlobalMetadataSection());
1886  return Metadata;
1887 }
1888 
1889 IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
1890  AsanDtorFunction =
1892  GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1893  BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1894 
1895  return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1896 }
1897 
1898 void AddressSanitizerModule::InstrumentGlobalsCOFF(
1899  IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1900  ArrayRef<Constant *> MetadataInitializers) {
1901  assert(ExtendedGlobals.size() == MetadataInitializers.size());
1902  auto &DL = M.getDataLayout();
1903 
1904  for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1905  Constant *Initializer = MetadataInitializers[i];
1906  GlobalVariable *G = ExtendedGlobals[i];
1907  GlobalVariable *Metadata =
1908  CreateMetadataGlobal(M, Initializer, G->getName());
1909 
1910  // The MSVC linker always inserts padding when linking incrementally. We
1911  // cope with that by aligning each struct to its size, which must be a power
1912  // of two.
1913  unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1914  assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1915  "global metadata will not be padded appropriately");
1916  Metadata->setAlignment(SizeOfGlobalStruct);
1917 
1918  SetComdatForGlobalMetadata(G, Metadata, "");
1919  }
1920 }
1921 
1922 void AddressSanitizerModule::InstrumentGlobalsELF(
1923  IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1924  ArrayRef<Constant *> MetadataInitializers,
1925  const std::string &UniqueModuleId) {
1926  assert(ExtendedGlobals.size() == MetadataInitializers.size());
1927 
1928  SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1929  for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1930  GlobalVariable *G = ExtendedGlobals[i];
1931  GlobalVariable *Metadata =
1932  CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1934  Metadata->setMetadata(LLVMContext::MD_associated, MD);
1935  MetadataGlobals[i] = Metadata;
1936 
1937  SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1938  }
1939 
1940  // Update llvm.compiler.used, adding the new metadata globals. This is
1941  // needed so that during LTO these variables stay alive.
1942  if (!MetadataGlobals.empty())
1943  appendToCompilerUsed(M, MetadataGlobals);
1944 
1945  // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1946  // to look up the loaded image that contains it. Second, we can store in it
1947  // whether registration has already occurred, to prevent duplicate
1948  // registration.
1949  //
1950  // Common linkage ensures that there is only one global per shared library.
1951  GlobalVariable *RegisteredFlag = new GlobalVariable(
1952  M, IntptrTy, false, GlobalVariable::CommonLinkage,
1953  ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1955 
1956  // Create start and stop symbols.
1957  GlobalVariable *StartELFMetadata = new GlobalVariable(
1958  M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1959  "__start_" + getGlobalMetadataSection());
1961  GlobalVariable *StopELFMetadata = new GlobalVariable(
1962  M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1963  "__stop_" + getGlobalMetadataSection());
1965 
1966  // Create a call to register the globals with the runtime.
1967  IRB.CreateCall(AsanRegisterElfGlobals,
1968  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1969  IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1970  IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1971 
1972  // We also need to unregister globals at the end, e.g., when a shared library
1973  // gets closed.
1974  IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1975  IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1976  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1977  IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1978  IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1979 }
1980 
1981 void AddressSanitizerModule::InstrumentGlobalsMachO(
1982  IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1983  ArrayRef<Constant *> MetadataInitializers) {
1984  assert(ExtendedGlobals.size() == MetadataInitializers.size());
1985 
1986  // On recent Mach-O platforms, use a structure which binds the liveness of
1987  // the global variable to the metadata struct. Keep the list of "Liveness" GV
1988  // created to be added to llvm.compiler.used
1989  StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
1990  SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1991 
1992  for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1993  Constant *Initializer = MetadataInitializers[i];
1994  GlobalVariable *G = ExtendedGlobals[i];
1995  GlobalVariable *Metadata =
1996  CreateMetadataGlobal(M, Initializer, G->getName());
1997 
1998  // On recent Mach-O platforms, we emit the global metadata in a way that
1999  // allows the linker to properly strip dead globals.
2000  auto LivenessBinder =
2001  ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
2002  ConstantExpr::getPointerCast(Metadata, IntptrTy));
2003  GlobalVariable *Liveness = new GlobalVariable(
2004  M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
2005  Twine("__asan_binder_") + G->getName());
2006  Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
2007  LivenessGlobals[i] = Liveness;
2008  }
2009 
2010  // Update llvm.compiler.used, adding the new liveness globals. This is
2011  // needed so that during LTO these variables stay alive. The alternative
2012  // would be to have the linker handling the LTO symbols, but libLTO
2013  // current API does not expose access to the section for each symbol.
2014  if (!LivenessGlobals.empty())
2015  appendToCompilerUsed(M, LivenessGlobals);
2016 
2017  // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2018  // to look up the loaded image that contains it. Second, we can store in it
2019  // whether registration has already occurred, to prevent duplicate
2020  // registration.
2021  //
2022  // common linkage ensures that there is only one global per shared library.
2023  GlobalVariable *RegisteredFlag = new GlobalVariable(
2024  M, IntptrTy, false, GlobalVariable::CommonLinkage,
2025  ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2027 
2028  IRB.CreateCall(AsanRegisterImageGlobals,
2029  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
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(AsanUnregisterImageGlobals,
2035  {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2036 }
2037 
2038 void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
2039  IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2040  ArrayRef<Constant *> MetadataInitializers) {
2041  assert(ExtendedGlobals.size() == MetadataInitializers.size());
2042  unsigned N = ExtendedGlobals.size();
2043  assert(N > 0);
2044 
2045  // On platforms that don't have a custom metadata section, we emit an array
2046  // of global metadata structures.
2047  ArrayType *ArrayOfGlobalStructTy =
2048  ArrayType::get(MetadataInitializers[0]->getType(), N);
2049  auto AllGlobals = new GlobalVariable(
2050  M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
2051  ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
2052  if (Mapping.Scale > 3)
2053  AllGlobals->setAlignment(1ULL << Mapping.Scale);
2054 
2055  IRB.CreateCall(AsanRegisterGlobals,
2056  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2057  ConstantInt::get(IntptrTy, N)});
2058 
2059  // We also need to unregister globals at the end, e.g., when a shared library
2060  // gets closed.
2061  IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2062  IRB_Dtor.CreateCall(AsanUnregisterGlobals,
2063  {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2064  ConstantInt::get(IntptrTy, N)});
2065 }
2066 
2067 // This function replaces all global variables with new variables that have
2068 // trailing redzones. It also creates a function that poisons
2069 // redzones and inserts this function into llvm.global_ctors.
2070 // Sets *CtorComdat to true if the global registration code emitted into the
2071 // asan constructor is comdat-compatible.
2072 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
2073  *CtorComdat = false;
2074  GlobalsMD.init(M);
2075 
2076  SmallVector<GlobalVariable *, 16> GlobalsToChange;
2077 
2078  for (auto &G : M.globals()) {
2079  if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
2080  }
2081 
2082  size_t n = GlobalsToChange.size();
2083  if (n == 0) {
2084  *CtorComdat = true;
2085  return false;
2086  }
2087 
2088  auto &DL = M.getDataLayout();
2089 
2090  // A global is described by a structure
2091  // size_t beg;
2092  // size_t size;
2093  // size_t size_with_redzone;
2094  // const char *name;
2095  // const char *module_name;
2096  // size_t has_dynamic_init;
2097  // void *source_location;
2098  // size_t odr_indicator;
2099  // We initialize an array of such structures and pass it to a run-time call.
2100  StructType *GlobalStructTy =
2101  StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
2102  IntptrTy, IntptrTy, IntptrTy);
2103  SmallVector<GlobalVariable *, 16> NewGlobals(n);
2104  SmallVector<Constant *, 16> Initializers(n);
2105 
2106  bool HasDynamicallyInitializedGlobals = false;
2107 
2108  // We shouldn't merge same module names, as this string serves as unique
2109  // module ID in runtime.
2111  M, M.getModuleIdentifier(), /*AllowMerging*/ false);
2112 
2113  for (size_t i = 0; i < n; i++) {
2114  static const uint64_t kMaxGlobalRedzone = 1 << 18;
2115  GlobalVariable *G = GlobalsToChange[i];
2116 
2117  auto MD = GlobalsMD.get(G);
2118  StringRef NameForGlobal = G->getName();
2119  // Create string holding the global name (use global name from metadata
2120  // if it's available, otherwise just write the name of global variable).
2122  M, MD.Name.empty() ? NameForGlobal : MD.Name,
2123  /*AllowMerging*/ true);
2124 
2125  Type *Ty = G->getValueType();
2126  uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
2127  uint64_t MinRZ = MinRedzoneSizeForGlobal();
2128  // MinRZ <= RZ <= kMaxGlobalRedzone
2129  // and trying to make RZ to be ~ 1/4 of SizeInBytes.
2130  uint64_t RZ = std::max(
2131  MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
2132  uint64_t RightRedzoneSize = RZ;
2133  // Round up to MinRZ
2134  if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
2135  assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
2136  Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2137 
2138  StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2139  Constant *NewInitializer = ConstantStruct::get(
2140  NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
2141 
2142  // Create a new global variable with enough space for a redzone.
2143  GlobalValue::LinkageTypes Linkage = G->getLinkage();
2144  if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2145  Linkage = GlobalValue::InternalLinkage;
2146  GlobalVariable *NewGlobal =
2147  new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2148  "", G, G->getThreadLocalMode());
2149  NewGlobal->copyAttributesFrom(G);
2150  NewGlobal->setComdat(G->getComdat());
2151  NewGlobal->setAlignment(MinRZ);
2152 
2153  // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2154  if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2155  G->isConstant()) {
2156  auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2157  if (Seq && Seq->isCString())
2158  NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2159  }
2160 
2161  // Transfer the debug info. The payload starts at offset zero so we can
2162  // copy the debug info over as is.
2164  G->getDebugInfo(GVs);
2165  for (auto *GV : GVs)
2166  NewGlobal->addDebugInfo(GV);
2167 
2168  Value *Indices2[2];
2169  Indices2[0] = IRB.getInt32(0);
2170  Indices2[1] = IRB.getInt32(0);
2171 
2172  G->replaceAllUsesWith(
2173  ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
2174  NewGlobal->takeName(G);
2175  G->eraseFromParent();
2176  NewGlobals[i] = NewGlobal;
2177 
2178  Constant *SourceLoc;
2179  if (!MD.SourceLoc.empty()) {
2180  auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2181  SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2182  } else {
2183  SourceLoc = ConstantInt::get(IntptrTy, 0);
2184  }
2185 
2186  Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2187  GlobalValue *InstrumentedGlobal = NewGlobal;
2188 
2189  bool CanUsePrivateAliases =
2190  TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2191  TargetTriple.isOSBinFormatWasm();
2192  if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
2193  // Create local alias for NewGlobal to avoid crash on ODR between
2194  // instrumented and non-instrumented libraries.
2196  NameForGlobal + M.getName(), NewGlobal);
2197 
2198  // With local aliases, we need to provide another externally visible
2199  // symbol __odr_asan_XXX to detect ODR violation.
2200  auto *ODRIndicatorSym =
2201  new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2203  kODRGenPrefix + NameForGlobal, nullptr,
2204  NewGlobal->getThreadLocalMode());
2205 
2206  // Set meaningful attributes for indicator symbol.
2207  ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2208  ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2209  ODRIndicatorSym->setAlignment(1);
2210  ODRIndicator = ODRIndicatorSym;
2211  InstrumentedGlobal = GA;
2212  }
2213 
2214  Constant *Initializer = ConstantStruct::get(
2215  GlobalStructTy,
2216  ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
2217  ConstantInt::get(IntptrTy, SizeInBytes),
2218  ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2219  ConstantExpr::getPointerCast(Name, IntptrTy),
2220  ConstantExpr::getPointerCast(ModuleName, IntptrTy),
2221  ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
2222  ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
2223 
2224  if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
2225 
2226  LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
2227 
2228  Initializers[i] = Initializer;
2229  }
2230 
2231  // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2232  // ConstantMerge'ing them.
2233  SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2234  for (size_t i = 0; i < n; i++) {
2235  GlobalVariable *G = NewGlobals[i];
2236  if (G->getName().empty()) continue;
2237  GlobalsToAddToUsedList.push_back(G);
2238  }
2239  appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2240 
2241  std::string ELFUniqueModuleId =
2242  (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2243  : "";
2244 
2245  if (!ELFUniqueModuleId.empty()) {
2246  InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2247  *CtorComdat = true;
2248  } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
2249  InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2250  } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2251  InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2252  } else {
2253  InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2254  }
2255 
2256  // Create calls for poisoning before initializers run and unpoisoning after.
2257  if (HasDynamicallyInitializedGlobals)
2258  createInitializerPoisonCalls(M, ModuleName);
2259 
2260  LLVM_DEBUG(dbgs() << M);
2261  return true;
2262 }
2263 
2264 int AddressSanitizerModule::GetAsanVersion(const Module &M) const {
2265  int LongSize = M.getDataLayout().getPointerSizeInBits();
2266  bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2267  int Version = 8;
2268  // 32-bit Android is one version ahead because of the switch to dynamic
2269  // shadow.
2270  Version += (LongSize == 32 && isAndroid);
2271  return Version;
2272 }
2273 
2274 bool AddressSanitizerModule::runOnModule(Module &M) {
2275  C = &(M.getContext());
2276  int LongSize = M.getDataLayout().getPointerSizeInBits();
2277  IntptrTy = Type::getIntNTy(*C, LongSize);
2278  TargetTriple = Triple(M.getTargetTriple());
2279  Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2280  initializeCallbacks(M);
2281 
2282  if (CompileKernel)
2283  return false;
2284 
2285  // Create a module constructor. A destructor is created lazily because not all
2286  // platforms, and not all modules need it.
2287  std::string VersionCheckName =
2288  kAsanVersionCheckNamePrefix + std::to_string(GetAsanVersion(M));
2289  std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2290  M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
2291  /*InitArgs=*/{}, VersionCheckName);
2292 
2293  bool CtorComdat = true;
2294  bool Changed = false;
2295  // TODO(glider): temporarily disabled globals instrumentation for KASan.
2296  if (ClGlobals) {
2297  IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2298  Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2299  }
2300 
2301  // Put the constructor and destructor in comdat if both
2302  // (1) global instrumentation is not TU-specific
2303  // (2) target is ELF.
2304  if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2305  AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2306  appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2307  AsanCtorFunction);
2308  if (AsanDtorFunction) {
2309  AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2310  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2311  AsanDtorFunction);
2312  }
2313  } else {
2314  appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2315  if (AsanDtorFunction)
2316  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
2317  }
2318 
2319  return Changed;
2320 }
2321 
2322 void AddressSanitizer::initializeCallbacks(Module &M) {
2323  IRBuilder<> IRB(*C);
2324  // Create __asan_report* callbacks.
2325  // IsWrite, TypeSize and Exp are encoded in the function name.
2326  for (int Exp = 0; Exp < 2; Exp++) {
2327  for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2328  const std::string TypeStr = AccessIsWrite ? "store" : "load";
2329  const std::string ExpStr = Exp ? "exp_" : "";
2330  const std::string EndingStr = Recover ? "_noabort" : "";
2331 
2332  SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2333  SmallVector<Type *, 2> Args1{1, IntptrTy};
2334  if (Exp) {
2335  Type *ExpType = Type::getInt32Ty(*C);
2336  Args2.push_back(ExpType);
2337  Args1.push_back(ExpType);
2338  }
2339  AsanErrorCallbackSized[AccessIsWrite][Exp] =
2341  kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
2342  FunctionType::get(IRB.getVoidTy(), Args2, false)));
2343 
2344  AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2346  ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2347  FunctionType::get(IRB.getVoidTy(), Args2, false)));
2348 
2349  for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2350  AccessSizeIndex++) {
2351  const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2352  AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2354  kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2355  FunctionType::get(IRB.getVoidTy(), Args1, false)));
2356 
2357  AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2359  ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2360  FunctionType::get(IRB.getVoidTy(), Args1, false)));
2361  }
2362  }
2363  }
2364 
2365  const std::string MemIntrinCallbackPrefix =
2366  CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
2368  MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
2369  IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
2371  MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
2372  IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
2374  MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
2375  IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
2376 
2377  AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
2378  M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
2379 
2381  kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
2383  kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
2384  // We insert an empty inline asm after __asan_report* to avoid callback merge.
2385  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2386  StringRef(""), StringRef(""),
2387  /*hasSideEffects=*/true);
2388  if (Mapping.InGlobal)
2389  AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2390  ArrayType::get(IRB.getInt8Ty(), 0));
2391 }
2392 
2393 // virtual
2394 bool AddressSanitizer::doInitialization(Module &M) {
2395  // Initialize the private fields. No one has accessed them before.
2396  GlobalsMD.init(M);
2397 
2398  C = &(M.getContext());
2399  LongSize = M.getDataLayout().getPointerSizeInBits();
2400  IntptrTy = Type::getIntNTy(*C, LongSize);
2401  TargetTriple = Triple(M.getTargetTriple());
2402 
2403  Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2404  return true;
2405 }
2406 
2407 bool AddressSanitizer::doFinalization(Module &M) {
2408  GlobalsMD.reset();
2409  return false;
2410 }
2411 
2412 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2413  // For each NSObject descendant having a +load method, this method is invoked
2414  // by the ObjC runtime before any of the static constructors is called.
2415  // Therefore we need to instrument such methods with a call to __asan_init
2416  // at the beginning in order to initialize our runtime before any access to
2417  // the shadow memory.
2418  // We cannot just ignore these methods, because they may call other
2419  // instrumented functions.
2420  if (F.getName().find(" load]") != std::string::npos) {
2421  Function *AsanInitFunction =
2423  IRBuilder<> IRB(&F.front(), F.front().begin());
2424  IRB.CreateCall(AsanInitFunction, {});
2425  return true;
2426  }
2427  return false;
2428 }
2429 
2430 void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2431  // Generate code only when dynamic addressing is needed.
2432  if (Mapping.Offset != kDynamicShadowSentinel)
2433  return;
2434 
2435  IRBuilder<> IRB(&F.front().front());
2436  if (Mapping.InGlobal) {
2438  // An empty inline asm with input reg == output reg.
2439  // An opaque pointer-to-int cast, basically.
2441  FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2442  StringRef(""), StringRef("=r,0"),
2443  /*hasSideEffects=*/false);
2444  LocalDynamicShadow =
2445  IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2446  } else {
2447  LocalDynamicShadow =
2448  IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2449  }
2450  } else {
2451  Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2452  kAsanShadowMemoryDynamicAddress, IntptrTy);
2453  LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2454  }
2455 }
2456 
2457 void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2458  // Find the one possible call to llvm.localescape and pre-mark allocas passed
2459  // to it as uninteresting. This assumes we haven't started processing allocas
2460  // yet. This check is done up front because iterating the use list in
2461  // isInterestingAlloca would be algorithmically slower.
2462  assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2463 
2464  // Try to get the declaration of llvm.localescape. If it's not in the module,
2465  // we can exit early.
2466  if (!F.getParent()->getFunction("llvm.localescape")) return;
2467 
2468  // Look for a call to llvm.localescape call in the entry block. It can't be in
2469  // any other block.
2470  for (Instruction &I : F.getEntryBlock()) {
2472  if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2473  // We found a call. Mark all the allocas passed in as uninteresting.
2474  for (Value *Arg : II->arg_operands()) {
2476  assert(AI && AI->isStaticAlloca() &&
2477  "non-static alloca arg to localescape");
2478  ProcessedAllocas[AI] = false;
2479  }
2480  break;
2481  }
2482  }
2483 }
2484 
2486  if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2487  if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2488  if (F.getName().startswith("__asan_")) return false;
2489 
2490  bool FunctionModified = false;
2491 
2492  // If needed, insert __asan_init before checking for SanitizeAddress attr.
2493  // This function needs to be called even if the function body is not
2494  // instrumented.
2495  if (maybeInsertAsanInitAtFunctionEntry(F))
2496  FunctionModified = true;
2497 
2498  // Leave if the function doesn't need instrumentation.
2499  if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2500 
2501  LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2502 
2503  initializeCallbacks(*F.getParent());
2504  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2505 
2506  FunctionStateRAII CleanupObj(this);
2507 
2508  maybeInsertDynamicShadowAtFunctionEntry(F);
2509 
2510  // We can't instrument allocas used with llvm.localescape. Only static allocas
2511  // can be passed to that intrinsic.
2512  markEscapedLocalAllocas(F);
2513 
2514  // We want to instrument every address only once per basic block (unless there
2515  // are calls between uses).
2516  SmallPtrSet<Value *, 16> TempsToInstrument;
2517  SmallVector<Instruction *, 16> ToInstrument;
2518  SmallVector<Instruction *, 8> NoReturnCalls;
2520  SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2521  int NumAllocas = 0;
2522  bool IsWrite;
2523  unsigned Alignment;
2524  uint64_t TypeSize;
2525  const TargetLibraryInfo *TLI =
2526  &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2527 
2528  // Fill the set of memory operations to instrument.
2529  for (auto &BB : F) {
2530  AllBlocks.push_back(&BB);
2531  TempsToInstrument.clear();
2532  int NumInsnsPerBB = 0;
2533  for (auto &Inst : BB) {
2534  if (LooksLikeCodeInBug11395(&Inst)) return false;
2535  Value *MaybeMask = nullptr;
2536  if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
2537  &Alignment, &MaybeMask)) {
2538  if (ClOpt && ClOptSameTemp) {
2539  // If we have a mask, skip instrumentation if we've already
2540  // instrumented the full object. But don't add to TempsToInstrument
2541  // because we might get another load/store with a different mask.
2542  if (MaybeMask) {
2543  if (TempsToInstrument.count(Addr))
2544  continue; // We've seen this (whole) temp in the current BB.
2545  } else {
2546  if (!TempsToInstrument.insert(Addr).second)
2547  continue; // We've seen this temp in the current BB.
2548  }
2549  }
2550  } else if (ClInvalidPointerPairs &&
2552  PointerComparisonsOrSubtracts.push_back(&Inst);
2553  continue;
2554  } else if (isa<MemIntrinsic>(Inst)) {
2555  // ok, take it.
2556  } else {
2557  if (isa<AllocaInst>(Inst)) NumAllocas++;
2558  CallSite CS(&Inst);
2559  if (CS) {
2560  // A call inside BB.
2561  TempsToInstrument.clear();
2562  if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
2563  }
2564  if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2566  continue;
2567  }
2568  ToInstrument.push_back(&Inst);
2569  NumInsnsPerBB++;
2570  if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
2571  }
2572  }
2573 
2574  bool UseCalls =
2577  const DataLayout &DL = F.getParent()->getDataLayout();
2578  ObjectSizeOpts ObjSizeOpts;
2579  ObjSizeOpts.RoundToAlign = true;
2580  ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
2581 
2582  // Instrument.
2583  int NumInstrumented = 0;
2584  for (auto Inst : ToInstrument) {
2585  if (ClDebugMin < 0 || ClDebugMax < 0 ||
2586  (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
2587  if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
2588  instrumentMop(ObjSizeVis, Inst, UseCalls,
2589  F.getParent()->getDataLayout());
2590  else
2591  instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
2592  }
2593  NumInstrumented++;
2594  }
2595 
2596  FunctionStackPoisoner FSP(F, *this);
2597  bool ChangedStack = FSP.runOnFunction();
2598 
2599  // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2600  // See e.g. https://github.com/google/sanitizers/issues/37
2601  for (auto CI : NoReturnCalls) {
2602  IRBuilder<> IRB(CI);
2603  IRB.CreateCall(AsanHandleNoReturnFunc, {});
2604  }
2605 
2606  for (auto Inst : PointerComparisonsOrSubtracts) {
2607  instrumentPointerComparisonOrSubtraction(Inst);
2608  NumInstrumented++;
2609  }
2610 
2611  if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2612  FunctionModified = true;
2613 
2614  LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2615  << F << "\n");
2616 
2617  return FunctionModified;
2618 }
2619 
2620 // Workaround for bug 11395: we don't want to instrument stack in functions
2621 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2622 // FIXME: remove once the bug 11395 is fixed.
2623 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2624  if (LongSize != 32) return false;
2625  CallInst *CI = dyn_cast<CallInst>(I);
2626  if (!CI || !CI->isInlineAsm()) return false;
2627  if (CI->getNumArgOperands() <= 5) return false;
2628  // We have inline assembly with quite a few arguments.
2629  return true;
2630 }
2631 
2632 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2633  IRBuilder<> IRB(*C);
2634  for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2635  std::string Suffix = itostr(i);
2636  AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2637  M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
2638  IntptrTy));
2639  AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
2640  M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2641  IRB.getVoidTy(), IntptrTy, IntptrTy));
2642  }
2643  if (ASan.UseAfterScope) {
2644  AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2645  M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2646  IntptrTy, IntptrTy));
2647  AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2648  M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2649  IntptrTy, IntptrTy));
2650  }
2651 
2652  for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2653  std::ostringstream Name;
2654  Name << kAsanSetShadowPrefix;
2655  Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2656  AsanSetShadowFunc[Val] =
2658  Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
2659  }
2660 
2661  AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2662  kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
2663  AsanAllocasUnpoisonFunc =
2665  kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
2666 }
2667 
2668 void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2669  ArrayRef<uint8_t> ShadowBytes,
2670  size_t Begin, size_t End,
2671  IRBuilder<> &IRB,
2672  Value *ShadowBase) {
2673  if (Begin >= End)
2674  return;
2675 
2676  const size_t LargestStoreSizeInBytes =
2677  std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2678 
2679  const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2680 
2681  // Poison given range in shadow using larges store size with out leading and
2682  // trailing zeros in ShadowMask. Zeros never change, so they need neither
2683  // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2684  // middle of a store.
2685  for (size_t i = Begin; i < End;) {
2686  if (!ShadowMask[i]) {
2687  assert(!ShadowBytes[i]);
2688  ++i;
2689  continue;
2690  }
2691 
2692  size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2693  // Fit store size into the range.
2694  while (StoreSizeInBytes > End - i)
2695  StoreSizeInBytes /= 2;
2696 
2697  // Minimize store size by trimming trailing zeros.
2698  for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2699  while (j <= StoreSizeInBytes / 2)
2700  StoreSizeInBytes /= 2;
2701  }
2702 
2703  uint64_t Val = 0;
2704  for (size_t j = 0; j < StoreSizeInBytes; j++) {
2705  if (IsLittleEndian)
2706  Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2707  else
2708  Val = (Val << 8) | ShadowBytes[i + j];
2709  }
2710 
2711  Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2712  Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
2713  IRB.CreateAlignedStore(
2714  Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
2715 
2716  i += StoreSizeInBytes;
2717  }
2718 }
2719 
2720 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2721  ArrayRef<uint8_t> ShadowBytes,
2722  IRBuilder<> &IRB, Value *ShadowBase) {
2723  copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2724 }
2725 
2726 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2727  ArrayRef<uint8_t> ShadowBytes,
2728  size_t Begin, size_t End,
2729  IRBuilder<> &IRB, Value *ShadowBase) {
2730  assert(ShadowMask.size() == ShadowBytes.size());
2731  size_t Done = Begin;
2732  for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2733  if (!ShadowMask[i]) {
2734  assert(!ShadowBytes[i]);
2735  continue;
2736  }
2737  uint8_t Val = ShadowBytes[i];
2738  if (!AsanSetShadowFunc[Val])
2739  continue;
2740 
2741  // Skip same values.
2742  for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
2743  }
2744 
2745  if (j - i >= ClMaxInlinePoisoningSize) {
2746  copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
2747  IRB.CreateCall(AsanSetShadowFunc[Val],
2748  {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2749  ConstantInt::get(IntptrTy, j - i)});
2750  Done = j;
2751  }
2752  }
2753 
2754  copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
2755 }
2756 
2757 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
2758 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2759 static int StackMallocSizeClass(uint64_t LocalStackSize) {
2760  assert(LocalStackSize <= kMaxStackMallocSize);
2761  uint64_t MaxSize = kMinStackMallocSize;
2762  for (int i = 0;; i++, MaxSize *= 2)
2763  if (LocalStackSize <= MaxSize) return i;
2764  llvm_unreachable("impossible LocalStackSize");
2765 }
2766 
2767 void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
2768  Instruction *CopyInsertPoint = &F.front().front();
2769  if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2770  // Insert after the dynamic shadow location is determined
2771  CopyInsertPoint = CopyInsertPoint->getNextNode();
2772  assert(CopyInsertPoint);
2773  }
2774  IRBuilder<> IRB(CopyInsertPoint);
2775  const DataLayout &DL = F.getParent()->getDataLayout();
2776  for (Argument &Arg : F.args()) {
2777  if (Arg.hasByValAttr()) {
2779  unsigned Align = Arg.getParamAlignment();
2780  if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2781 
2782  AllocaInst *AI = IRB.CreateAlloca(
2783  Ty, nullptr,
2784  (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
2785  ".byval");
2786  AI->setAlignment(Align);
2787  Arg.replaceAllUsesWith(AI);
2788 
2789  uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2790  IRB.CreateMemCpy(AI, Align, &Arg, Align, AllocSize);
2791  }
2792  }
2793 }
2794 
2795 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2796  Value *ValueIfTrue,
2797  Instruction *ThenTerm,
2798  Value *ValueIfFalse) {
2799  PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2800  BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2801  PHI->addIncoming(ValueIfFalse, CondBlock);
2802  BasicBlock *ThenBlock = ThenTerm->getParent();
2803  PHI->addIncoming(ValueIfTrue, ThenBlock);
2804  return PHI;
2805 }
2806 
2807 Value *FunctionStackPoisoner::createAllocaForLayout(
2808  IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2809  AllocaInst *Alloca;
2810  if (Dynamic) {
2811  Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2813  "MyAlloca");
2814  } else {
2815  Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2816  nullptr, "MyAlloca");
2817  assert(Alloca->isStaticAlloca());
2818  }
2819  assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2820  size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2821  Alloca->setAlignment(FrameAlignment);
2822  return IRB.CreatePointerCast(Alloca, IntptrTy);
2823 }
2824 
2825 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2826  BasicBlock &FirstBB = *F.begin();
2827  IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2828  DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2829  IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2830  DynamicAllocaLayout->setAlignment(32);
2831 }
2832 
2833 void FunctionStackPoisoner::processDynamicAllocas() {
2834  if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2835  assert(DynamicAllocaPoisonCallVec.empty());
2836  return;
2837  }
2838 
2839  // Insert poison calls for lifetime intrinsics for dynamic allocas.
2840  for (const auto &APC : DynamicAllocaPoisonCallVec) {
2841  assert(APC.InsBefore);
2842  assert(APC.AI);
2843  assert(ASan.isInterestingAlloca(*APC.AI));
2844  assert(!APC.AI->isStaticAlloca());
2845 
2846  IRBuilder<> IRB(APC.InsBefore);
2847  poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2848  // Dynamic allocas will be unpoisoned unconditionally below in
2849  // unpoisonDynamicAllocas.
2850  // Flag that we need unpoison static allocas.
2851  }
2852 
2853  // Handle dynamic allocas.
2854  createDynamicAllocasInitStorage();
2855  for (auto &AI : DynamicAllocaVec)
2856  handleDynamicAllocaCall(AI);
2857  unpoisonDynamicAllocas();
2858 }
2859 
2860 void FunctionStackPoisoner::processStaticAllocas() {
2861  if (AllocaVec.empty()) {
2862  assert(StaticAllocaPoisonCallVec.empty());
2863  return;
2864  }
2865 
2866  int StackMallocIdx = -1;
2867  DebugLoc EntryDebugLocation;
2868  if (auto SP = F.getSubprogram())
2869  EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
2870 
2871  Instruction *InsBefore = AllocaVec[0];
2872  IRBuilder<> IRB(InsBefore);
2873  IRB.SetCurrentDebugLocation(EntryDebugLocation);
2874 
2875  // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2876  // debug info is broken, because only entry-block allocas are treated as
2877  // regular stack slots.
2878  auto InsBeforeB = InsBefore->getParent();
2879  assert(InsBeforeB == &F.getEntryBlock());
2880  for (auto *AI : StaticAllocasToMoveUp)
2881  if (AI->getParent() == InsBeforeB)
2882  AI->moveBefore(InsBefore);
2883 
2884  // If we have a call to llvm.localescape, keep it in the entry block.
2885  if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2886 
2888  SVD.reserve(AllocaVec.size());
2889  for (AllocaInst *AI : AllocaVec) {
2891  ASan.getAllocaSizeInBytes(*AI),
2892  0,
2893  AI->getAlignment(),
2894  AI,
2895  0,
2896  0};
2897  SVD.push_back(D);
2898  }
2899 
2900  // Minimal header size (left redzone) is 4 pointers,
2901  // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2902  size_t Granularity = 1ULL << Mapping.Scale;
2903  size_t MinHeaderSize = std::max((size_t)ASan.LongSize / 2, Granularity);
2904  const ASanStackFrameLayout &L =
2905  ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
2906 
2907  // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2909  for (auto &Desc : SVD)
2910  AllocaToSVDMap[Desc.AI] = &Desc;
2911 
2912  // Update SVD with information from lifetime intrinsics.
2913  for (const auto &APC : StaticAllocaPoisonCallVec) {
2914  assert(APC.InsBefore);
2915  assert(APC.AI);
2916  assert(ASan.isInterestingAlloca(*APC.AI));
2917  assert(APC.AI->isStaticAlloca());
2918 
2919  ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2920  Desc.LifetimeSize = Desc.Size;
2921  if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2922  if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2923  if (LifetimeLoc->getFile() == FnLoc->getFile())
2924  if (unsigned Line = LifetimeLoc->getLine())
2925  Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2926  }
2927  }
2928  }
2929 
2930  auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2931  LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
2932  uint64_t LocalStackSize = L.FrameSize;
2933  bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2934  LocalStackSize <= kMaxStackMallocSize;
2935  bool DoDynamicAlloca = ClDynamicAllocaStack;
2936  // Don't do dynamic alloca or stack malloc if:
2937  // 1) There is inline asm: too often it makes assumptions on which registers
2938  // are available.
2939  // 2) There is a returns_twice call (typically setjmp), which is
2940  // optimization-hostile, and doesn't play well with introduced indirect
2941  // register-relative calculation of local variable addresses.
2942  DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2943  DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2944 
2945  Value *StaticAlloca =
2946  DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2947 
2948  Value *FakeStack;
2949  Value *LocalStackBase;
2950  Value *LocalStackBaseAlloca;
2951  bool Deref;
2952 
2953  if (DoStackMalloc) {
2954  LocalStackBaseAlloca =
2955  IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
2956  // void *FakeStack = __asan_option_detect_stack_use_after_return
2957  // ? __asan_stack_malloc_N(LocalStackSize)
2958  // : nullptr;
2959  // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
2960  Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2961  kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2962  Value *UseAfterReturnIsEnabled =
2963  IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
2965  Instruction *Term =
2966  SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
2967  IRBuilder<> IRBIf(Term);
2968  IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2969  StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2970  assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2971  Value *FakeStackValue =
2972  IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2973  ConstantInt::get(IntptrTy, LocalStackSize));
2974  IRB.SetInsertPoint(InsBefore);
2975  IRB.SetCurrentDebugLocation(EntryDebugLocation);
2976  FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
2977  ConstantInt::get(IntptrTy, 0));
2978 
2979  Value *NoFakeStack =
2980  IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2981  Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2982  IRBIf.SetInsertPoint(Term);
2983  IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2984  Value *AllocaValue =
2985  DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2986 
2987  IRB.SetInsertPoint(InsBefore);
2988  IRB.SetCurrentDebugLocation(EntryDebugLocation);
2989  LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2990  IRB.SetCurrentDebugLocation(EntryDebugLocation);
2991  IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
2992  Deref = true;
2993  } else {
2994  // void *FakeStack = nullptr;
2995  // void *LocalStackBase = alloca(LocalStackSize);
2996  FakeStack = ConstantInt::get(IntptrTy, 0);
2997  LocalStackBase =
2998  DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
2999  LocalStackBaseAlloca = LocalStackBase;
3000  Deref = false;
3001  }
3002 
3003  // Replace Alloca instructions with base+offset.
3004  for (const auto &Desc : SVD) {
3005  AllocaInst *AI = Desc.AI;
3006  replaceDbgDeclareForAlloca(AI, LocalStackBaseAlloca, DIB, Deref,
3007  Desc.Offset, DIExpression::NoDeref);
3008  Value *NewAllocaPtr = IRB.CreateIntToPtr(
3009  IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
3010  AI->getType());
3011  AI->replaceAllUsesWith(NewAllocaPtr);
3012  }
3013 
3014  // The left-most redzone has enough space for at least 4 pointers.
3015  // Write the Magic value to redzone[0].
3016  Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
3018  BasePlus0);
3019  // Write the frame description constant to redzone[1].
3020  Value *BasePlus1 = IRB.CreateIntToPtr(
3021  IRB.CreateAdd(LocalStackBase,
3022  ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
3023  IntptrPtrTy);
3024  GlobalVariable *StackDescriptionGlobal =
3025  createPrivateGlobalForString(*F.getParent(), DescriptionString,
3026  /*AllowMerging*/ true);
3027  Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
3028  IRB.CreateStore(Description, BasePlus1);
3029  // Write the PC to redzone[2].
3030  Value *BasePlus2 = IRB.CreateIntToPtr(
3031  IRB.CreateAdd(LocalStackBase,
3032  ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
3033  IntptrPtrTy);
3034  IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
3035 
3036  const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
3037 
3038  // Poison the stack red zones at the entry.
3039  Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
3040  // As mask we must use most poisoned case: red zones and after scope.
3041  // As bytes we can use either the same or just red zones only.
3042  copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3043 
3044  if (!StaticAllocaPoisonCallVec.empty()) {
3045  const auto &ShadowInScope = GetShadowBytes(SVD, L);
3046 
3047  // Poison static allocas near lifetime intrinsics.
3048  for (const auto &APC : StaticAllocaPoisonCallVec) {
3049  const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3050  assert(Desc.Offset % L.Granularity == 0);
3051  size_t Begin = Desc.Offset / L.Granularity;
3052  size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
3053 
3054  IRBuilder<> IRB(APC.InsBefore);
3055  copyToShadow(ShadowAfterScope,
3056  APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3057  IRB, ShadowBase);
3058  }
3059  }
3060 
3061  SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
3062  SmallVector<uint8_t, 64> ShadowAfterReturn;
3063 
3064  // (Un)poison the stack before all ret instructions.
3065  for (auto Ret : RetVec) {
3066  IRBuilder<> IRBRet(Ret);
3067  // Mark the current frame as retired.
3069  BasePlus0);
3070  if (DoStackMalloc) {
3071  assert(StackMallocIdx >= 0);
3072  // if FakeStack != 0 // LocalStackBase == FakeStack
3073  // // In use-after-return mode, poison the whole stack frame.
3074  // if StackMallocIdx <= 4
3075  // // For small sizes inline the whole thing:
3076  // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
3077  // **SavedFlagPtr(FakeStack) = 0
3078  // else
3079  // __asan_stack_free_N(FakeStack, LocalStackSize)
3080  // else
3081  // <This is not a fake stack; unpoison the redzones>
3082  Value *Cmp =
3083  IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
3084  TerminatorInst *ThenTerm, *ElseTerm;
3085  SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3086 
3087  IRBuilder<> IRBPoison(ThenTerm);
3088  if (StackMallocIdx <= 4) {
3089  int ClassSize = kMinStackMallocSize << StackMallocIdx;
3090  ShadowAfterReturn.resize(ClassSize / L.Granularity,
3092  copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3093  ShadowBase);
3094  Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
3095  FakeStack,
3096  ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3097  Value *SavedFlagPtr = IRBPoison.CreateLoad(
3098  IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3099  IRBPoison.CreateStore(
3100  Constant::getNullValue(IRBPoison.getInt8Ty()),
3101  IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3102  } else {
3103  // For larger frames call __asan_stack_free_*.
3104  IRBPoison.CreateCall(
3105  AsanStackFreeFunc[StackMallocIdx],
3106  {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
3107  }
3108 
3109  IRBuilder<> IRBElse(ElseTerm);
3110  copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
3111  } else {
3112  copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
3113  }
3114  }
3115 
3116  // We are done. Remove the old unused alloca instructions.
3117  for (auto AI : AllocaVec) AI->eraseFromParent();
3118 }
3119 
3120 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
3121  IRBuilder<> &IRB, bool DoPoison) {
3122  // For now just insert the call to ASan runtime.
3123  Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3124  Value *SizeArg = ConstantInt::get(IntptrTy, Size);
3125  IRB.CreateCall(
3126  DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3127  {AddrArg, SizeArg});
3128 }
3129 
3130 // Handling llvm.lifetime intrinsics for a given %alloca:
3131 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3132 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3133 // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3134 // could be poisoned by previous llvm.lifetime.end instruction, as the
3135 // variable may go in and out of scope several times, e.g. in loops).
3136 // (3) if we poisoned at least one %alloca in a function,
3137 // unpoison the whole stack frame at function exit.
3138 
3139 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
3140  if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
3141  // We're interested only in allocas we can handle.
3142  return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
3143  // See if we've already calculated (or started to calculate) alloca for a
3144  // given value.
3145  AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
3146  if (I != AllocaForValue.end()) return I->second;
3147  // Store 0 while we're calculating alloca for value V to avoid
3148  // infinite recursion if the value references itself.
3149  AllocaForValue[V] = nullptr;
3150  AllocaInst *Res = nullptr;
3151  if (CastInst *CI = dyn_cast<CastInst>(V))
3152  Res = findAllocaForValue(CI->getOperand(0));
3153  else if (PHINode *PN = dyn_cast<PHINode>(V)) {
3154  for (Value *IncValue : PN->incoming_values()) {
3155  // Allow self-referencing phi-nodes.
3156  if (IncValue == PN) continue;
3157  AllocaInst *IncValueAI = findAllocaForValue(IncValue);
3158  // AI for incoming values should exist and should all be equal.
3159  if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3160  return nullptr;
3161  Res = IncValueAI;
3162  }
3163  } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3164  Res = findAllocaForValue(EP->getPointerOperand());
3165  } else {
3166  LLVM_DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V
3167  << "\n");
3168  }
3169  if (Res) AllocaForValue[V] = Res;
3170  return Res;
3171 }
3172 
3173 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
3174  IRBuilder<> IRB(AI);
3175 
3176  const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
3177  const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3178 
3179  Value *Zero = Constant::getNullValue(IntptrTy);
3180  Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3181  Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
3182 
3183  // Since we need to extend alloca with additional memory to locate
3184  // redzones, and OldSize is number of allocated blocks with
3185  // ElementSize size, get allocated memory size in bytes by
3186  // OldSize * ElementSize.
3187  const unsigned ElementSize =
3189  Value *OldSize =
3190  IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3191  ConstantInt::get(IntptrTy, ElementSize));
3192 
3193  // PartialSize = OldSize % 32
3194  Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3195 
3196  // Misalign = kAllocaRzSize - PartialSize;
3197  Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3198 
3199  // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3200  Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3201  Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3202 
3203  // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
3204  // Align is added to locate left redzone, PartialPadding for possible
3205  // partial redzone and kAllocaRzSize for right redzone respectively.
3206  Value *AdditionalChunkSize = IRB.CreateAdd(
3207  ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
3208 
3209  Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3210 
3211  // Insert new alloca with new NewSize and Align params.
3212  AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3213  NewAlloca->setAlignment(Align);
3214 
3215  // NewAddress = Address + Align
3216  Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3217  ConstantInt::get(IntptrTy, Align));
3218 
3219  // Insert __asan_alloca_poison call for new created alloca.
3220  IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
3221 
3222  // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3223  // for unpoisoning stuff.
3224  IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3225 
3226  Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3227 
3228  // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
3229  AI->replaceAllUsesWith(NewAddressPtr);
3230 
3231  // We are done. Erase old alloca from parent.
3232  AI->eraseFromParent();
3233 }
3234 
3235 // isSafeAccess returns true if Addr is always inbounds with respect to its
3236 // base object. For example, it is a field access or an array access with
3237 // constant inbounds index.
3238 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3239  Value *Addr, uint64_t TypeSize) const {
3240  SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3241  if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
3242  uint64_t Size = SizeOffset.first.getZExtValue();
3243  int64_t Offset = SizeOffset.second.getSExtValue();
3244  // Three checks are required to ensure safety:
3245  // . Offset >= 0 (since the offset is given from the base ptr)
3246  // . Size >= Offset (unsigned)
3247  // . Size - Offset >= NeededSize (unsigned)
3248  return Offset >= 0 && Size >= uint64_t(Offset) &&
3249  Size - uint64_t(Offset) >= TypeSize / 8;
3250 }
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:238
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:81
static const uint64_t kMyriadCacheBitMask32
static cl::opt< std::string > ClDebugFunc("asan-debug-func", cl::Hidden, cl::desc("Debug func"))
static bool isValueValidForType(Type *Ty, uint64_t V)
This static method returns true if the type Ty is big enough to represent the value V...
Definition: Constants.cpp:1234
uint64_t CallInst * C
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.compiler.used list.
Return a value (possibly void), from a function.
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:90
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:68
static const char *const kAsanSetShadowPrefix
unsigned getAlignment() const
Definition: GlobalObject.h:59
static const uint64_t kIOSShadowOffset32
static cl::opt< bool > ClStack("asan-stack", cl::desc("Handle stack memory"), cl::Hidden, cl::init(true))
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
Definition: DataLayout.h:419
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:238
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:254
void ReplaceInstWithInst(BasicBlock::InstListType &BIL, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
Function * declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type *> InitArgTypes)
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2479
void appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Same as appendToGlobalCtors(), but for global dtors.
Definition: ModuleUtils.cpp:88
bool hasLocalLinkage() const
Definition: GlobalValue.h:435
static const uint64_t kFreeBSD_ShadowOffset64
static cl::opt< bool > ClInitializers("asan-initialization-order", cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true))
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:22
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static bool GlobalWasGeneratedByCompiler(GlobalVariable *G)
Check if G has been created by a trusted compiler pass.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore, TerminatorInst **ThenTerm, TerminatorInst **ElseTerm, MDNode *BranchWeights=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:1292
Base class for instruction visitors.
Definition: InstVisitor.h:81
static cl::opt< int > ClMappingScale("asan-mapping-scale", cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0))
bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, bool DerefBefore, int Offset, bool DerefAfter)
Replaces llvm.dbg.declare instruction when the alloca it describes is replaced with a new value...
Definition: Local.cpp:1509
Function * checkSanitizerInterfaceFunction(Constant *FuncOrBitcast)
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1740
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:289
bool hasPrivateLinkage() const
Definition: GlobalValue.h:434
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition: StringRef.h:448
static size_t RedzoneSizeForScale(int MappingScale)
static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize, bool IsKasan)
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:142
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1138
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:262
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:137
void setAlignment(unsigned Align)
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:54
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:514
Available for inspection, not emission.
Definition: GlobalValue.h:50
static const char *const kAsanUnregisterElfGlobalsName
static const uintptr_t kCurrentStackFrameMagic
This class represents a function call, abstracting a target machine&#39;s calling convention.
This file contains the declarations for metadata subclasses.
static cl::opt< bool > ClUseAfterReturn("asan-use-after-return", cl::desc("Check stack-use-after-return"), cl::Hidden, cl::init(true))
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:617
static bool isInterestingPointerComparisonOrSubtraction(Instruction *I)
static const char *const kODRGenPrefix
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Definition: Instructions.h:132
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
static cl::opt< bool > ClWithIfunc("asan-with-ifunc", cl::desc("Access dynamic shadow through an ifunc global on " "platforms that support this"), cl::Hidden, cl::init(true))
bool isWatchOS() const
Is this an Apple watchOS triple.
Definition: Triple.h:459
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables...
Externally visible function.
Definition: GlobalValue.h:49
static cl::opt< bool > ClForceDynamicShadow("asan-force-dynamic-shadow", cl::desc("Load shadow address into a local variable for each function"), cl::Hidden, cl::init(false))
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:307
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:39
static cl::opt< int > ClDebug("asan-debug", cl::desc("debug"), cl::Hidden, cl::init(0))
static cl::opt< bool > ClRecover("asan-recover", cl::desc("Enable recovery mode (continue-after-error)."), cl::Hidden, cl::init(false))
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
Definition: Module.h:373
INITIALIZE_PASS_BEGIN(AddressSanitizer, "asan", "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false, false) INITIALIZE_PASS_END(AddressSanitizer
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:360
STATISTIC(NumFunctions, "Total number of functions")
SmallString< 64 > ComputeASanStackFrameDescription(const SmallVectorImpl< ASanStackVariableDescription > &Vars)
A debug info location.
Definition: DebugLoc.h:34
Metadata node.
Definition: Metadata.h:862
StringRef getName() const
Get a short "name" for the module.
Definition: Module.h:225
static cl::opt< bool > ClUseAfterScope("asan-use-after-scope", cl::desc("Check stack-use-after-scope"), cl::Hidden, cl::init(false))
F(f)
static CallInst * Create(Value *Func, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1067
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Definition: DerivedTypes.h:503
bool isOSFuchsia() const
Definition: Triple.h:488
An instruction for reading from memory.
Definition: Instructions.h:164
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:677
This defines the Use class.
void reserve(size_type N)
Definition: SmallVector.h:377
void setAlignment(unsigned Align)
Definition: Globals.cpp:111
static GlobalVariable * createPrivateGlobalForString(Module &M, StringRef Str, bool AllowMerging)
static cl::opt< unsigned long long > ClMappingOffset("asan-mapping-offset", cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden, cl::init(0))
Tentative definitions.
Definition: GlobalValue.h:59
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:128
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:950
static const uint64_t kMyriadDDRTag
bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:258
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align, bool isVolatile=false)
Definition: IRBuilder.h:1346
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:264
static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I, Instruction *InsertBefore, Value *Addr, unsigned Alignment, unsigned Granularity, uint32_t TypeSize, bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:347
static const uint64_t kDefaultShadowScale
static const char *const kAsanShadowMemoryDynamicAddress
static const int kAsanStackUseAfterReturnMagic
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
A tuple of MDNodes.
Definition: Metadata.h:1323
bool doesNotReturn() const
Determine if the call cannot return.
Definition: CallSite.h:497
Type * getPointerElementType() const
Definition: Type.h:373
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:109
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition: IRBuilder.h:352
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:592
PointerType * getType() const
Overload to return most specific pointer type.
Definition: Instructions.h:97
Class to represent struct types.
Definition: DerivedTypes.h:201
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:242
static const uint64_t kSmallX86_64ShadowOffsetBase
static const uint64_t kLinuxKasan_ShadowOffset64
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:639
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:731
This file contains the simple types necessary to represent the attributes associated with functions a...
InstrTy * getInstruction() const
Definition: CallSite.h:92
The linker may choose any COMDAT.
Definition: Comdat.h:35
static const char *const kAsanAllocasUnpoison
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:962
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:295
static const char *const kAsanModuleCtorName
static const uint64_t kIOSSimShadowOffset64
static const uint64_t kMyriadMemoryOffset32
Definition: regcomp.c:191
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:336
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:380
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1321
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1624
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition: Constants.h:201
static const uint64_t kSmallX86_64ShadowOffsetAlignMask
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
static const char *const kAsanPoisonStackMemoryName
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
SmallVector< uint8_t, 64 > GetShadowBytesAfterScope(const SmallVectorImpl< ASanStackVariableDescription > &Vars, const ASanStackFrameLayout &Layout)
std::string itostr(int64_t X)
Definition: StringExtras.h:218
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:570
static const char *const kSanCovGenPrefix
bool empty() const
Definition: Module.h:586
bool isSwiftError() const
Return true if this value is a swifterror value.
Definition: Value.cpp:734
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:283
Class to represent array types.
Definition: DerivedTypes.h:369
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
Definition: Instructions.h:121
static const int kMaxAsanStackMallocSizeClass
static const uint64_t kIOSSimShadowOffset32
static cl::opt< bool > ClOptSameTemp("asan-opt-same-temp", cl::desc("Instrument the same temp just once"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClEnableKasan("asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"), cl::Hidden, cl::init(false))
static const uint64_t kAsanCtorAndDtorPriority
void setComdat(Comdat *C)
Definition: GlobalObject.h:103
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:242
static cl::opt< bool > ClOpt("asan-opt", cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true))
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:200
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:138
bool isLittleEndian() const
Layout endianness...
Definition: DataLayout.h:221
static const uint64_t kWindowsShadowOffset64
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:979
bool isiOS() const
Is this an iOS triple.
Definition: Triple.h:449
An instruction for storing to memory.
Definition: Instructions.h:306
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:151
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition: Constants.h:209
static const uint64_t kMyriadTagShift
LinkageTypes getLinkage() const
Definition: GlobalValue.h:450
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:439
bool isOSNetBSD() const
Definition: Triple.h:476
Debug location.
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:301
iterator begin()
Definition: Function.h:642
static cl::opt< bool > ClAlwaysSlowPath("asan-always-slow-path", cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden, cl::init(false))
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:142
iterator_range< op_iterator > operands()
Definition: Metadata.h:1415
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1001
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:127
static const uint64_t kDefaultShadowOffset32
Value * getOperand(unsigned i) const
Definition: User.h:170
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended or truncated from a 64-bit value.
Definition: IRBuilder.h:318
static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass, const DataLayout &DL, Type *IntptrTy, Value *Mask, Instruction *I, Value *Addr, unsigned Alignment, unsigned Granularity, uint32_t TypeSize, bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp)
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1130
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:328
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return &#39;this&#39;.
Definition: Type.h:301
Value * getOperand(unsigned i_nocapture) const
static cl::opt< bool > ClInstrumentWrites("asan-instrument-writes", cl::desc("instrument write instructions"), cl::Hidden, cl::init(true))
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:560
ExternalWeak linkage description.
Definition: GlobalValue.h:58
const BasicBlock & getEntryBlock() const
Definition: Function.h:626
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:837
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool&#39; fo...
Definition: IRBuilder.h:1305
static const size_t kNumberOfAccessSizes
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1164
static bool runOnFunction(Function &F, bool PostInlining)
static const char *const kAsanGlobalsRegisteredFlagName
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:52
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:410
No other Module may specify this COMDAT.
Definition: Comdat.h:38
static const char *const kAsanPtrCmp
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:149
static std::string ParseSectionSpecifier(StringRef Spec, StringRef &Segment, StringRef &Section, unsigned &TAA, bool &TAAParsed, unsigned &StubSize)
Parse the section specifier indicated by "Spec".
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:55
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:218
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:287
DLLStorageClassTypes getDLLStorageClass() const
Definition: GlobalValue.h:258
std::size_t countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0&#39;s from the least significant bit to the most stopping at the first 1...
Definition: MathExtras.h:112
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:232
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:421
bool hasName() const
Definition: Value.h:251
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
std::pair< Function *, Function * > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type *> InitArgTypes, ArrayRef< Value *> InitArgs, StringRef VersionCheckName=StringRef())
Creates sanitizer constructor function, and calls sanitizer&#39;s init function from it.
VendorType getVendor() const
getVendor - Get the parsed vendor type of this triple.
Definition: Triple.h:289
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1508
Constant * getOrInsertGlobal(StringRef Name, Type *Ty)
Look up the specified global in the module symbol table.
Definition: Module.cpp:202
Conditional or Unconditional Branch instruction.
static const size_t kMinStackMallocSize
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
This function has undefined behavior.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
Resume the propagation of an exception.
static const char *const kAsanInitName
static const char *const kAsanStackFreeNameTemplate
static const uint64_t kNetBSD_ShadowOffset32
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.h:1901
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:221
static const uint64_t kMIPS32_ShadowOffset32
const Instruction & front() const
Definition: BasicBlock.h:276
static const char *const kAsanOptionDetectUseAfterReturn
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:371
static const uint64_t kFreeBSD_ShadowOffset32
static const uint64_t kAArch64_ShadowOffset64
static cl::opt< bool > ClInstrumentReads("asan-instrument-reads", cl::desc("instrument read instructions"), cl::Hidden, cl::init(true))
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:161
bool isAndroidVersionLT(unsigned Major) const
Definition: Triple.h:621
bool isPS4CPU() const
Tests whether the target is the PS4 CPU.
Definition: Triple.h:606
This instruction compares its operands according to the predicate given to the constructor.
static const unsigned End
Value * CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1764
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:297
static Constant * get(StructType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:1011
op_range operands()
Definition: User.h:238
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:101
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1736
ASanStackFrameLayout ComputeASanStackFrameLayout(SmallVectorImpl< ASanStackVariableDescription > &Vars, size_t Granularity, size_t MinHeaderSize)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:382
static cl::opt< bool > ClOptGlobals("asan-opt-globals", cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClUseGlobalsGC("asan-globals-live-support", cl::desc("Use linker features to support dead " "code stripping of globals"), cl::Hidden, cl::init(true))
static const uintptr_t kRetiredStackFrameMagic
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:36
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:1921
static const uint64_t kMyriadShadowScale
static cl::opt< bool > ClUsePrivateAliasForGlobals("asan-use-private-alias", cl::desc("Use private aliases for global" " variables"), cl::Hidden, cl::init(false))
static const char *const kAsanGenPrefix
std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module&#39;s strong...
static const char *const kAsanPtrSub
static cl::opt< int > ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb", cl::init(10000), cl::desc("maximal number of instructions to instrument in any given BB"), cl::Hidden)
S_CSTRING_LITERALS - Section with literal C strings.
Definition: MachO.h:124
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:474
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:538
iterator_range< User::op_iterator > arg_operands()
Iteration adapter for range-for loops.
static cl::opt< bool > ClGlobals("asan-globals", cl::desc("Handle global objects"), cl::Hidden, cl::init(true))
static cl::opt< uint32_t > ClMaxInlinePoisoningSize("asan-max-inline-poisoning-size", cl::desc("Inline shadow poisoning for blocks up to the given size in bytes."), cl::Hidden, cl::init(64))
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:93
std::pair< APInt, APInt > SizeOffsetType
static wasm::ValType getType(const TargetRegisterClass *RC)
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:385
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:208
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
Definition: MDBuilder.cpp:38
static const uint64_t kWindowsShadowOffset32
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void initializeAddressSanitizerPass(PassRegistry &)
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:996
static cl::opt< bool > ClWithComdat("asan-with-comdat", cl::desc("Place ASan constructors in comdat sections"), cl::Hidden, cl::init(true))
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:102
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
static const char *const kAsanRegisterGlobalsName
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:51
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:1866
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1374
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:1554
static const uint64_t kDynamicShadowSentinel
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:240
static cl::opt< int > ClDebugMax("asan-debug-max", cl::desc("Debug max inst"), cl::Hidden, cl::init(-1))
print lazy value Lazy Value Info Printer Pass
This is the common base class for memset/memcpy/memmove.
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition: Constants.h:251
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
void setSelectionKind(SelectionKind Val)
Definition: Comdat.h:46
static const char *const kAsanStackMallocNameTemplate
static const char *const kAsanUnpoisonStackMemoryName
Evaluate the size and offset of an object pointed to by a Value* statically.
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:1698
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:349
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:82
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
static size_t TypeSizeToSizeIndex(uint32_t TypeSize)
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:722
const DataFlowGraph & G
Definition: RDFGraph.cpp:211
bool isOSLinux() const
Tests whether the OS is Linux.
Definition: Triple.h:570
TerminatorInst * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
static const uint64_t kDefaultShadowOffset64
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:307
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:180
static cl::opt< int > ClDebugStack("asan-debug-stack", cl::desc("debug stack"), cl::Hidden, cl::init(0))
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
CallInst * CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memcpy between the specified pointers.
Definition: IRBuilder.h:446
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:611
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
The linker will choose the largest COMDAT.
Definition: Comdat.h:37
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
Definition: ModuleUtils.cpp:84
static cl::opt< bool > ClInvalidPointerPairs("asan-detect-invalid-pointer-pair", cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden, cl::init(false))
static bool isPointerOperand(Value *V)
static cl::opt< int > ClInstrumentationWithCallsThreshold("asan-instrumentation-with-call-threshold", cl::desc("If the function being instrumented contains more than " "this number of memory accesses, use callbacks instead of " "inline checks (-1 means never use callbacks)."), cl::Hidden, cl::init(7000))
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:444
bool isOSFreeBSD() const
Definition: Triple.h:484
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:172
SizeOffsetType compute(Value *V)
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:56
ConstantArray - Constant Array Declarations.
Definition: Constants.h:410
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character &#39;\1&#39;, drop it.
Definition: GlobalValue.h:471
static const uint64_t kSystemZ_ShadowOffset64
static GlobalVariable * createPrivateGlobalForSourceLoc(Module &M, LocationMetadata MD)
Create a global describing a source location.
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:48
static cl::opt< bool > ClWithIfuncSuppressRemat("asan-with-ifunc-suppress-remat", cl::desc("Suppress rematerialization of dynamic shadow address by passing " "it through inline asm in prologue."), cl::Hidden, cl::init(true))
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:337
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1675
bool hasComdat() const
Definition: GlobalObject.h:100
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1434
amdgpu Simplify well known AMD library false Value Value * Arg
static cl::opt< bool > ClSkipPromotableAllocas("asan-skip-promotable-allocas", cl::desc("Do not instrument promotable allocas"), cl::Hidden, cl::init(true))
const Comdat * getComdat() const
Definition: GlobalObject.h:101
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:428
static const uint64_t kMyriadMemorySize32
static cl::opt< int > ClDebugMin("asan-debug-min", cl::desc("Debug min inst"), cl::Hidden, cl::init(-1))
static cl::opt< std::string > ClMemoryAccessCallbackPrefix("asan-memory-access-callback-prefix", cl::desc("Prefix for memory access callbacks"), cl::Hidden, cl::init("__asan_"))
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:290
bool isInlineAsm() const
Check if this call is an inline asm statement.
static const uint64_t kMIPS64_ShadowOffset64
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:215
static const size_t npos
Definition: StringRef.h:51
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
bool isThumb() const
Tests whether the target is Thumb (little and big endian).
Definition: Triple.h:647
static int StackMallocSizeClass(uint64_t LocalStackSize)
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:62
unsigned getNumArgOperands() const
Return the number of call arguments.
static cl::opt< uint32_t > ClForceExperiment("asan-force-experiment", cl::desc("Force optimization experiment (for testing)"), cl::Hidden, cl::init(0))
static const char *const kAsanRegisterElfGlobalsName
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
Definition: APInt.h:475
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:381
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
static cl::opt< bool > ClDynamicAllocaStack("asan-stack-dynamic-alloca", cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden, cl::init(true))
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:225
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:568
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
Type * getValueType() const
Definition: GlobalValue.h:275
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
Definition: Function.h:619
static const uint64_t kNetBSD_ShadowOffset64
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI, const TargetLibraryInfo *TLI)
Given a CallInst, check if it calls a string function known to CodeGen, and mark it with NoBuiltin if...
Definition: Local.cpp:2515
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:43
static const uint64_t kPS4CPU_ShadowOffset64
static const char *const kAsanModuleDtorName
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1112
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1619
const std::string to_string(const T &Value)
Definition: ScopedPrinter.h:62
static uint64_t getAllocaSizeInBytes(const AllocaInst &AI)
static const char *const kAsanUnregisterGlobalsName
iterator_range< df_iterator< T > > depth_first(const T &G)
static const char *const kAsanUnpoisonGlobalsName
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
Definition: Function.h:649
static bool bothKnown(const SizeOffsetType &SizeOffset)
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
static const char *const kAsanPoisonGlobalsName
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
LLVM Value Representation.
Definition: Value.h:73
void setAlignment(unsigned Align)
INITIALIZE_PASS(AddressSanitizerModule, "asan-module", "AddressSanitizer: detects use-after-free and out-of-bounds bugs." "ModulePass", false, false) ModulePass *llvm
static const uint64_t kPPC64_ShadowOffset64
static const unsigned kAllocaRzSize
bool hasInitializer() const
Definitions have initializers, declarations don&#39;t.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static cl::opt< bool > ClRedzoneByvalArgs("asan-redzone-byval-args", cl::desc("Create redzones for byval " "arguments (extra copy " "required)"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClInstrumentAtomics("asan-instrument-atomics", cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden, cl::init(true))
static const char *const kAsanUnregisterImageGlobalsName
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:81
static const Function * getParent(const Value *V)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:87
bool isAndroid() const
Tests whether the target is Android.
Definition: Triple.h:619
static const char *const kAsanRegisterImageGlobalsName
static Constant * getAnon(ArrayRef< Constant *> V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Definition: Constants.h:465
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1072
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
Definition: Metadata.cpp:1521
bool isThreadLocal() const
If the value is "Thread Local", its value isn&#39;t shared by the threads.
Definition: GlobalValue.h:246
FunctionPass * createAddressSanitizerFunctionPass(bool CompileKernel=false, bool Recover=false, bool UseAfterScope=false)
static const char *const kAsanAllocaPoison
static const char *const kAsanHandleNoReturnName
iterator_range< global_iterator > globals()
Definition: Module.h:566
IRTranslator LLVM IR MI
static const size_t kMaxStackMallocSize
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Various options to control the behavior of getObjectSize.
A single uniqued string.
Definition: Metadata.h:602
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Definition: Function.h:136
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:254
static cl::opt< bool > ClOptStack("asan-opt-stack", cl::desc("Don't instrument scalar stack variables"), cl::Hidden, cl::init(false))
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
static const char *const kAsanVersionCheckNamePrefix
static cl::opt< unsigned > ClRealignStack("asan-realign-stack", cl::desc("Realign stack to the value of this flag (power of two)"), cl::Hidden, cl::init(32))
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1073
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:298
#define LLVM_DEBUG(X)
Definition: Debug.h:119
ModulePass * createAddressSanitizerModulePass(bool CompileKernel=false, bool Recover=false, bool UseGlobalsGC=true)
Root of the metadata hierarchy.
Definition: Metadata.h:58
static cl::opt< bool > ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas", cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(true))
const uint64_t Version
Definition: InstrProf.h:895
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:184
#define OP(n)
Definition: regex2.h:73
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:418
bool isARM() const
Tests whether the target is ARM (little and big endian).
Definition: Triple.h:652
std::vector< uint32_t > Metadata
PAL metadata represented as a vector.
iterator_range< arg_iterator > args()
Definition: Function.h:675
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
const BasicBlock * getParent() const
Definition: Instruction.h:67
an instruction to allocate memory on the stack
Definition: Instructions.h:60
SmallVector< uint8_t, 64 > GetShadowBytes(const SmallVectorImpl< ASanStackVariableDescription > &Vars, const ASanStackFrameLayout &Layout)
static const char *const kAsanReportErrorTemplate
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1871
void resize(size_type N)
Definition: SmallVector.h:352