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