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