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