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