ShadowStackGCLowering.cpp 15 KB

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