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