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