1 //===-- ShadowStackGCLowering.cpp - Custom lowering for shadow-stack gc ---===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the custom lowering code required by the shadow-stack GC 11 // strategy. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/Passes.h" 16 #include "llvm/ADT/StringExtras.h" 17 #include "llvm/CodeGen/GCStrategy.h" 18 #include "llvm/IR/CallSite.h" 19 #include "llvm/IR/IRBuilder.h" 20 #include "llvm/IR/IntrinsicInst.h" 21 #include "llvm/IR/Module.h" 22 23 using namespace llvm; 24 25 #define DEBUG_TYPE "shadowstackgclowering" 26 27 namespace { 28 29 class ShadowStackGCLowering : public FunctionPass { 30 /// RootChain - This is the global linked-list that contains the chain of GC 31 /// roots. 32 GlobalVariable *Head; 33 34 /// StackEntryTy - Abstract type of a link in the shadow stack. 35 /// 36 StructType *StackEntryTy; 37 StructType *FrameMapTy; 38 39 /// Roots - GC roots in the current function. Each is a pair of the 40 /// intrinsic call and its corresponding alloca. 41 std::vector<std::pair<CallInst *, AllocaInst *>> Roots; 42 43 public: 44 static char ID; 45 ShadowStackGCLowering(); 46 47 bool doInitialization(Module &M) override; 48 bool runOnFunction(Function &F) override; 49 50 private: 51 bool IsNullValue(Value *V); 52 Constant *GetFrameMap(Function &F); 53 Type *GetConcreteStackEntryType(Function &F); 54 void CollectRoots(Function &F); 55 static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B, 56 Type *Ty, Value *BasePtr, int Idx1, 57 const char *Name); 58 static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B, 59 Type *Ty, Value *BasePtr, int Idx1, int Idx2, 60 const char *Name); 61 }; 62 } 63 64 INITIALIZE_PASS_BEGIN(ShadowStackGCLowering, "shadow-stack-gc-lowering", 65 "Shadow Stack GC Lowering", false, false) 66 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo) 67 INITIALIZE_PASS_END(ShadowStackGCLowering, "shadow-stack-gc-lowering", 68 "Shadow Stack GC Lowering", false, false) 69 70 FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); } 71 72 char ShadowStackGCLowering::ID = 0; 73 74 ShadowStackGCLowering::ShadowStackGCLowering() 75 : FunctionPass(ID), Head(nullptr), StackEntryTy(nullptr), 76 FrameMapTy(nullptr) { 77 initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry()); 78 } 79 80 namespace { 81 /// EscapeEnumerator - This is a little algorithm to find all escape points 82 /// from a function so that "finally"-style code can be inserted. In addition 83 /// to finding the existing return and unwind instructions, it also (if 84 /// necessary) transforms any call instructions into invokes and sends them to 85 /// a landing pad. 86 /// 87 /// It's wrapped up in a state machine using the same transform C# uses for 88 /// 'yield return' enumerators, This transform allows it to be non-allocating. 89 class EscapeEnumerator { 90 Function &F; 91 const char *CleanupBBName; 92 93 // State. 94 int State; 95 Function::iterator StateBB, StateE; 96 IRBuilder<> Builder; 97 98 public: 99 EscapeEnumerator(Function &F, const char *N = "cleanup") 100 : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {} 101 102 IRBuilder<> *Next() { 103 switch (State) { 104 default: 105 return nullptr; 106 107 case 0: 108 StateBB = F.begin(); 109 StateE = F.end(); 110 State = 1; 111 112 case 1: 113 // Find all 'return', 'resume', and 'unwind' instructions. 114 while (StateBB != StateE) { 115 BasicBlock *CurBB = &*StateBB++; 116 117 // Branches and invokes do not escape, only unwind, resume, and return 118 // do. 119 TerminatorInst *TI = CurBB->getTerminator(); 120 if (!isa<ReturnInst>(TI) && !isa<ResumeInst>(TI)) 121 continue; 122 123 Builder.SetInsertPoint(TI); 124 return &Builder; 125 } 126 127 State = 2; 128 129 // Find all 'call' instructions. 130 SmallVector<Instruction *, 16> Calls; 131 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 132 for (BasicBlock::iterator II = BB->begin(), EE = BB->end(); II != EE; 133 ++II) 134 if (CallInst *CI = dyn_cast<CallInst>(II)) 135 if (!CI->getCalledFunction() || 136 !CI->getCalledFunction()->getIntrinsicID()) 137 Calls.push_back(CI); 138 139 if (Calls.empty()) 140 return nullptr; 141 142 // Create a cleanup block. 143 LLVMContext &C = F.getContext(); 144 BasicBlock *CleanupBB = BasicBlock::Create(C, CleanupBBName, &F); 145 Type *ExnTy = 146 StructType::get(Type::getInt8PtrTy(C), Type::getInt32Ty(C), nullptr); 147 if (!F.hasPersonalityFn()) { 148 Constant *PersFn = F.getParent()->getOrInsertFunction( 149 "__gcc_personality_v0", 150 FunctionType::get(Type::getInt32Ty(C), true)); 151 F.setPersonalityFn(PersFn); 152 } 153 LandingPadInst *LPad = 154 LandingPadInst::Create(ExnTy, 1, "cleanup.lpad", CleanupBB); 155 LPad->setCleanup(true); 156 ResumeInst *RI = ResumeInst::Create(LPad, CleanupBB); 157 158 // Transform the 'call' instructions into 'invoke's branching to the 159 // cleanup block. Go in reverse order to make prettier BB names. 160 SmallVector<Value *, 16> Args; 161 for (unsigned I = Calls.size(); I != 0;) { 162 CallInst *CI = cast<CallInst>(Calls[--I]); 163 164 // Split the basic block containing the function call. 165 BasicBlock *CallBB = CI->getParent(); 166 BasicBlock *NewBB = CallBB->splitBasicBlock( 167 CI->getIterator(), CallBB->getName() + ".cont"); 168 169 // Remove the unconditional branch inserted at the end of CallBB. 170 CallBB->getInstList().pop_back(); 171 NewBB->getInstList().remove(CI); 172 173 // Create a new invoke instruction. 174 Args.clear(); 175 CallSite CS(CI); 176 Args.append(CS.arg_begin(), CS.arg_end()); 177 178 InvokeInst *II = 179 InvokeInst::Create(CI->getCalledValue(), NewBB, CleanupBB, Args, 180 CI->getName(), CallBB); 181 II->setCallingConv(CI->getCallingConv()); 182 II->setAttributes(CI->getAttributes()); 183 CI->replaceAllUsesWith(II); 184 delete CI; 185 } 186 187 Builder.SetInsertPoint(RI); 188 return &Builder; 189 } 190 } 191 }; 192 } 193 194 195 Constant *ShadowStackGCLowering::GetFrameMap(Function &F) { 196 // doInitialization creates the abstract type of this value. 197 Type *VoidPtr = Type::getInt8PtrTy(F.getContext()); 198 199 // Truncate the ShadowStackDescriptor if some metadata is null. 200 unsigned NumMeta = 0; 201 SmallVector<Constant *, 16> Metadata; 202 for (unsigned I = 0; I != Roots.size(); ++I) { 203 Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1)); 204 if (!C->isNullValue()) 205 NumMeta = I + 1; 206 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr)); 207 } 208 Metadata.resize(NumMeta); 209 210 Type *Int32Ty = Type::getInt32Ty(F.getContext()); 211 212 Constant *BaseElts[] = { 213 ConstantInt::get(Int32Ty, Roots.size(), false), 214 ConstantInt::get(Int32Ty, NumMeta, false), 215 }; 216 217 Constant *DescriptorElts[] = { 218 ConstantStruct::get(FrameMapTy, BaseElts), 219 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)}; 220 221 Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()}; 222 StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta)); 223 224 Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts); 225 226 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems 227 // that, short of multithreaded LLVM, it should be safe; all that is 228 // necessary is that a simple Module::iterator loop not be invalidated. 229 // Appending to the GlobalVariable list is safe in that sense. 230 // 231 // All of the output passes emit globals last. The ExecutionEngine 232 // explicitly supports adding globals to the module after 233 // initialization. 234 // 235 // Still, if it isn't deemed acceptable, then this transformation needs 236 // to be a ModulePass (which means it cannot be in the 'llc' pipeline 237 // (which uses a FunctionPassManager (which segfaults (not asserts) if 238 // provided a ModulePass))). 239 Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true, 240 GlobalVariable::InternalLinkage, FrameMap, 241 "__gc_" + F.getName()); 242 243 Constant *GEPIndices[2] = { 244 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0), 245 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)}; 246 return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices); 247 } 248 249 Type *ShadowStackGCLowering::GetConcreteStackEntryType(Function &F) { 250 // doInitialization creates the generic version of this type. 251 std::vector<Type *> EltTys; 252 EltTys.push_back(StackEntryTy); 253 for (size_t I = 0; I != Roots.size(); I++) 254 EltTys.push_back(Roots[I].second->getAllocatedType()); 255 256 return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str()); 257 } 258 259 /// doInitialization - If this module uses the GC intrinsics, find them now. If 260 /// not, exit fast. 261 bool ShadowStackGCLowering::doInitialization(Module &M) { 262 bool Active = false; 263 for (Function &F : M) { 264 if (F.hasGC() && F.getGC() == std::string("shadow-stack")) { 265 Active = true; 266 break; 267 } 268 } 269 if (!Active) 270 return false; 271 272 // struct FrameMap { 273 // int32_t NumRoots; // Number of roots in stack frame. 274 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots. 275 // void *Meta[]; // May be absent for roots without metadata. 276 // }; 277 std::vector<Type *> EltTys; 278 // 32 bits is ok up to a 32GB stack frame. :) 279 EltTys.push_back(Type::getInt32Ty(M.getContext())); 280 // Specifies length of variable length array. 281 EltTys.push_back(Type::getInt32Ty(M.getContext())); 282 FrameMapTy = StructType::create(EltTys, "gc_map"); 283 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy); 284 285 // struct StackEntry { 286 // ShadowStackEntry *Next; // Caller's stack entry. 287 // FrameMap *Map; // Pointer to constant FrameMap. 288 // void *Roots[]; // Stack roots (in-place array, so we pretend). 289 // }; 290 291 StackEntryTy = StructType::create(M.getContext(), "gc_stackentry"); 292 293 EltTys.clear(); 294 EltTys.push_back(PointerType::getUnqual(StackEntryTy)); 295 EltTys.push_back(FrameMapPtrTy); 296 StackEntryTy->setBody(EltTys); 297 PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy); 298 299 // Get the root chain if it already exists. 300 Head = M.getGlobalVariable("llvm_gc_root_chain"); 301 if (!Head) { 302 // If the root chain does not exist, insert a new one with linkonce 303 // linkage! 304 Head = new GlobalVariable( 305 M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage, 306 Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain"); 307 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) { 308 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy)); 309 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage); 310 } 311 312 return true; 313 } 314 315 bool ShadowStackGCLowering::IsNullValue(Value *V) { 316 if (Constant *C = dyn_cast<Constant>(V)) 317 return C->isNullValue(); 318 return false; 319 } 320 321 void ShadowStackGCLowering::CollectRoots(Function &F) { 322 // FIXME: Account for original alignment. Could fragment the root array. 323 // Approach 1: Null initialize empty slots at runtime. Yuck. 324 // Approach 2: Emit a map of the array instead of just a count. 325 326 assert(Roots.empty() && "Not cleaned up?"); 327 328 SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots; 329 330 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 331 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) 332 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) 333 if (Function *F = CI->getCalledFunction()) 334 if (F->getIntrinsicID() == Intrinsic::gcroot) { 335 std::pair<CallInst *, AllocaInst *> Pair = std::make_pair( 336 CI, 337 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts())); 338 if (IsNullValue(CI->getArgOperand(1))) 339 Roots.push_back(Pair); 340 else 341 MetaRoots.push_back(Pair); 342 } 343 344 // Number roots with metadata (usually empty) at the beginning, so that the 345 // FrameMap::Meta array can be elided. 346 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end()); 347 } 348 349 GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context, 350 IRBuilder<> &B, Type *Ty, 351 Value *BasePtr, int Idx, 352 int Idx2, 353 const char *Name) { 354 Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0), 355 ConstantInt::get(Type::getInt32Ty(Context), Idx), 356 ConstantInt::get(Type::getInt32Ty(Context), Idx2)}; 357 Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name); 358 359 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant"); 360 361 return dyn_cast<GetElementPtrInst>(Val); 362 } 363 364 GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context, 365 IRBuilder<> &B, Type *Ty, Value *BasePtr, 366 int Idx, const char *Name) { 367 Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0), 368 ConstantInt::get(Type::getInt32Ty(Context), Idx)}; 369 Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name); 370 371 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant"); 372 373 return dyn_cast<GetElementPtrInst>(Val); 374 } 375 376 /// runOnFunction - Insert code to maintain the shadow stack. 377 bool ShadowStackGCLowering::runOnFunction(Function &F) { 378 // Quick exit for functions that do not use the shadow stack GC. 379 if (!F.hasGC() || 380 F.getGC() != std::string("shadow-stack")) 381 return false; 382 383 LLVMContext &Context = F.getContext(); 384 385 // Find calls to llvm.gcroot. 386 CollectRoots(F); 387 388 // If there are no roots in this function, then there is no need to add a 389 // stack map entry for it. 390 if (Roots.empty()) 391 return false; 392 393 // Build the constant map and figure the type of the shadow stack entry. 394 Value *FrameMap = GetFrameMap(F); 395 Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F); 396 397 // Build the shadow stack entry at the very start of the function. 398 BasicBlock::iterator IP = F.getEntryBlock().begin(); 399 IRBuilder<> AtEntry(IP->getParent(), IP); 400 401 Instruction *StackEntry = 402 AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame"); 403 404 while (isa<AllocaInst>(IP)) 405 ++IP; 406 AtEntry.SetInsertPoint(IP->getParent(), IP); 407 408 // Initialize the map pointer and load the current head of the shadow stack. 409 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead"); 410 Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy, 411 StackEntry, 0, 1, "gc_frame.map"); 412 AtEntry.CreateStore(FrameMap, EntryMapPtr); 413 414 // After all the allocas... 415 for (unsigned I = 0, E = Roots.size(); I != E; ++I) { 416 // For each root, find the corresponding slot in the aggregate... 417 Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy, 418 StackEntry, 1 + I, "gc_root"); 419 420 // And use it in lieu of the alloca. 421 AllocaInst *OriginalAlloca = Roots[I].second; 422 SlotPtr->takeName(OriginalAlloca); 423 OriginalAlloca->replaceAllUsesWith(SlotPtr); 424 } 425 426 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't 427 // really necessary (the collector would never see the intermediate state at 428 // runtime), but it's nicer not to push the half-initialized entry onto the 429 // shadow stack. 430 while (isa<StoreInst>(IP)) 431 ++IP; 432 AtEntry.SetInsertPoint(IP->getParent(), IP); 433 434 // Push the entry onto the shadow stack. 435 Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy, 436 StackEntry, 0, 0, "gc_frame.next"); 437 Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy, 438 StackEntry, 0, "gc_newhead"); 439 AtEntry.CreateStore(CurrentHead, EntryNextPtr); 440 AtEntry.CreateStore(NewHeadVal, Head); 441 442 // For each instruction that escapes... 443 EscapeEnumerator EE(F, "gc_cleanup"); 444 while (IRBuilder<> *AtExit = EE.Next()) { 445 // Pop the entry from the shadow stack. Don't reuse CurrentHead from 446 // AtEntry, since that would make the value live for the entire function. 447 Instruction *EntryNextPtr2 = 448 CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0, 449 "gc_frame.next"); 450 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead"); 451 AtExit->CreateStore(SavedHead, Head); 452 } 453 454 // Delete the original allocas (which are no longer used) and the intrinsic 455 // calls (which are no longer valid). Doing this last avoids invalidating 456 // iterators. 457 for (unsigned I = 0, E = Roots.size(); I != E; ++I) { 458 Roots[I].first->eraseFromParent(); 459 Roots[I].second->eraseFromParent(); 460 } 461 462 Roots.clear(); 463 return true; 464 } 465