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