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