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