1 //===- HWAddressSanitizer.cpp - detector of uninitialized reads -------===// 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 /// \file 10 /// This file is a part of HWAddressSanitizer, an address sanity checker 11 /// based on tagged addressing. 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h" 15 #include "llvm/ADT/MapVector.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/ADT/Triple.h" 20 #include "llvm/BinaryFormat/ELF.h" 21 #include "llvm/IR/Attributes.h" 22 #include "llvm/IR/BasicBlock.h" 23 #include "llvm/IR/Constant.h" 24 #include "llvm/IR/Constants.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/DebugInfoMetadata.h" 27 #include "llvm/IR/DerivedTypes.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/IRBuilder.h" 30 #include "llvm/IR/InlineAsm.h" 31 #include "llvm/IR/InstVisitor.h" 32 #include "llvm/IR/Instruction.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/LLVMContext.h" 37 #include "llvm/IR/MDBuilder.h" 38 #include "llvm/IR/Module.h" 39 #include "llvm/IR/Type.h" 40 #include "llvm/IR/Value.h" 41 #include "llvm/Pass.h" 42 #include "llvm/Support/Casting.h" 43 #include "llvm/Support/CommandLine.h" 44 #include "llvm/Support/Debug.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Transforms/Instrumentation.h" 47 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 48 #include "llvm/Transforms/Utils/ModuleUtils.h" 49 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 50 #include <sstream> 51 52 using namespace llvm; 53 54 #define DEBUG_TYPE "hwasan" 55 56 static const char *const kHwasanModuleCtorName = "hwasan.module_ctor"; 57 static const char *const kHwasanNoteName = "hwasan.note"; 58 static const char *const kHwasanInitName = "__hwasan_init"; 59 static const char *const kHwasanPersonalityThunkName = 60 "__hwasan_personality_thunk"; 61 62 static const char *const kHwasanShadowMemoryDynamicAddress = 63 "__hwasan_shadow_memory_dynamic_address"; 64 65 // Accesses sizes are powers of two: 1, 2, 4, 8, 16. 66 static const size_t kNumberOfAccessSizes = 5; 67 68 static const size_t kDefaultShadowScale = 4; 69 static const uint64_t kDynamicShadowSentinel = 70 std::numeric_limits<uint64_t>::max(); 71 static const unsigned kPointerTagShift = 56; 72 73 static const unsigned kShadowBaseAlignment = 32; 74 75 static cl::opt<std::string> ClMemoryAccessCallbackPrefix( 76 "hwasan-memory-access-callback-prefix", 77 cl::desc("Prefix for memory access callbacks"), cl::Hidden, 78 cl::init("__hwasan_")); 79 80 static cl::opt<bool> 81 ClInstrumentWithCalls("hwasan-instrument-with-calls", 82 cl::desc("instrument reads and writes with callbacks"), 83 cl::Hidden, cl::init(false)); 84 85 static cl::opt<bool> ClInstrumentReads("hwasan-instrument-reads", 86 cl::desc("instrument read instructions"), 87 cl::Hidden, cl::init(true)); 88 89 static cl::opt<bool> ClInstrumentWrites( 90 "hwasan-instrument-writes", cl::desc("instrument write instructions"), 91 cl::Hidden, cl::init(true)); 92 93 static cl::opt<bool> ClInstrumentAtomics( 94 "hwasan-instrument-atomics", 95 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden, 96 cl::init(true)); 97 98 static cl::opt<bool> ClRecover( 99 "hwasan-recover", 100 cl::desc("Enable recovery mode (continue-after-error)."), 101 cl::Hidden, cl::init(false)); 102 103 static cl::opt<bool> ClInstrumentStack("hwasan-instrument-stack", 104 cl::desc("instrument stack (allocas)"), 105 cl::Hidden, cl::init(true)); 106 107 static cl::opt<bool> ClUARRetagToZero( 108 "hwasan-uar-retag-to-zero", 109 cl::desc("Clear alloca tags before returning from the function to allow " 110 "non-instrumented and instrumented function calls mix. When set " 111 "to false, allocas are retagged before returning from the " 112 "function to detect use after return."), 113 cl::Hidden, cl::init(true)); 114 115 static cl::opt<bool> ClGenerateTagsWithCalls( 116 "hwasan-generate-tags-with-calls", 117 cl::desc("generate new tags with runtime library calls"), cl::Hidden, 118 cl::init(false)); 119 120 static cl::opt<bool> ClGlobals("hwasan-globals", cl::desc("Instrument globals"), 121 cl::Hidden, cl::init(false)); 122 123 static cl::opt<int> ClMatchAllTag( 124 "hwasan-match-all-tag", 125 cl::desc("don't report bad accesses via pointers with this tag"), 126 cl::Hidden, cl::init(-1)); 127 128 static cl::opt<bool> ClEnableKhwasan( 129 "hwasan-kernel", 130 cl::desc("Enable KernelHWAddressSanitizer instrumentation"), 131 cl::Hidden, cl::init(false)); 132 133 // These flags allow to change the shadow mapping and control how shadow memory 134 // is accessed. The shadow mapping looks like: 135 // Shadow = (Mem >> scale) + offset 136 137 static cl::opt<uint64_t> 138 ClMappingOffset("hwasan-mapping-offset", 139 cl::desc("HWASan shadow mapping offset [EXPERIMENTAL]"), 140 cl::Hidden, cl::init(0)); 141 142 static cl::opt<bool> 143 ClWithIfunc("hwasan-with-ifunc", 144 cl::desc("Access dynamic shadow through an ifunc global on " 145 "platforms that support this"), 146 cl::Hidden, cl::init(false)); 147 148 static cl::opt<bool> ClWithTls( 149 "hwasan-with-tls", 150 cl::desc("Access dynamic shadow through an thread-local pointer on " 151 "platforms that support this"), 152 cl::Hidden, cl::init(true)); 153 154 static cl::opt<bool> 155 ClRecordStackHistory("hwasan-record-stack-history", 156 cl::desc("Record stack frames with tagged allocations " 157 "in a thread-local ring buffer"), 158 cl::Hidden, cl::init(true)); 159 static cl::opt<bool> 160 ClInstrumentMemIntrinsics("hwasan-instrument-mem-intrinsics", 161 cl::desc("instrument memory intrinsics"), 162 cl::Hidden, cl::init(true)); 163 164 static cl::opt<bool> 165 ClInstrumentLandingPads("hwasan-instrument-landing-pads", 166 cl::desc("instrument landing pads"), cl::Hidden, 167 cl::init(false), cl::ZeroOrMore); 168 169 static cl::opt<bool> ClUseShortGranules( 170 "hwasan-use-short-granules", 171 cl::desc("use short granules in allocas and outlined checks"), cl::Hidden, 172 cl::init(false), cl::ZeroOrMore); 173 174 static cl::opt<bool> ClInstrumentPersonalityFunctions( 175 "hwasan-instrument-personality-functions", 176 cl::desc("instrument personality functions"), cl::Hidden, cl::init(false), 177 cl::ZeroOrMore); 178 179 static cl::opt<bool> ClInlineAllChecks("hwasan-inline-all-checks", 180 cl::desc("inline all checks"), 181 cl::Hidden, cl::init(false)); 182 183 namespace { 184 185 /// An instrumentation pass implementing detection of addressability bugs 186 /// using tagged pointers. 187 class HWAddressSanitizer { 188 public: 189 explicit HWAddressSanitizer(Module &M, bool CompileKernel = false, 190 bool Recover = false) : M(M) { 191 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover; 192 this->CompileKernel = ClEnableKhwasan.getNumOccurrences() > 0 ? 193 ClEnableKhwasan : CompileKernel; 194 195 initializeModule(); 196 } 197 198 bool sanitizeFunction(Function &F); 199 void initializeModule(); 200 201 void initializeCallbacks(Module &M); 202 203 Value *getDynamicShadowIfunc(IRBuilder<> &IRB); 204 Value *getDynamicShadowNonTls(IRBuilder<> &IRB); 205 206 void untagPointerOperand(Instruction *I, Value *Addr); 207 Value *shadowBase(); 208 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB); 209 void instrumentMemAccessInline(Value *Ptr, bool IsWrite, 210 unsigned AccessSizeIndex, 211 Instruction *InsertBefore); 212 void instrumentMemIntrinsic(MemIntrinsic *MI); 213 bool instrumentMemAccess(Instruction *I); 214 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite, 215 uint64_t *TypeSize, unsigned *Alignment, 216 Value **MaybeMask); 217 218 bool isInterestingAlloca(const AllocaInst &AI); 219 bool tagAlloca(IRBuilder<> &IRB, AllocaInst *AI, Value *Tag, size_t Size); 220 Value *tagPointer(IRBuilder<> &IRB, Type *Ty, Value *PtrLong, Value *Tag); 221 Value *untagPointer(IRBuilder<> &IRB, Value *PtrLong); 222 bool instrumentStack( 223 SmallVectorImpl<AllocaInst *> &Allocas, 224 DenseMap<AllocaInst *, std::vector<DbgDeclareInst *>> &AllocaDeclareMap, 225 SmallVectorImpl<Instruction *> &RetVec, Value *StackTag); 226 Value *readRegister(IRBuilder<> &IRB, StringRef Name); 227 bool instrumentLandingPads(SmallVectorImpl<Instruction *> &RetVec); 228 Value *getNextTagWithCall(IRBuilder<> &IRB); 229 Value *getStackBaseTag(IRBuilder<> &IRB); 230 Value *getAllocaTag(IRBuilder<> &IRB, Value *StackTag, AllocaInst *AI, 231 unsigned AllocaNo); 232 Value *getUARTag(IRBuilder<> &IRB, Value *StackTag); 233 234 Value *getHwasanThreadSlotPtr(IRBuilder<> &IRB, Type *Ty); 235 void emitPrologue(IRBuilder<> &IRB, bool WithFrameRecord); 236 237 void instrumentGlobal(GlobalVariable *GV, uint8_t Tag); 238 void instrumentGlobals(); 239 240 void instrumentPersonalityFunctions(); 241 242 private: 243 LLVMContext *C; 244 Module &M; 245 Triple TargetTriple; 246 FunctionCallee HWAsanMemmove, HWAsanMemcpy, HWAsanMemset; 247 FunctionCallee HWAsanHandleVfork; 248 249 /// This struct defines the shadow mapping using the rule: 250 /// shadow = (mem >> Scale) + Offset. 251 /// If InGlobal is true, then 252 /// extern char __hwasan_shadow[]; 253 /// shadow = (mem >> Scale) + &__hwasan_shadow 254 /// If InTls is true, then 255 /// extern char *__hwasan_tls; 256 /// shadow = (mem>>Scale) + align_up(__hwasan_shadow, kShadowBaseAlignment) 257 struct ShadowMapping { 258 int Scale; 259 uint64_t Offset; 260 bool InGlobal; 261 bool InTls; 262 263 void init(Triple &TargetTriple); 264 unsigned getObjectAlignment() const { return 1U << Scale; } 265 }; 266 ShadowMapping Mapping; 267 268 Type *VoidTy = Type::getVoidTy(M.getContext()); 269 Type *IntptrTy; 270 Type *Int8PtrTy; 271 Type *Int8Ty; 272 Type *Int32Ty; 273 Type *Int64Ty = Type::getInt64Ty(M.getContext()); 274 275 bool CompileKernel; 276 bool Recover; 277 bool UseShortGranules; 278 bool InstrumentLandingPads; 279 280 Function *HwasanCtorFunction; 281 282 FunctionCallee HwasanMemoryAccessCallback[2][kNumberOfAccessSizes]; 283 FunctionCallee HwasanMemoryAccessCallbackSized[2]; 284 285 FunctionCallee HwasanTagMemoryFunc; 286 FunctionCallee HwasanGenerateTagFunc; 287 288 Constant *ShadowGlobal; 289 290 Value *LocalDynamicShadow = nullptr; 291 Value *StackBaseTag = nullptr; 292 GlobalValue *ThreadPtrGlobal = nullptr; 293 }; 294 295 class HWAddressSanitizerLegacyPass : public FunctionPass { 296 public: 297 // Pass identification, replacement for typeid. 298 static char ID; 299 300 explicit HWAddressSanitizerLegacyPass(bool CompileKernel = false, 301 bool Recover = false) 302 : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover) {} 303 304 StringRef getPassName() const override { return "HWAddressSanitizer"; } 305 306 bool doInitialization(Module &M) override { 307 HWASan = std::make_unique<HWAddressSanitizer>(M, CompileKernel, Recover); 308 return true; 309 } 310 311 bool runOnFunction(Function &F) override { 312 return HWASan->sanitizeFunction(F); 313 } 314 315 bool doFinalization(Module &M) override { 316 HWASan.reset(); 317 return false; 318 } 319 320 private: 321 std::unique_ptr<HWAddressSanitizer> HWASan; 322 bool CompileKernel; 323 bool Recover; 324 }; 325 326 } // end anonymous namespace 327 328 char HWAddressSanitizerLegacyPass::ID = 0; 329 330 INITIALIZE_PASS_BEGIN( 331 HWAddressSanitizerLegacyPass, "hwasan", 332 "HWAddressSanitizer: detect memory bugs using tagged addressing.", false, 333 false) 334 INITIALIZE_PASS_END( 335 HWAddressSanitizerLegacyPass, "hwasan", 336 "HWAddressSanitizer: detect memory bugs using tagged addressing.", false, 337 false) 338 339 FunctionPass *llvm::createHWAddressSanitizerLegacyPassPass(bool CompileKernel, 340 bool Recover) { 341 assert(!CompileKernel || Recover); 342 return new HWAddressSanitizerLegacyPass(CompileKernel, Recover); 343 } 344 345 HWAddressSanitizerPass::HWAddressSanitizerPass(bool CompileKernel, bool Recover) 346 : CompileKernel(CompileKernel), Recover(Recover) {} 347 348 PreservedAnalyses HWAddressSanitizerPass::run(Module &M, 349 ModuleAnalysisManager &MAM) { 350 HWAddressSanitizer HWASan(M, CompileKernel, Recover); 351 bool Modified = false; 352 for (Function &F : M) 353 Modified |= HWASan.sanitizeFunction(F); 354 if (Modified) 355 return PreservedAnalyses::none(); 356 return PreservedAnalyses::all(); 357 } 358 359 /// Module-level initialization. 360 /// 361 /// inserts a call to __hwasan_init to the module's constructor list. 362 void HWAddressSanitizer::initializeModule() { 363 LLVM_DEBUG(dbgs() << "Init " << M.getName() << "\n"); 364 auto &DL = M.getDataLayout(); 365 366 TargetTriple = Triple(M.getTargetTriple()); 367 368 Mapping.init(TargetTriple); 369 370 C = &(M.getContext()); 371 IRBuilder<> IRB(*C); 372 IntptrTy = IRB.getIntPtrTy(DL); 373 Int8PtrTy = IRB.getInt8PtrTy(); 374 Int8Ty = IRB.getInt8Ty(); 375 Int32Ty = IRB.getInt32Ty(); 376 377 HwasanCtorFunction = nullptr; 378 379 // Older versions of Android do not have the required runtime support for 380 // short granules, global or personality function instrumentation. On other 381 // platforms we currently require using the latest version of the runtime. 382 bool NewRuntime = 383 !TargetTriple.isAndroid() || !TargetTriple.isAndroidVersionLT(30); 384 385 UseShortGranules = 386 ClUseShortGranules.getNumOccurrences() ? ClUseShortGranules : NewRuntime; 387 388 // If we don't have personality function support, fall back to landing pads. 389 InstrumentLandingPads = ClInstrumentLandingPads.getNumOccurrences() 390 ? ClInstrumentLandingPads 391 : !NewRuntime; 392 393 if (!CompileKernel) { 394 std::tie(HwasanCtorFunction, std::ignore) = 395 getOrCreateSanitizerCtorAndInitFunctions( 396 M, kHwasanModuleCtorName, kHwasanInitName, 397 /*InitArgTypes=*/{}, 398 /*InitArgs=*/{}, 399 // This callback is invoked when the functions are created the first 400 // time. Hook them into the global ctors list in that case: 401 [&](Function *Ctor, FunctionCallee) { 402 Comdat *CtorComdat = M.getOrInsertComdat(kHwasanModuleCtorName); 403 Ctor->setComdat(CtorComdat); 404 appendToGlobalCtors(M, Ctor, 0, Ctor); 405 }); 406 407 bool InstrumentGlobals = 408 ClGlobals.getNumOccurrences() ? ClGlobals : NewRuntime; 409 if (InstrumentGlobals) 410 instrumentGlobals(); 411 412 bool InstrumentPersonalityFunctions = 413 ClInstrumentPersonalityFunctions.getNumOccurrences() 414 ? ClInstrumentPersonalityFunctions 415 : NewRuntime; 416 if (InstrumentPersonalityFunctions) 417 instrumentPersonalityFunctions(); 418 } 419 420 if (!TargetTriple.isAndroid()) { 421 Constant *C = M.getOrInsertGlobal("__hwasan_tls", IntptrTy, [&] { 422 auto *GV = new GlobalVariable(M, IntptrTy, /*isConstant=*/false, 423 GlobalValue::ExternalLinkage, nullptr, 424 "__hwasan_tls", nullptr, 425 GlobalVariable::InitialExecTLSModel); 426 appendToCompilerUsed(M, GV); 427 return GV; 428 }); 429 ThreadPtrGlobal = cast<GlobalVariable>(C); 430 } 431 } 432 433 void HWAddressSanitizer::initializeCallbacks(Module &M) { 434 IRBuilder<> IRB(*C); 435 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) { 436 const std::string TypeStr = AccessIsWrite ? "store" : "load"; 437 const std::string EndingStr = Recover ? "_noabort" : ""; 438 439 HwasanMemoryAccessCallbackSized[AccessIsWrite] = M.getOrInsertFunction( 440 ClMemoryAccessCallbackPrefix + TypeStr + "N" + EndingStr, 441 FunctionType::get(IRB.getVoidTy(), {IntptrTy, IntptrTy}, false)); 442 443 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes; 444 AccessSizeIndex++) { 445 HwasanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] = 446 M.getOrInsertFunction( 447 ClMemoryAccessCallbackPrefix + TypeStr + 448 itostr(1ULL << AccessSizeIndex) + EndingStr, 449 FunctionType::get(IRB.getVoidTy(), {IntptrTy}, false)); 450 } 451 } 452 453 HwasanTagMemoryFunc = M.getOrInsertFunction( 454 "__hwasan_tag_memory", IRB.getVoidTy(), Int8PtrTy, Int8Ty, IntptrTy); 455 HwasanGenerateTagFunc = 456 M.getOrInsertFunction("__hwasan_generate_tag", Int8Ty); 457 458 ShadowGlobal = M.getOrInsertGlobal("__hwasan_shadow", 459 ArrayType::get(IRB.getInt8Ty(), 0)); 460 461 const std::string MemIntrinCallbackPrefix = 462 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix; 463 HWAsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove", 464 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), 465 IRB.getInt8PtrTy(), IntptrTy); 466 HWAsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy", 467 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), 468 IRB.getInt8PtrTy(), IntptrTy); 469 HWAsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset", 470 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), 471 IRB.getInt32Ty(), IntptrTy); 472 473 HWAsanHandleVfork = 474 M.getOrInsertFunction("__hwasan_handle_vfork", IRB.getVoidTy(), IntptrTy); 475 } 476 477 Value *HWAddressSanitizer::getDynamicShadowIfunc(IRBuilder<> &IRB) { 478 // An empty inline asm with input reg == output reg. 479 // An opaque no-op cast, basically. 480 InlineAsm *Asm = InlineAsm::get( 481 FunctionType::get(Int8PtrTy, {ShadowGlobal->getType()}, false), 482 StringRef(""), StringRef("=r,0"), 483 /*hasSideEffects=*/false); 484 return IRB.CreateCall(Asm, {ShadowGlobal}, ".hwasan.shadow"); 485 } 486 487 Value *HWAddressSanitizer::getDynamicShadowNonTls(IRBuilder<> &IRB) { 488 // Generate code only when dynamic addressing is needed. 489 if (Mapping.Offset != kDynamicShadowSentinel) 490 return nullptr; 491 492 if (Mapping.InGlobal) { 493 return getDynamicShadowIfunc(IRB); 494 } else { 495 Value *GlobalDynamicAddress = 496 IRB.GetInsertBlock()->getParent()->getParent()->getOrInsertGlobal( 497 kHwasanShadowMemoryDynamicAddress, Int8PtrTy); 498 return IRB.CreateLoad(Int8PtrTy, GlobalDynamicAddress); 499 } 500 } 501 502 Value *HWAddressSanitizer::isInterestingMemoryAccess(Instruction *I, 503 bool *IsWrite, 504 uint64_t *TypeSize, 505 unsigned *Alignment, 506 Value **MaybeMask) { 507 // Skip memory accesses inserted by another instrumentation. 508 if (I->hasMetadata("nosanitize")) return nullptr; 509 510 // Do not instrument the load fetching the dynamic shadow address. 511 if (LocalDynamicShadow == I) 512 return nullptr; 513 514 Value *PtrOperand = nullptr; 515 const DataLayout &DL = I->getModule()->getDataLayout(); 516 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 517 if (!ClInstrumentReads) return nullptr; 518 *IsWrite = false; 519 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType()); 520 *Alignment = LI->getAlignment(); 521 PtrOperand = LI->getPointerOperand(); 522 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 523 if (!ClInstrumentWrites) return nullptr; 524 *IsWrite = true; 525 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType()); 526 *Alignment = SI->getAlignment(); 527 PtrOperand = SI->getPointerOperand(); 528 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { 529 if (!ClInstrumentAtomics) return nullptr; 530 *IsWrite = true; 531 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType()); 532 *Alignment = 0; 533 PtrOperand = RMW->getPointerOperand(); 534 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) { 535 if (!ClInstrumentAtomics) return nullptr; 536 *IsWrite = true; 537 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType()); 538 *Alignment = 0; 539 PtrOperand = XCHG->getPointerOperand(); 540 } 541 542 if (PtrOperand) { 543 // Do not instrument accesses from different address spaces; we cannot deal 544 // with them. 545 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType()); 546 if (PtrTy->getPointerAddressSpace() != 0) 547 return nullptr; 548 549 // Ignore swifterror addresses. 550 // swifterror memory addresses are mem2reg promoted by instruction 551 // selection. As such they cannot have regular uses like an instrumentation 552 // function and it makes no sense to track them as memory. 553 if (PtrOperand->isSwiftError()) 554 return nullptr; 555 } 556 557 return PtrOperand; 558 } 559 560 static unsigned getPointerOperandIndex(Instruction *I) { 561 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 562 return LI->getPointerOperandIndex(); 563 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 564 return SI->getPointerOperandIndex(); 565 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) 566 return RMW->getPointerOperandIndex(); 567 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) 568 return XCHG->getPointerOperandIndex(); 569 report_fatal_error("Unexpected instruction"); 570 return -1; 571 } 572 573 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) { 574 size_t Res = countTrailingZeros(TypeSize / 8); 575 assert(Res < kNumberOfAccessSizes); 576 return Res; 577 } 578 579 void HWAddressSanitizer::untagPointerOperand(Instruction *I, Value *Addr) { 580 if (TargetTriple.isAArch64()) 581 return; 582 583 IRBuilder<> IRB(I); 584 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy); 585 Value *UntaggedPtr = 586 IRB.CreateIntToPtr(untagPointer(IRB, AddrLong), Addr->getType()); 587 I->setOperand(getPointerOperandIndex(I), UntaggedPtr); 588 } 589 590 Value *HWAddressSanitizer::shadowBase() { 591 if (LocalDynamicShadow) 592 return LocalDynamicShadow; 593 return ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, Mapping.Offset), 594 Int8PtrTy); 595 } 596 597 Value *HWAddressSanitizer::memToShadow(Value *Mem, IRBuilder<> &IRB) { 598 // Mem >> Scale 599 Value *Shadow = IRB.CreateLShr(Mem, Mapping.Scale); 600 if (Mapping.Offset == 0) 601 return IRB.CreateIntToPtr(Shadow, Int8PtrTy); 602 // (Mem >> Scale) + Offset 603 return IRB.CreateGEP(Int8Ty, shadowBase(), Shadow); 604 } 605 606 void HWAddressSanitizer::instrumentMemAccessInline(Value *Ptr, bool IsWrite, 607 unsigned AccessSizeIndex, 608 Instruction *InsertBefore) { 609 const int64_t AccessInfo = Recover * 0x20 + IsWrite * 0x10 + AccessSizeIndex; 610 IRBuilder<> IRB(InsertBefore); 611 612 if (!ClInlineAllChecks && TargetTriple.isAArch64() && 613 TargetTriple.isOSBinFormatELF() && !Recover) { 614 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 615 Ptr = IRB.CreateBitCast(Ptr, Int8PtrTy); 616 IRB.CreateCall(Intrinsic::getDeclaration( 617 M, UseShortGranules 618 ? Intrinsic::hwasan_check_memaccess_shortgranules 619 : Intrinsic::hwasan_check_memaccess), 620 {shadowBase(), Ptr, ConstantInt::get(Int32Ty, AccessInfo)}); 621 return; 622 } 623 624 Value *PtrLong = IRB.CreatePointerCast(Ptr, IntptrTy); 625 Value *PtrTag = IRB.CreateTrunc(IRB.CreateLShr(PtrLong, kPointerTagShift), 626 IRB.getInt8Ty()); 627 Value *AddrLong = untagPointer(IRB, PtrLong); 628 Value *Shadow = memToShadow(AddrLong, IRB); 629 Value *MemTag = IRB.CreateLoad(Int8Ty, Shadow); 630 Value *TagMismatch = IRB.CreateICmpNE(PtrTag, MemTag); 631 632 int matchAllTag = ClMatchAllTag.getNumOccurrences() > 0 ? 633 ClMatchAllTag : (CompileKernel ? 0xFF : -1); 634 if (matchAllTag != -1) { 635 Value *TagNotIgnored = IRB.CreateICmpNE(PtrTag, 636 ConstantInt::get(PtrTag->getType(), matchAllTag)); 637 TagMismatch = IRB.CreateAnd(TagMismatch, TagNotIgnored); 638 } 639 640 Instruction *CheckTerm = 641 SplitBlockAndInsertIfThen(TagMismatch, InsertBefore, false, 642 MDBuilder(*C).createBranchWeights(1, 100000)); 643 644 IRB.SetInsertPoint(CheckTerm); 645 Value *OutOfShortGranuleTagRange = 646 IRB.CreateICmpUGT(MemTag, ConstantInt::get(Int8Ty, 15)); 647 Instruction *CheckFailTerm = 648 SplitBlockAndInsertIfThen(OutOfShortGranuleTagRange, CheckTerm, !Recover, 649 MDBuilder(*C).createBranchWeights(1, 100000)); 650 651 IRB.SetInsertPoint(CheckTerm); 652 Value *PtrLowBits = IRB.CreateTrunc(IRB.CreateAnd(PtrLong, 15), Int8Ty); 653 PtrLowBits = IRB.CreateAdd( 654 PtrLowBits, ConstantInt::get(Int8Ty, (1 << AccessSizeIndex) - 1)); 655 Value *PtrLowBitsOOB = IRB.CreateICmpUGE(PtrLowBits, MemTag); 656 SplitBlockAndInsertIfThen(PtrLowBitsOOB, CheckTerm, false, 657 MDBuilder(*C).createBranchWeights(1, 100000), 658 nullptr, nullptr, CheckFailTerm->getParent()); 659 660 IRB.SetInsertPoint(CheckTerm); 661 Value *InlineTagAddr = IRB.CreateOr(AddrLong, 15); 662 InlineTagAddr = IRB.CreateIntToPtr(InlineTagAddr, Int8PtrTy); 663 Value *InlineTag = IRB.CreateLoad(Int8Ty, InlineTagAddr); 664 Value *InlineTagMismatch = IRB.CreateICmpNE(PtrTag, InlineTag); 665 SplitBlockAndInsertIfThen(InlineTagMismatch, CheckTerm, false, 666 MDBuilder(*C).createBranchWeights(1, 100000), 667 nullptr, nullptr, CheckFailTerm->getParent()); 668 669 IRB.SetInsertPoint(CheckFailTerm); 670 InlineAsm *Asm; 671 switch (TargetTriple.getArch()) { 672 case Triple::x86_64: 673 // The signal handler will find the data address in rdi. 674 Asm = InlineAsm::get( 675 FunctionType::get(IRB.getVoidTy(), {PtrLong->getType()}, false), 676 "int3\nnopl " + itostr(0x40 + AccessInfo) + "(%rax)", 677 "{rdi}", 678 /*hasSideEffects=*/true); 679 break; 680 case Triple::aarch64: 681 case Triple::aarch64_be: 682 // The signal handler will find the data address in x0. 683 Asm = InlineAsm::get( 684 FunctionType::get(IRB.getVoidTy(), {PtrLong->getType()}, false), 685 "brk #" + itostr(0x900 + AccessInfo), 686 "{x0}", 687 /*hasSideEffects=*/true); 688 break; 689 default: 690 report_fatal_error("unsupported architecture"); 691 } 692 IRB.CreateCall(Asm, PtrLong); 693 if (Recover) 694 cast<BranchInst>(CheckFailTerm)->setSuccessor(0, CheckTerm->getParent()); 695 } 696 697 void HWAddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) { 698 IRBuilder<> IRB(MI); 699 if (isa<MemTransferInst>(MI)) { 700 IRB.CreateCall( 701 isa<MemMoveInst>(MI) ? HWAsanMemmove : HWAsanMemcpy, 702 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()), 703 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()), 704 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)}); 705 } else if (isa<MemSetInst>(MI)) { 706 IRB.CreateCall( 707 HWAsanMemset, 708 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()), 709 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false), 710 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)}); 711 } 712 MI->eraseFromParent(); 713 } 714 715 bool HWAddressSanitizer::instrumentMemAccess(Instruction *I) { 716 LLVM_DEBUG(dbgs() << "Instrumenting: " << *I << "\n"); 717 bool IsWrite = false; 718 unsigned Alignment = 0; 719 uint64_t TypeSize = 0; 720 Value *MaybeMask = nullptr; 721 722 if (ClInstrumentMemIntrinsics && isa<MemIntrinsic>(I)) { 723 instrumentMemIntrinsic(cast<MemIntrinsic>(I)); 724 return true; 725 } 726 727 Value *Addr = 728 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask); 729 730 if (!Addr) 731 return false; 732 733 if (MaybeMask) 734 return false; //FIXME 735 736 IRBuilder<> IRB(I); 737 if (isPowerOf2_64(TypeSize) && 738 (TypeSize / 8 <= (1UL << (kNumberOfAccessSizes - 1))) && 739 (Alignment >= (1UL << Mapping.Scale) || Alignment == 0 || 740 Alignment >= TypeSize / 8)) { 741 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize); 742 if (ClInstrumentWithCalls) { 743 IRB.CreateCall(HwasanMemoryAccessCallback[IsWrite][AccessSizeIndex], 744 IRB.CreatePointerCast(Addr, IntptrTy)); 745 } else { 746 instrumentMemAccessInline(Addr, IsWrite, AccessSizeIndex, I); 747 } 748 } else { 749 IRB.CreateCall(HwasanMemoryAccessCallbackSized[IsWrite], 750 {IRB.CreatePointerCast(Addr, IntptrTy), 751 ConstantInt::get(IntptrTy, TypeSize / 8)}); 752 } 753 untagPointerOperand(I, Addr); 754 755 return true; 756 } 757 758 static uint64_t getAllocaSizeInBytes(const AllocaInst &AI) { 759 uint64_t ArraySize = 1; 760 if (AI.isArrayAllocation()) { 761 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize()); 762 assert(CI && "non-constant array size"); 763 ArraySize = CI->getZExtValue(); 764 } 765 Type *Ty = AI.getAllocatedType(); 766 uint64_t SizeInBytes = AI.getModule()->getDataLayout().getTypeAllocSize(Ty); 767 return SizeInBytes * ArraySize; 768 } 769 770 bool HWAddressSanitizer::tagAlloca(IRBuilder<> &IRB, AllocaInst *AI, 771 Value *Tag, size_t Size) { 772 size_t AlignedSize = alignTo(Size, Mapping.getObjectAlignment()); 773 if (!UseShortGranules) 774 Size = AlignedSize; 775 776 Value *JustTag = IRB.CreateTrunc(Tag, IRB.getInt8Ty()); 777 if (ClInstrumentWithCalls) { 778 IRB.CreateCall(HwasanTagMemoryFunc, 779 {IRB.CreatePointerCast(AI, Int8PtrTy), JustTag, 780 ConstantInt::get(IntptrTy, AlignedSize)}); 781 } else { 782 size_t ShadowSize = Size >> Mapping.Scale; 783 Value *ShadowPtr = memToShadow(IRB.CreatePointerCast(AI, IntptrTy), IRB); 784 // If this memset is not inlined, it will be intercepted in the hwasan 785 // runtime library. That's OK, because the interceptor skips the checks if 786 // the address is in the shadow region. 787 // FIXME: the interceptor is not as fast as real memset. Consider lowering 788 // llvm.memset right here into either a sequence of stores, or a call to 789 // hwasan_tag_memory. 790 if (ShadowSize) 791 IRB.CreateMemSet(ShadowPtr, JustTag, ShadowSize, /*Align=*/1); 792 if (Size != AlignedSize) { 793 IRB.CreateStore( 794 ConstantInt::get(Int8Ty, Size % Mapping.getObjectAlignment()), 795 IRB.CreateConstGEP1_32(Int8Ty, ShadowPtr, ShadowSize)); 796 IRB.CreateStore(JustTag, IRB.CreateConstGEP1_32( 797 Int8Ty, IRB.CreateBitCast(AI, Int8PtrTy), 798 AlignedSize - 1)); 799 } 800 } 801 return true; 802 } 803 804 static unsigned RetagMask(unsigned AllocaNo) { 805 // A list of 8-bit numbers that have at most one run of non-zero bits. 806 // x = x ^ (mask << 56) can be encoded as a single armv8 instruction for these 807 // masks. 808 // The list does not include the value 255, which is used for UAR. 809 // 810 // Because we are more likely to use earlier elements of this list than later 811 // ones, it is sorted in increasing order of probability of collision with a 812 // mask allocated (temporally) nearby. The program that generated this list 813 // can be found at: 814 // https://github.com/google/sanitizers/blob/master/hwaddress-sanitizer/sort_masks.py 815 static unsigned FastMasks[] = {0, 128, 64, 192, 32, 96, 224, 112, 240, 816 48, 16, 120, 248, 56, 24, 8, 124, 252, 817 60, 28, 12, 4, 126, 254, 62, 30, 14, 818 6, 2, 127, 63, 31, 15, 7, 3, 1}; 819 return FastMasks[AllocaNo % (sizeof(FastMasks) / sizeof(FastMasks[0]))]; 820 } 821 822 Value *HWAddressSanitizer::getNextTagWithCall(IRBuilder<> &IRB) { 823 return IRB.CreateZExt(IRB.CreateCall(HwasanGenerateTagFunc), IntptrTy); 824 } 825 826 Value *HWAddressSanitizer::getStackBaseTag(IRBuilder<> &IRB) { 827 if (ClGenerateTagsWithCalls) 828 return getNextTagWithCall(IRB); 829 if (StackBaseTag) 830 return StackBaseTag; 831 // FIXME: use addressofreturnaddress (but implement it in aarch64 backend 832 // first). 833 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 834 auto GetStackPointerFn = Intrinsic::getDeclaration( 835 M, Intrinsic::frameaddress, 836 IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace())); 837 Value *StackPointer = IRB.CreateCall( 838 GetStackPointerFn, {Constant::getNullValue(IRB.getInt32Ty())}); 839 840 // Extract some entropy from the stack pointer for the tags. 841 // Take bits 20..28 (ASLR entropy) and xor with bits 0..8 (these differ 842 // between functions). 843 Value *StackPointerLong = IRB.CreatePointerCast(StackPointer, IntptrTy); 844 Value *StackTag = 845 IRB.CreateXor(StackPointerLong, IRB.CreateLShr(StackPointerLong, 20), 846 "hwasan.stack.base.tag"); 847 return StackTag; 848 } 849 850 Value *HWAddressSanitizer::getAllocaTag(IRBuilder<> &IRB, Value *StackTag, 851 AllocaInst *AI, unsigned AllocaNo) { 852 if (ClGenerateTagsWithCalls) 853 return getNextTagWithCall(IRB); 854 return IRB.CreateXor(StackTag, 855 ConstantInt::get(IntptrTy, RetagMask(AllocaNo))); 856 } 857 858 Value *HWAddressSanitizer::getUARTag(IRBuilder<> &IRB, Value *StackTag) { 859 if (ClUARRetagToZero) 860 return ConstantInt::get(IntptrTy, 0); 861 if (ClGenerateTagsWithCalls) 862 return getNextTagWithCall(IRB); 863 return IRB.CreateXor(StackTag, ConstantInt::get(IntptrTy, 0xFFU)); 864 } 865 866 // Add a tag to an address. 867 Value *HWAddressSanitizer::tagPointer(IRBuilder<> &IRB, Type *Ty, 868 Value *PtrLong, Value *Tag) { 869 Value *TaggedPtrLong; 870 if (CompileKernel) { 871 // Kernel addresses have 0xFF in the most significant byte. 872 Value *ShiftedTag = IRB.CreateOr( 873 IRB.CreateShl(Tag, kPointerTagShift), 874 ConstantInt::get(IntptrTy, (1ULL << kPointerTagShift) - 1)); 875 TaggedPtrLong = IRB.CreateAnd(PtrLong, ShiftedTag); 876 } else { 877 // Userspace can simply do OR (tag << 56); 878 Value *ShiftedTag = IRB.CreateShl(Tag, kPointerTagShift); 879 TaggedPtrLong = IRB.CreateOr(PtrLong, ShiftedTag); 880 } 881 return IRB.CreateIntToPtr(TaggedPtrLong, Ty); 882 } 883 884 // Remove tag from an address. 885 Value *HWAddressSanitizer::untagPointer(IRBuilder<> &IRB, Value *PtrLong) { 886 Value *UntaggedPtrLong; 887 if (CompileKernel) { 888 // Kernel addresses have 0xFF in the most significant byte. 889 UntaggedPtrLong = IRB.CreateOr(PtrLong, 890 ConstantInt::get(PtrLong->getType(), 0xFFULL << kPointerTagShift)); 891 } else { 892 // Userspace addresses have 0x00. 893 UntaggedPtrLong = IRB.CreateAnd(PtrLong, 894 ConstantInt::get(PtrLong->getType(), ~(0xFFULL << kPointerTagShift))); 895 } 896 return UntaggedPtrLong; 897 } 898 899 Value *HWAddressSanitizer::getHwasanThreadSlotPtr(IRBuilder<> &IRB, Type *Ty) { 900 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 901 if (TargetTriple.isAArch64() && TargetTriple.isAndroid()) { 902 // Android provides a fixed TLS slot for sanitizers. See TLS_SLOT_SANITIZER 903 // in Bionic's libc/private/bionic_tls.h. 904 Function *ThreadPointerFunc = 905 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 906 Value *SlotPtr = IRB.CreatePointerCast( 907 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), 908 IRB.CreateCall(ThreadPointerFunc), 0x30), 909 Ty->getPointerTo(0)); 910 return SlotPtr; 911 } 912 if (ThreadPtrGlobal) 913 return ThreadPtrGlobal; 914 915 916 return nullptr; 917 } 918 919 void HWAddressSanitizer::emitPrologue(IRBuilder<> &IRB, bool WithFrameRecord) { 920 if (!Mapping.InTls) { 921 LocalDynamicShadow = getDynamicShadowNonTls(IRB); 922 return; 923 } 924 925 if (!WithFrameRecord && TargetTriple.isAndroid()) { 926 LocalDynamicShadow = getDynamicShadowIfunc(IRB); 927 return; 928 } 929 930 Value *SlotPtr = getHwasanThreadSlotPtr(IRB, IntptrTy); 931 assert(SlotPtr); 932 933 Value *ThreadLong = IRB.CreateLoad(IntptrTy, SlotPtr); 934 // Extract the address field from ThreadLong. Unnecessary on AArch64 with TBI. 935 Value *ThreadLongMaybeUntagged = 936 TargetTriple.isAArch64() ? ThreadLong : untagPointer(IRB, ThreadLong); 937 938 if (WithFrameRecord) { 939 Function *F = IRB.GetInsertBlock()->getParent(); 940 StackBaseTag = IRB.CreateAShr(ThreadLong, 3); 941 942 // Prepare ring buffer data. 943 Value *PC; 944 if (TargetTriple.getArch() == Triple::aarch64) 945 PC = readRegister(IRB, "pc"); 946 else 947 PC = IRB.CreatePtrToInt(F, IntptrTy); 948 Module *M = F->getParent(); 949 auto GetStackPointerFn = Intrinsic::getDeclaration( 950 M, Intrinsic::frameaddress, 951 IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace())); 952 Value *SP = IRB.CreatePtrToInt( 953 IRB.CreateCall(GetStackPointerFn, 954 {Constant::getNullValue(IRB.getInt32Ty())}), 955 IntptrTy); 956 // Mix SP and PC. 957 // Assumptions: 958 // PC is 0x0000PPPPPPPPPPPP (48 bits are meaningful, others are zero) 959 // SP is 0xsssssssssssSSSS0 (4 lower bits are zero) 960 // We only really need ~20 lower non-zero bits (SSSS), so we mix like this: 961 // 0xSSSSPPPPPPPPPPPP 962 SP = IRB.CreateShl(SP, 44); 963 964 // Store data to ring buffer. 965 Value *RecordPtr = 966 IRB.CreateIntToPtr(ThreadLongMaybeUntagged, IntptrTy->getPointerTo(0)); 967 IRB.CreateStore(IRB.CreateOr(PC, SP), RecordPtr); 968 969 // Update the ring buffer. Top byte of ThreadLong defines the size of the 970 // buffer in pages, it must be a power of two, and the start of the buffer 971 // must be aligned by twice that much. Therefore wrap around of the ring 972 // buffer is simply Addr &= ~((ThreadLong >> 56) << 12). 973 // The use of AShr instead of LShr is due to 974 // https://bugs.llvm.org/show_bug.cgi?id=39030 975 // Runtime library makes sure not to use the highest bit. 976 Value *WrapMask = IRB.CreateXor( 977 IRB.CreateShl(IRB.CreateAShr(ThreadLong, 56), 12, "", true, true), 978 ConstantInt::get(IntptrTy, (uint64_t)-1)); 979 Value *ThreadLongNew = IRB.CreateAnd( 980 IRB.CreateAdd(ThreadLong, ConstantInt::get(IntptrTy, 8)), WrapMask); 981 IRB.CreateStore(ThreadLongNew, SlotPtr); 982 } 983 984 // Get shadow base address by aligning RecordPtr up. 985 // Note: this is not correct if the pointer is already aligned. 986 // Runtime library will make sure this never happens. 987 LocalDynamicShadow = IRB.CreateAdd( 988 IRB.CreateOr( 989 ThreadLongMaybeUntagged, 990 ConstantInt::get(IntptrTy, (1ULL << kShadowBaseAlignment) - 1)), 991 ConstantInt::get(IntptrTy, 1), "hwasan.shadow"); 992 LocalDynamicShadow = IRB.CreateIntToPtr(LocalDynamicShadow, Int8PtrTy); 993 } 994 995 Value *HWAddressSanitizer::readRegister(IRBuilder<> &IRB, StringRef Name) { 996 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 997 Function *ReadRegister = 998 Intrinsic::getDeclaration(M, Intrinsic::read_register, IntptrTy); 999 MDNode *MD = MDNode::get(*C, {MDString::get(*C, Name)}); 1000 Value *Args[] = {MetadataAsValue::get(*C, MD)}; 1001 return IRB.CreateCall(ReadRegister, Args); 1002 } 1003 1004 bool HWAddressSanitizer::instrumentLandingPads( 1005 SmallVectorImpl<Instruction *> &LandingPadVec) { 1006 for (auto *LP : LandingPadVec) { 1007 IRBuilder<> IRB(LP->getNextNode()); 1008 IRB.CreateCall( 1009 HWAsanHandleVfork, 1010 {readRegister(IRB, (TargetTriple.getArch() == Triple::x86_64) ? "rsp" 1011 : "sp")}); 1012 } 1013 return true; 1014 } 1015 1016 bool HWAddressSanitizer::instrumentStack( 1017 SmallVectorImpl<AllocaInst *> &Allocas, 1018 DenseMap<AllocaInst *, std::vector<DbgDeclareInst *>> &AllocaDeclareMap, 1019 SmallVectorImpl<Instruction *> &RetVec, Value *StackTag) { 1020 // Ideally, we want to calculate tagged stack base pointer, and rewrite all 1021 // alloca addresses using that. Unfortunately, offsets are not known yet 1022 // (unless we use ASan-style mega-alloca). Instead we keep the base tag in a 1023 // temp, shift-OR it into each alloca address and xor with the retag mask. 1024 // This generates one extra instruction per alloca use. 1025 for (unsigned N = 0; N < Allocas.size(); ++N) { 1026 auto *AI = Allocas[N]; 1027 IRBuilder<> IRB(AI->getNextNode()); 1028 1029 // Replace uses of the alloca with tagged address. 1030 Value *Tag = getAllocaTag(IRB, StackTag, AI, N); 1031 Value *AILong = IRB.CreatePointerCast(AI, IntptrTy); 1032 Value *Replacement = tagPointer(IRB, AI->getType(), AILong, Tag); 1033 std::string Name = 1034 AI->hasName() ? AI->getName().str() : "alloca." + itostr(N); 1035 Replacement->setName(Name + ".hwasan"); 1036 1037 AI->replaceUsesWithIf(Replacement, 1038 [AILong](Use &U) { return U.getUser() != AILong; }); 1039 1040 for (auto *DDI : AllocaDeclareMap.lookup(AI)) { 1041 DIExpression *OldExpr = DDI->getExpression(); 1042 DIExpression *NewExpr = DIExpression::append( 1043 OldExpr, {dwarf::DW_OP_LLVM_tag_offset, RetagMask(N)}); 1044 DDI->setArgOperand(2, MetadataAsValue::get(*C, NewExpr)); 1045 } 1046 1047 size_t Size = getAllocaSizeInBytes(*AI); 1048 tagAlloca(IRB, AI, Tag, Size); 1049 1050 for (auto RI : RetVec) { 1051 IRB.SetInsertPoint(RI); 1052 1053 // Re-tag alloca memory with the special UAR tag. 1054 Value *Tag = getUARTag(IRB, StackTag); 1055 tagAlloca(IRB, AI, Tag, alignTo(Size, Mapping.getObjectAlignment())); 1056 } 1057 } 1058 1059 return true; 1060 } 1061 1062 bool HWAddressSanitizer::isInterestingAlloca(const AllocaInst &AI) { 1063 return (AI.getAllocatedType()->isSized() && 1064 // FIXME: instrument dynamic allocas, too 1065 AI.isStaticAlloca() && 1066 // alloca() may be called with 0 size, ignore it. 1067 getAllocaSizeInBytes(AI) > 0 && 1068 // We are only interested in allocas not promotable to registers. 1069 // Promotable allocas are common under -O0. 1070 !isAllocaPromotable(&AI) && 1071 // inalloca allocas are not treated as static, and we don't want 1072 // dynamic alloca instrumentation for them as well. 1073 !AI.isUsedWithInAlloca() && 1074 // swifterror allocas are register promoted by ISel 1075 !AI.isSwiftError()); 1076 } 1077 1078 bool HWAddressSanitizer::sanitizeFunction(Function &F) { 1079 if (&F == HwasanCtorFunction) 1080 return false; 1081 1082 if (!F.hasFnAttribute(Attribute::SanitizeHWAddress)) 1083 return false; 1084 1085 LLVM_DEBUG(dbgs() << "Function: " << F.getName() << "\n"); 1086 1087 SmallVector<Instruction*, 16> ToInstrument; 1088 SmallVector<AllocaInst*, 8> AllocasToInstrument; 1089 SmallVector<Instruction*, 8> RetVec; 1090 SmallVector<Instruction*, 8> LandingPadVec; 1091 DenseMap<AllocaInst *, std::vector<DbgDeclareInst *>> AllocaDeclareMap; 1092 for (auto &BB : F) { 1093 for (auto &Inst : BB) { 1094 if (ClInstrumentStack) 1095 if (AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) { 1096 if (isInterestingAlloca(*AI)) 1097 AllocasToInstrument.push_back(AI); 1098 continue; 1099 } 1100 1101 if (isa<ReturnInst>(Inst) || isa<ResumeInst>(Inst) || 1102 isa<CleanupReturnInst>(Inst)) 1103 RetVec.push_back(&Inst); 1104 1105 if (auto *DDI = dyn_cast<DbgDeclareInst>(&Inst)) 1106 if (auto *Alloca = dyn_cast_or_null<AllocaInst>(DDI->getAddress())) 1107 AllocaDeclareMap[Alloca].push_back(DDI); 1108 1109 if (InstrumentLandingPads && isa<LandingPadInst>(Inst)) 1110 LandingPadVec.push_back(&Inst); 1111 1112 Value *MaybeMask = nullptr; 1113 bool IsWrite; 1114 unsigned Alignment; 1115 uint64_t TypeSize; 1116 Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize, 1117 &Alignment, &MaybeMask); 1118 if (Addr || isa<MemIntrinsic>(Inst)) 1119 ToInstrument.push_back(&Inst); 1120 } 1121 } 1122 1123 initializeCallbacks(*F.getParent()); 1124 1125 if (!LandingPadVec.empty()) 1126 instrumentLandingPads(LandingPadVec); 1127 1128 if (AllocasToInstrument.empty() && F.hasPersonalityFn() && 1129 F.getPersonalityFn()->getName() == kHwasanPersonalityThunkName) { 1130 // __hwasan_personality_thunk is a no-op for functions without an 1131 // instrumented stack, so we can drop it. 1132 F.setPersonalityFn(nullptr); 1133 } 1134 1135 if (AllocasToInstrument.empty() && ToInstrument.empty()) 1136 return false; 1137 1138 assert(!LocalDynamicShadow); 1139 1140 Instruction *InsertPt = &*F.getEntryBlock().begin(); 1141 IRBuilder<> EntryIRB(InsertPt); 1142 emitPrologue(EntryIRB, 1143 /*WithFrameRecord*/ ClRecordStackHistory && 1144 !AllocasToInstrument.empty()); 1145 1146 bool Changed = false; 1147 if (!AllocasToInstrument.empty()) { 1148 Value *StackTag = 1149 ClGenerateTagsWithCalls ? nullptr : getStackBaseTag(EntryIRB); 1150 Changed |= instrumentStack(AllocasToInstrument, AllocaDeclareMap, RetVec, 1151 StackTag); 1152 } 1153 1154 // Pad and align each of the allocas that we instrumented to stop small 1155 // uninteresting allocas from hiding in instrumented alloca's padding and so 1156 // that we have enough space to store real tags for short granules. 1157 DenseMap<AllocaInst *, AllocaInst *> AllocaToPaddedAllocaMap; 1158 for (AllocaInst *AI : AllocasToInstrument) { 1159 uint64_t Size = getAllocaSizeInBytes(*AI); 1160 uint64_t AlignedSize = alignTo(Size, Mapping.getObjectAlignment()); 1161 AI->setAlignment( 1162 MaybeAlign(std::max(AI->getAlignment(), Mapping.getObjectAlignment()))); 1163 if (Size != AlignedSize) { 1164 Type *AllocatedType = AI->getAllocatedType(); 1165 if (AI->isArrayAllocation()) { 1166 uint64_t ArraySize = 1167 cast<ConstantInt>(AI->getArraySize())->getZExtValue(); 1168 AllocatedType = ArrayType::get(AllocatedType, ArraySize); 1169 } 1170 Type *TypeWithPadding = StructType::get( 1171 AllocatedType, ArrayType::get(Int8Ty, AlignedSize - Size)); 1172 auto *NewAI = new AllocaInst( 1173 TypeWithPadding, AI->getType()->getAddressSpace(), nullptr, "", AI); 1174 NewAI->takeName(AI); 1175 NewAI->setAlignment(MaybeAlign(AI->getAlignment())); 1176 NewAI->setUsedWithInAlloca(AI->isUsedWithInAlloca()); 1177 NewAI->setSwiftError(AI->isSwiftError()); 1178 NewAI->copyMetadata(*AI); 1179 auto *Bitcast = new BitCastInst(NewAI, AI->getType(), "", AI); 1180 AI->replaceAllUsesWith(Bitcast); 1181 AllocaToPaddedAllocaMap[AI] = NewAI; 1182 } 1183 } 1184 1185 if (!AllocaToPaddedAllocaMap.empty()) { 1186 for (auto &BB : F) 1187 for (auto &Inst : BB) 1188 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&Inst)) 1189 if (auto *AI = 1190 dyn_cast_or_null<AllocaInst>(DVI->getVariableLocation())) 1191 if (auto *NewAI = AllocaToPaddedAllocaMap.lookup(AI)) 1192 DVI->setArgOperand( 1193 0, MetadataAsValue::get(*C, LocalAsMetadata::get(NewAI))); 1194 for (auto &P : AllocaToPaddedAllocaMap) 1195 P.first->eraseFromParent(); 1196 } 1197 1198 // If we split the entry block, move any allocas that were originally in the 1199 // entry block back into the entry block so that they aren't treated as 1200 // dynamic allocas. 1201 if (EntryIRB.GetInsertBlock() != &F.getEntryBlock()) { 1202 InsertPt = &*F.getEntryBlock().begin(); 1203 for (auto II = EntryIRB.GetInsertBlock()->begin(), 1204 IE = EntryIRB.GetInsertBlock()->end(); 1205 II != IE;) { 1206 Instruction *I = &*II++; 1207 if (auto *AI = dyn_cast<AllocaInst>(I)) 1208 if (isa<ConstantInt>(AI->getArraySize())) 1209 I->moveBefore(InsertPt); 1210 } 1211 } 1212 1213 for (auto Inst : ToInstrument) 1214 Changed |= instrumentMemAccess(Inst); 1215 1216 LocalDynamicShadow = nullptr; 1217 StackBaseTag = nullptr; 1218 1219 return Changed; 1220 } 1221 1222 void HWAddressSanitizer::instrumentGlobal(GlobalVariable *GV, uint8_t Tag) { 1223 Constant *Initializer = GV->getInitializer(); 1224 uint64_t SizeInBytes = 1225 M.getDataLayout().getTypeAllocSize(Initializer->getType()); 1226 uint64_t NewSize = alignTo(SizeInBytes, Mapping.getObjectAlignment()); 1227 if (SizeInBytes != NewSize) { 1228 // Pad the initializer out to the next multiple of 16 bytes and add the 1229 // required short granule tag. 1230 std::vector<uint8_t> Init(NewSize - SizeInBytes, 0); 1231 Init.back() = Tag; 1232 Constant *Padding = ConstantDataArray::get(*C, Init); 1233 Initializer = ConstantStruct::getAnon({Initializer, Padding}); 1234 } 1235 1236 auto *NewGV = new GlobalVariable(M, Initializer->getType(), GV->isConstant(), 1237 GlobalValue::ExternalLinkage, Initializer, 1238 GV->getName() + ".hwasan"); 1239 NewGV->copyAttributesFrom(GV); 1240 NewGV->setLinkage(GlobalValue::PrivateLinkage); 1241 NewGV->copyMetadata(GV, 0); 1242 NewGV->setAlignment( 1243 MaybeAlign(std::max(GV->getAlignment(), Mapping.getObjectAlignment()))); 1244 1245 // It is invalid to ICF two globals that have different tags. In the case 1246 // where the size of the global is a multiple of the tag granularity the 1247 // contents of the globals may be the same but the tags (i.e. symbol values) 1248 // may be different, and the symbols are not considered during ICF. In the 1249 // case where the size is not a multiple of the granularity, the short granule 1250 // tags would discriminate two globals with different tags, but there would 1251 // otherwise be nothing stopping such a global from being incorrectly ICF'd 1252 // with an uninstrumented (i.e. tag 0) global that happened to have the short 1253 // granule tag in the last byte. 1254 NewGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None); 1255 1256 // Descriptor format (assuming little-endian): 1257 // bytes 0-3: relative address of global 1258 // bytes 4-6: size of global (16MB ought to be enough for anyone, but in case 1259 // it isn't, we create multiple descriptors) 1260 // byte 7: tag 1261 auto *DescriptorTy = StructType::get(Int32Ty, Int32Ty); 1262 const uint64_t MaxDescriptorSize = 0xfffff0; 1263 for (uint64_t DescriptorPos = 0; DescriptorPos < SizeInBytes; 1264 DescriptorPos += MaxDescriptorSize) { 1265 auto *Descriptor = 1266 new GlobalVariable(M, DescriptorTy, true, GlobalValue::PrivateLinkage, 1267 nullptr, GV->getName() + ".hwasan.descriptor"); 1268 auto *GVRelPtr = ConstantExpr::getTrunc( 1269 ConstantExpr::getAdd( 1270 ConstantExpr::getSub( 1271 ConstantExpr::getPtrToInt(NewGV, Int64Ty), 1272 ConstantExpr::getPtrToInt(Descriptor, Int64Ty)), 1273 ConstantInt::get(Int64Ty, DescriptorPos)), 1274 Int32Ty); 1275 uint32_t Size = std::min(SizeInBytes - DescriptorPos, MaxDescriptorSize); 1276 auto *SizeAndTag = ConstantInt::get(Int32Ty, Size | (uint32_t(Tag) << 24)); 1277 Descriptor->setComdat(NewGV->getComdat()); 1278 Descriptor->setInitializer(ConstantStruct::getAnon({GVRelPtr, SizeAndTag})); 1279 Descriptor->setSection("hwasan_globals"); 1280 Descriptor->setMetadata(LLVMContext::MD_associated, 1281 MDNode::get(*C, ValueAsMetadata::get(NewGV))); 1282 appendToCompilerUsed(M, Descriptor); 1283 } 1284 1285 Constant *Aliasee = ConstantExpr::getIntToPtr( 1286 ConstantExpr::getAdd( 1287 ConstantExpr::getPtrToInt(NewGV, Int64Ty), 1288 ConstantInt::get(Int64Ty, uint64_t(Tag) << kPointerTagShift)), 1289 GV->getType()); 1290 auto *Alias = GlobalAlias::create(GV->getValueType(), GV->getAddressSpace(), 1291 GV->getLinkage(), "", Aliasee, &M); 1292 Alias->setVisibility(GV->getVisibility()); 1293 Alias->takeName(GV); 1294 GV->replaceAllUsesWith(Alias); 1295 GV->eraseFromParent(); 1296 } 1297 1298 void HWAddressSanitizer::instrumentGlobals() { 1299 // Start by creating a note that contains pointers to the list of global 1300 // descriptors. Adding a note to the output file will cause the linker to 1301 // create a PT_NOTE program header pointing to the note that we can use to 1302 // find the descriptor list starting from the program headers. A function 1303 // provided by the runtime initializes the shadow memory for the globals by 1304 // accessing the descriptor list via the note. The dynamic loader needs to 1305 // call this function whenever a library is loaded. 1306 // 1307 // The reason why we use a note for this instead of a more conventional 1308 // approach of having a global constructor pass a descriptor list pointer to 1309 // the runtime is because of an order of initialization problem. With 1310 // constructors we can encounter the following problematic scenario: 1311 // 1312 // 1) library A depends on library B and also interposes one of B's symbols 1313 // 2) B's constructors are called before A's (as required for correctness) 1314 // 3) during construction, B accesses one of its "own" globals (actually 1315 // interposed by A) and triggers a HWASAN failure due to the initialization 1316 // for A not having happened yet 1317 // 1318 // Even without interposition it is possible to run into similar situations in 1319 // cases where two libraries mutually depend on each other. 1320 // 1321 // We only need one note per binary, so put everything for the note in a 1322 // comdat. 1323 Comdat *NoteComdat = M.getOrInsertComdat(kHwasanNoteName); 1324 1325 Type *Int8Arr0Ty = ArrayType::get(Int8Ty, 0); 1326 auto Start = 1327 new GlobalVariable(M, Int8Arr0Ty, true, GlobalVariable::ExternalLinkage, 1328 nullptr, "__start_hwasan_globals"); 1329 Start->setVisibility(GlobalValue::HiddenVisibility); 1330 Start->setDSOLocal(true); 1331 auto Stop = 1332 new GlobalVariable(M, Int8Arr0Ty, true, GlobalVariable::ExternalLinkage, 1333 nullptr, "__stop_hwasan_globals"); 1334 Stop->setVisibility(GlobalValue::HiddenVisibility); 1335 Stop->setDSOLocal(true); 1336 1337 // Null-terminated so actually 8 bytes, which are required in order to align 1338 // the note properly. 1339 auto *Name = ConstantDataArray::get(*C, "LLVM\0\0\0"); 1340 1341 auto *NoteTy = StructType::get(Int32Ty, Int32Ty, Int32Ty, Name->getType(), 1342 Int32Ty, Int32Ty); 1343 auto *Note = 1344 new GlobalVariable(M, NoteTy, /*isConstantGlobal=*/true, 1345 GlobalValue::PrivateLinkage, nullptr, kHwasanNoteName); 1346 Note->setSection(".note.hwasan.globals"); 1347 Note->setComdat(NoteComdat); 1348 Note->setAlignment(Align(4)); 1349 Note->setDSOLocal(true); 1350 1351 // The pointers in the note need to be relative so that the note ends up being 1352 // placed in rodata, which is the standard location for notes. 1353 auto CreateRelPtr = [&](Constant *Ptr) { 1354 return ConstantExpr::getTrunc( 1355 ConstantExpr::getSub(ConstantExpr::getPtrToInt(Ptr, Int64Ty), 1356 ConstantExpr::getPtrToInt(Note, Int64Ty)), 1357 Int32Ty); 1358 }; 1359 Note->setInitializer(ConstantStruct::getAnon( 1360 {ConstantInt::get(Int32Ty, 8), // n_namesz 1361 ConstantInt::get(Int32Ty, 8), // n_descsz 1362 ConstantInt::get(Int32Ty, ELF::NT_LLVM_HWASAN_GLOBALS), // n_type 1363 Name, CreateRelPtr(Start), CreateRelPtr(Stop)})); 1364 appendToCompilerUsed(M, Note); 1365 1366 // Create a zero-length global in hwasan_globals so that the linker will 1367 // always create start and stop symbols. 1368 auto Dummy = new GlobalVariable( 1369 M, Int8Arr0Ty, /*isConstantGlobal*/ true, GlobalVariable::PrivateLinkage, 1370 Constant::getNullValue(Int8Arr0Ty), "hwasan.dummy.global"); 1371 Dummy->setSection("hwasan_globals"); 1372 Dummy->setComdat(NoteComdat); 1373 Dummy->setMetadata(LLVMContext::MD_associated, 1374 MDNode::get(*C, ValueAsMetadata::get(Note))); 1375 appendToCompilerUsed(M, Dummy); 1376 1377 std::vector<GlobalVariable *> Globals; 1378 for (GlobalVariable &GV : M.globals()) { 1379 if (GV.isDeclarationForLinker() || GV.getName().startswith("llvm.") || 1380 GV.isThreadLocal()) 1381 continue; 1382 1383 // Common symbols can't have aliases point to them, so they can't be tagged. 1384 if (GV.hasCommonLinkage()) 1385 continue; 1386 1387 // Globals with custom sections may be used in __start_/__stop_ enumeration, 1388 // which would be broken both by adding tags and potentially by the extra 1389 // padding/alignment that we insert. 1390 if (GV.hasSection()) 1391 continue; 1392 1393 Globals.push_back(&GV); 1394 } 1395 1396 MD5 Hasher; 1397 Hasher.update(M.getSourceFileName()); 1398 MD5::MD5Result Hash; 1399 Hasher.final(Hash); 1400 uint8_t Tag = Hash[0]; 1401 1402 for (GlobalVariable *GV : Globals) { 1403 // Skip tag 0 in order to avoid collisions with untagged memory. 1404 if (Tag == 0) 1405 Tag = 1; 1406 instrumentGlobal(GV, Tag++); 1407 } 1408 } 1409 1410 void HWAddressSanitizer::instrumentPersonalityFunctions() { 1411 // We need to untag stack frames as we unwind past them. That is the job of 1412 // the personality function wrapper, which either wraps an existing 1413 // personality function or acts as a personality function on its own. Each 1414 // function that has a personality function or that can be unwound past has 1415 // its personality function changed to a thunk that calls the personality 1416 // function wrapper in the runtime. 1417 MapVector<Constant *, std::vector<Function *>> PersonalityFns; 1418 for (Function &F : M) { 1419 if (F.isDeclaration() || !F.hasFnAttribute(Attribute::SanitizeHWAddress)) 1420 continue; 1421 1422 if (F.hasPersonalityFn()) { 1423 PersonalityFns[F.getPersonalityFn()->stripPointerCasts()].push_back(&F); 1424 } else if (!F.hasFnAttribute(Attribute::NoUnwind)) { 1425 PersonalityFns[nullptr].push_back(&F); 1426 } 1427 } 1428 1429 if (PersonalityFns.empty()) 1430 return; 1431 1432 FunctionCallee HwasanPersonalityWrapper = M.getOrInsertFunction( 1433 "__hwasan_personality_wrapper", Int32Ty, Int32Ty, Int32Ty, Int64Ty, 1434 Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy); 1435 FunctionCallee UnwindGetGR = M.getOrInsertFunction("_Unwind_GetGR", VoidTy); 1436 FunctionCallee UnwindGetCFA = M.getOrInsertFunction("_Unwind_GetCFA", VoidTy); 1437 1438 for (auto &P : PersonalityFns) { 1439 std::string ThunkName = kHwasanPersonalityThunkName; 1440 if (P.first) 1441 ThunkName += ("." + P.first->getName()).str(); 1442 FunctionType *ThunkFnTy = FunctionType::get( 1443 Int32Ty, {Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int8PtrTy}, false); 1444 bool IsLocal = P.first && (!isa<GlobalValue>(P.first) || 1445 cast<GlobalValue>(P.first)->hasLocalLinkage()); 1446 auto *ThunkFn = Function::Create(ThunkFnTy, 1447 IsLocal ? GlobalValue::InternalLinkage 1448 : GlobalValue::LinkOnceODRLinkage, 1449 ThunkName, &M); 1450 if (!IsLocal) { 1451 ThunkFn->setVisibility(GlobalValue::HiddenVisibility); 1452 ThunkFn->setComdat(M.getOrInsertComdat(ThunkName)); 1453 } 1454 1455 auto *BB = BasicBlock::Create(*C, "entry", ThunkFn); 1456 IRBuilder<> IRB(BB); 1457 CallInst *WrapperCall = IRB.CreateCall( 1458 HwasanPersonalityWrapper, 1459 {ThunkFn->getArg(0), ThunkFn->getArg(1), ThunkFn->getArg(2), 1460 ThunkFn->getArg(3), ThunkFn->getArg(4), 1461 P.first ? IRB.CreateBitCast(P.first, Int8PtrTy) 1462 : Constant::getNullValue(Int8PtrTy), 1463 IRB.CreateBitCast(UnwindGetGR.getCallee(), Int8PtrTy), 1464 IRB.CreateBitCast(UnwindGetCFA.getCallee(), Int8PtrTy)}); 1465 WrapperCall->setTailCall(); 1466 IRB.CreateRet(WrapperCall); 1467 1468 for (Function *F : P.second) 1469 F->setPersonalityFn(ThunkFn); 1470 } 1471 } 1472 1473 void HWAddressSanitizer::ShadowMapping::init(Triple &TargetTriple) { 1474 Scale = kDefaultShadowScale; 1475 if (ClMappingOffset.getNumOccurrences() > 0) { 1476 InGlobal = false; 1477 InTls = false; 1478 Offset = ClMappingOffset; 1479 } else if (ClEnableKhwasan || ClInstrumentWithCalls) { 1480 InGlobal = false; 1481 InTls = false; 1482 Offset = 0; 1483 } else if (ClWithIfunc) { 1484 InGlobal = true; 1485 InTls = false; 1486 Offset = kDynamicShadowSentinel; 1487 } else if (ClWithTls) { 1488 InGlobal = false; 1489 InTls = true; 1490 Offset = kDynamicShadowSentinel; 1491 } else { 1492 InGlobal = false; 1493 InTls = false; 1494 Offset = kDynamicShadowSentinel; 1495 } 1496 } 1497