ShadowStackGCLowering.cpp 14 KB

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