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