Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 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 |
Philip Reames | 3195500 | 2016-01-19 03:57:18 +0000 | [diff] [blame] | 11 | // strategy. |
| 12 | // |
| 13 | // This pass implements the code transformation described in this paper: |
| 14 | // "Accurate Garbage Collection in an Uncooperative Environment" |
| 15 | // Fergus Henderson, ISMM, 2002 |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 16 | // |
| 17 | //===----------------------------------------------------------------------===// |
| 18 | |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 19 | #include "llvm/ADT/StringExtras.h" |
Chandler Carruth | 71f308a | 2015-02-13 09:09:03 +0000 | [diff] [blame] | 20 | #include "llvm/CodeGen/GCStrategy.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame^] | 21 | #include "llvm/CodeGen/Passes.h" |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 22 | #include "llvm/IR/CallSite.h" |
| 23 | #include "llvm/IR/IRBuilder.h" |
| 24 | #include "llvm/IR/IntrinsicInst.h" |
| 25 | #include "llvm/IR/Module.h" |
Kuba Brecka | ddfdba3 | 2016-11-14 21:41:13 +0000 | [diff] [blame] | 26 | #include "llvm/Transforms/Utils/EscapeEnumerator.h" |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 27 | |
| 28 | using namespace llvm; |
| 29 | |
Matthias Braun | 1527baa | 2017-05-25 21:26:32 +0000 | [diff] [blame] | 30 | #define DEBUG_TYPE "shadow-stack-gc-lowering" |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 31 | |
| 32 | namespace { |
| 33 | |
| 34 | class ShadowStackGCLowering : public FunctionPass { |
| 35 | /// RootChain - This is the global linked-list that contains the chain of GC |
| 36 | /// roots. |
| 37 | GlobalVariable *Head; |
| 38 | |
| 39 | /// StackEntryTy - Abstract type of a link in the shadow stack. |
| 40 | /// |
| 41 | StructType *StackEntryTy; |
| 42 | StructType *FrameMapTy; |
| 43 | |
| 44 | /// Roots - GC roots in the current function. Each is a pair of the |
| 45 | /// intrinsic call and its corresponding alloca. |
| 46 | std::vector<std::pair<CallInst *, AllocaInst *>> Roots; |
| 47 | |
| 48 | public: |
| 49 | static char ID; |
| 50 | ShadowStackGCLowering(); |
| 51 | |
| 52 | bool doInitialization(Module &M) override; |
| 53 | bool runOnFunction(Function &F) override; |
| 54 | |
| 55 | private: |
| 56 | bool IsNullValue(Value *V); |
| 57 | Constant *GetFrameMap(Function &F); |
| 58 | Type *GetConcreteStackEntryType(Function &F); |
| 59 | void CollectRoots(Function &F); |
| 60 | static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B, |
David Blaikie | 86ecb1b | 2015-03-15 01:03:19 +0000 | [diff] [blame] | 61 | Type *Ty, Value *BasePtr, int Idx1, |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 62 | const char *Name); |
| 63 | static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B, |
David Blaikie | 86ecb1b | 2015-03-15 01:03:19 +0000 | [diff] [blame] | 64 | Type *Ty, Value *BasePtr, int Idx1, int Idx2, |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 65 | const char *Name); |
| 66 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 67 | } |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 68 | |
Matthias Braun | 1527baa | 2017-05-25 21:26:32 +0000 | [diff] [blame] | 69 | INITIALIZE_PASS_BEGIN(ShadowStackGCLowering, DEBUG_TYPE, |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 70 | "Shadow Stack GC Lowering", false, false) |
| 71 | INITIALIZE_PASS_DEPENDENCY(GCModuleInfo) |
Matthias Braun | 1527baa | 2017-05-25 21:26:32 +0000 | [diff] [blame] | 72 | INITIALIZE_PASS_END(ShadowStackGCLowering, DEBUG_TYPE, |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 73 | "Shadow Stack GC Lowering", false, false) |
| 74 | |
| 75 | FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); } |
| 76 | |
| 77 | char ShadowStackGCLowering::ID = 0; |
| 78 | |
| 79 | ShadowStackGCLowering::ShadowStackGCLowering() |
| 80 | : FunctionPass(ID), Head(nullptr), StackEntryTy(nullptr), |
| 81 | FrameMapTy(nullptr) { |
| 82 | initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry()); |
| 83 | } |
| 84 | |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 85 | Constant *ShadowStackGCLowering::GetFrameMap(Function &F) { |
| 86 | // doInitialization creates the abstract type of this value. |
| 87 | Type *VoidPtr = Type::getInt8PtrTy(F.getContext()); |
| 88 | |
| 89 | // Truncate the ShadowStackDescriptor if some metadata is null. |
| 90 | unsigned NumMeta = 0; |
| 91 | SmallVector<Constant *, 16> Metadata; |
| 92 | for (unsigned I = 0; I != Roots.size(); ++I) { |
| 93 | Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1)); |
| 94 | if (!C->isNullValue()) |
| 95 | NumMeta = I + 1; |
| 96 | Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr)); |
| 97 | } |
| 98 | Metadata.resize(NumMeta); |
| 99 | |
| 100 | Type *Int32Ty = Type::getInt32Ty(F.getContext()); |
| 101 | |
| 102 | Constant *BaseElts[] = { |
| 103 | ConstantInt::get(Int32Ty, Roots.size(), false), |
| 104 | ConstantInt::get(Int32Ty, NumMeta, false), |
| 105 | }; |
| 106 | |
| 107 | Constant *DescriptorElts[] = { |
| 108 | ConstantStruct::get(FrameMapTy, BaseElts), |
| 109 | ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)}; |
| 110 | |
| 111 | Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()}; |
| 112 | StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta)); |
| 113 | |
| 114 | Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts); |
| 115 | |
| 116 | // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems |
| 117 | // that, short of multithreaded LLVM, it should be safe; all that is |
| 118 | // necessary is that a simple Module::iterator loop not be invalidated. |
| 119 | // Appending to the GlobalVariable list is safe in that sense. |
| 120 | // |
| 121 | // All of the output passes emit globals last. The ExecutionEngine |
| 122 | // explicitly supports adding globals to the module after |
| 123 | // initialization. |
| 124 | // |
| 125 | // Still, if it isn't deemed acceptable, then this transformation needs |
| 126 | // to be a ModulePass (which means it cannot be in the 'llc' pipeline |
| 127 | // (which uses a FunctionPassManager (which segfaults (not asserts) if |
| 128 | // provided a ModulePass))). |
| 129 | Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true, |
| 130 | GlobalVariable::InternalLinkage, FrameMap, |
| 131 | "__gc_" + F.getName()); |
| 132 | |
| 133 | Constant *GEPIndices[2] = { |
| 134 | ConstantInt::get(Type::getInt32Ty(F.getContext()), 0), |
| 135 | ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)}; |
David Blaikie | 4a2e73b | 2015-04-02 18:55:32 +0000 | [diff] [blame] | 136 | return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices); |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 137 | } |
| 138 | |
| 139 | Type *ShadowStackGCLowering::GetConcreteStackEntryType(Function &F) { |
| 140 | // doInitialization creates the generic version of this type. |
| 141 | std::vector<Type *> EltTys; |
| 142 | EltTys.push_back(StackEntryTy); |
| 143 | for (size_t I = 0; I != Roots.size(); I++) |
| 144 | EltTys.push_back(Roots[I].second->getAllocatedType()); |
| 145 | |
Yaron Keren | 75e0c4b | 2015-03-27 17:51:30 +0000 | [diff] [blame] | 146 | return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str()); |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 147 | } |
| 148 | |
| 149 | /// doInitialization - If this module uses the GC intrinsics, find them now. If |
| 150 | /// not, exit fast. |
| 151 | bool ShadowStackGCLowering::doInitialization(Module &M) { |
| 152 | bool Active = false; |
| 153 | for (Function &F : M) { |
| 154 | if (F.hasGC() && F.getGC() == std::string("shadow-stack")) { |
| 155 | Active = true; |
| 156 | break; |
| 157 | } |
| 158 | } |
| 159 | if (!Active) |
| 160 | return false; |
| 161 | |
| 162 | // struct FrameMap { |
| 163 | // int32_t NumRoots; // Number of roots in stack frame. |
| 164 | // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots. |
| 165 | // void *Meta[]; // May be absent for roots without metadata. |
| 166 | // }; |
| 167 | std::vector<Type *> EltTys; |
| 168 | // 32 bits is ok up to a 32GB stack frame. :) |
| 169 | EltTys.push_back(Type::getInt32Ty(M.getContext())); |
| 170 | // Specifies length of variable length array. |
| 171 | EltTys.push_back(Type::getInt32Ty(M.getContext())); |
| 172 | FrameMapTy = StructType::create(EltTys, "gc_map"); |
| 173 | PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy); |
| 174 | |
| 175 | // struct StackEntry { |
| 176 | // ShadowStackEntry *Next; // Caller's stack entry. |
| 177 | // FrameMap *Map; // Pointer to constant FrameMap. |
| 178 | // void *Roots[]; // Stack roots (in-place array, so we pretend). |
| 179 | // }; |
| 180 | |
| 181 | StackEntryTy = StructType::create(M.getContext(), "gc_stackentry"); |
| 182 | |
| 183 | EltTys.clear(); |
| 184 | EltTys.push_back(PointerType::getUnqual(StackEntryTy)); |
| 185 | EltTys.push_back(FrameMapPtrTy); |
| 186 | StackEntryTy->setBody(EltTys); |
| 187 | PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy); |
| 188 | |
| 189 | // Get the root chain if it already exists. |
| 190 | Head = M.getGlobalVariable("llvm_gc_root_chain"); |
| 191 | if (!Head) { |
| 192 | // If the root chain does not exist, insert a new one with linkonce |
| 193 | // linkage! |
| 194 | Head = new GlobalVariable( |
| 195 | M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage, |
| 196 | Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain"); |
| 197 | } else if (Head->hasExternalLinkage() && Head->isDeclaration()) { |
| 198 | Head->setInitializer(Constant::getNullValue(StackEntryPtrTy)); |
| 199 | Head->setLinkage(GlobalValue::LinkOnceAnyLinkage); |
| 200 | } |
| 201 | |
| 202 | return true; |
| 203 | } |
| 204 | |
| 205 | bool ShadowStackGCLowering::IsNullValue(Value *V) { |
| 206 | if (Constant *C = dyn_cast<Constant>(V)) |
| 207 | return C->isNullValue(); |
| 208 | return false; |
| 209 | } |
| 210 | |
| 211 | void ShadowStackGCLowering::CollectRoots(Function &F) { |
| 212 | // FIXME: Account for original alignment. Could fragment the root array. |
| 213 | // Approach 1: Null initialize empty slots at runtime. Yuck. |
| 214 | // Approach 2: Emit a map of the array instead of just a count. |
| 215 | |
| 216 | assert(Roots.empty() && "Not cleaned up?"); |
| 217 | |
| 218 | SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots; |
| 219 | |
| 220 | for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) |
| 221 | for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) |
| 222 | if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) |
| 223 | if (Function *F = CI->getCalledFunction()) |
| 224 | if (F->getIntrinsicID() == Intrinsic::gcroot) { |
| 225 | std::pair<CallInst *, AllocaInst *> Pair = std::make_pair( |
| 226 | CI, |
| 227 | cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts())); |
| 228 | if (IsNullValue(CI->getArgOperand(1))) |
| 229 | Roots.push_back(Pair); |
| 230 | else |
| 231 | MetaRoots.push_back(Pair); |
| 232 | } |
| 233 | |
| 234 | // Number roots with metadata (usually empty) at the beginning, so that the |
| 235 | // FrameMap::Meta array can be elided. |
| 236 | Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end()); |
| 237 | } |
| 238 | |
| 239 | GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context, |
David Blaikie | 86ecb1b | 2015-03-15 01:03:19 +0000 | [diff] [blame] | 240 | IRBuilder<> &B, Type *Ty, |
| 241 | Value *BasePtr, int Idx, |
| 242 | int Idx2, |
| 243 | const char *Name) { |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 244 | Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0), |
| 245 | ConstantInt::get(Type::getInt32Ty(Context), Idx), |
| 246 | ConstantInt::get(Type::getInt32Ty(Context), Idx2)}; |
David Blaikie | 86ecb1b | 2015-03-15 01:03:19 +0000 | [diff] [blame] | 247 | Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name); |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 248 | |
| 249 | assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant"); |
| 250 | |
| 251 | return dyn_cast<GetElementPtrInst>(Val); |
| 252 | } |
| 253 | |
| 254 | GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context, |
David Blaikie | 86ecb1b | 2015-03-15 01:03:19 +0000 | [diff] [blame] | 255 | IRBuilder<> &B, Type *Ty, Value *BasePtr, |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 256 | int Idx, const char *Name) { |
| 257 | Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0), |
| 258 | ConstantInt::get(Type::getInt32Ty(Context), Idx)}; |
David Blaikie | 86ecb1b | 2015-03-15 01:03:19 +0000 | [diff] [blame] | 259 | Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name); |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 260 | |
| 261 | assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant"); |
| 262 | |
| 263 | return dyn_cast<GetElementPtrInst>(Val); |
| 264 | } |
| 265 | |
| 266 | /// runOnFunction - Insert code to maintain the shadow stack. |
| 267 | bool ShadowStackGCLowering::runOnFunction(Function &F) { |
| 268 | // Quick exit for functions that do not use the shadow stack GC. |
| 269 | if (!F.hasGC() || |
| 270 | F.getGC() != std::string("shadow-stack")) |
| 271 | return false; |
| 272 | |
| 273 | LLVMContext &Context = F.getContext(); |
| 274 | |
| 275 | // Find calls to llvm.gcroot. |
| 276 | CollectRoots(F); |
| 277 | |
| 278 | // If there are no roots in this function, then there is no need to add a |
| 279 | // stack map entry for it. |
| 280 | if (Roots.empty()) |
| 281 | return false; |
| 282 | |
| 283 | // Build the constant map and figure the type of the shadow stack entry. |
| 284 | Value *FrameMap = GetFrameMap(F); |
| 285 | Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F); |
| 286 | |
| 287 | // Build the shadow stack entry at the very start of the function. |
| 288 | BasicBlock::iterator IP = F.getEntryBlock().begin(); |
| 289 | IRBuilder<> AtEntry(IP->getParent(), IP); |
| 290 | |
| 291 | Instruction *StackEntry = |
| 292 | AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame"); |
| 293 | |
| 294 | while (isa<AllocaInst>(IP)) |
| 295 | ++IP; |
| 296 | AtEntry.SetInsertPoint(IP->getParent(), IP); |
| 297 | |
| 298 | // Initialize the map pointer and load the current head of the shadow stack. |
| 299 | Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead"); |
David Blaikie | 86ecb1b | 2015-03-15 01:03:19 +0000 | [diff] [blame] | 300 | Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy, |
| 301 | StackEntry, 0, 1, "gc_frame.map"); |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 302 | AtEntry.CreateStore(FrameMap, EntryMapPtr); |
| 303 | |
| 304 | // After all the allocas... |
| 305 | for (unsigned I = 0, E = Roots.size(); I != E; ++I) { |
| 306 | // For each root, find the corresponding slot in the aggregate... |
David Blaikie | 86ecb1b | 2015-03-15 01:03:19 +0000 | [diff] [blame] | 307 | Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy, |
| 308 | StackEntry, 1 + I, "gc_root"); |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 309 | |
| 310 | // And use it in lieu of the alloca. |
| 311 | AllocaInst *OriginalAlloca = Roots[I].second; |
| 312 | SlotPtr->takeName(OriginalAlloca); |
| 313 | OriginalAlloca->replaceAllUsesWith(SlotPtr); |
| 314 | } |
| 315 | |
| 316 | // Move past the original stores inserted by GCStrategy::InitRoots. This isn't |
| 317 | // really necessary (the collector would never see the intermediate state at |
| 318 | // runtime), but it's nicer not to push the half-initialized entry onto the |
| 319 | // shadow stack. |
| 320 | while (isa<StoreInst>(IP)) |
| 321 | ++IP; |
| 322 | AtEntry.SetInsertPoint(IP->getParent(), IP); |
| 323 | |
| 324 | // Push the entry onto the shadow stack. |
David Blaikie | 86ecb1b | 2015-03-15 01:03:19 +0000 | [diff] [blame] | 325 | Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy, |
| 326 | StackEntry, 0, 0, "gc_frame.next"); |
| 327 | Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy, |
| 328 | StackEntry, 0, "gc_newhead"); |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 329 | AtEntry.CreateStore(CurrentHead, EntryNextPtr); |
| 330 | AtEntry.CreateStore(NewHeadVal, Head); |
| 331 | |
| 332 | // For each instruction that escapes... |
| 333 | EscapeEnumerator EE(F, "gc_cleanup"); |
| 334 | while (IRBuilder<> *AtExit = EE.Next()) { |
| 335 | // Pop the entry from the shadow stack. Don't reuse CurrentHead from |
| 336 | // AtEntry, since that would make the value live for the entire function. |
| 337 | Instruction *EntryNextPtr2 = |
David Blaikie | 86ecb1b | 2015-03-15 01:03:19 +0000 | [diff] [blame] | 338 | CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0, |
| 339 | "gc_frame.next"); |
Philip Reames | 23cf2e2 | 2015-01-28 19:28:03 +0000 | [diff] [blame] | 340 | Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead"); |
| 341 | AtExit->CreateStore(SavedHead, Head); |
| 342 | } |
| 343 | |
| 344 | // Delete the original allocas (which are no longer used) and the intrinsic |
| 345 | // calls (which are no longer valid). Doing this last avoids invalidating |
| 346 | // iterators. |
| 347 | for (unsigned I = 0, E = Roots.size(); I != E; ++I) { |
| 348 | Roots[I].first->eraseFromParent(); |
| 349 | Roots[I].second->eraseFromParent(); |
| 350 | } |
| 351 | |
| 352 | Roots.clear(); |
| 353 | return true; |
| 354 | } |