LCOV - code coverage report
Current view: top level - lib/CodeGen - ShadowStackGCLowering.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 124 129 96.1 %
Date: 2017-09-14 15:23:50 Functions: 13 13 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       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             : // This pass implements the code transformation described in this paper:
      14             : //   "Accurate Garbage Collection in an Uncooperative Environment"
      15             : //   Fergus Henderson, ISMM, 2002
      16             : //
      17             : //===----------------------------------------------------------------------===//
      18             : 
      19             : #include "llvm/ADT/StringExtras.h"
      20             : #include "llvm/CodeGen/GCStrategy.h"
      21             : #include "llvm/CodeGen/Passes.h"
      22             : #include "llvm/IR/CallSite.h"
      23             : #include "llvm/IR/IRBuilder.h"
      24             : #include "llvm/IR/IntrinsicInst.h"
      25             : #include "llvm/IR/Module.h"
      26             : #include "llvm/Transforms/Utils/EscapeEnumerator.h"
      27             : 
      28             : using namespace llvm;
      29             : 
      30             : #define DEBUG_TYPE "shadow-stack-gc-lowering"
      31             : 
      32             : namespace {
      33             : 
      34       67280 : 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,
      61             :                                       Type *Ty, Value *BasePtr, int Idx1,
      62             :                                       const char *Name);
      63             :   static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
      64             :                                       Type *Ty, Value *BasePtr, int Idx1, int Idx2,
      65             :                                       const char *Name);
      66             : };
      67             : }
      68             : 
      69       16748 : INITIALIZE_PASS_BEGIN(ShadowStackGCLowering, DEBUG_TYPE,
      70             :                       "Shadow Stack GC Lowering", false, false)
      71       16748 : INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
      72       84264 : INITIALIZE_PASS_END(ShadowStackGCLowering, DEBUG_TYPE,
      73             :                     "Shadow Stack GC Lowering", false, false)
      74             : 
      75       16923 : FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); }
      76             : 
      77             : char ShadowStackGCLowering::ID = 0;
      78             : 
      79       16923 : ShadowStackGCLowering::ShadowStackGCLowering()
      80             :   : FunctionPass(ID), Head(nullptr), StackEntryTy(nullptr),
      81       50769 :     FrameMapTy(nullptr) {
      82       16923 :   initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry());
      83       16922 : }
      84             : 
      85           2 : Constant *ShadowStackGCLowering::GetFrameMap(Function &F) {
      86             :   // doInitialization creates the abstract type of this value.
      87           2 :   Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
      88             : 
      89             :   // Truncate the ShadowStackDescriptor if some metadata is null.
      90           2 :   unsigned NumMeta = 0;
      91           4 :   SmallVector<Constant *, 16> Metadata;
      92          10 :   for (unsigned I = 0; I != Roots.size(); ++I) {
      93          12 :     Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
      94           3 :     if (!C->isNullValue())
      95           0 :       NumMeta = I + 1;
      96           3 :     Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
      97             :   }
      98           2 :   Metadata.resize(NumMeta);
      99             : 
     100           2 :   Type *Int32Ty = Type::getInt32Ty(F.getContext());
     101             : 
     102             :   Constant *BaseElts[] = {
     103           4 :       ConstantInt::get(Int32Ty, Roots.size(), false),
     104           2 :       ConstantInt::get(Int32Ty, NumMeta, false),
     105           4 :   };
     106             : 
     107             :   Constant *DescriptorElts[] = {
     108           4 :       ConstantStruct::get(FrameMapTy, BaseElts),
     109           4 :       ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)};
     110             : 
     111           2 :   Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()};
     112          10 :   StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta));
     113             : 
     114           2 :   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           2 :   Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
     130             :                                     GlobalVariable::InternalLinkage, FrameMap,
     131           6 :                                     "__gc_" + F.getName());
     132             : 
     133             :   Constant *GEPIndices[2] = {
     134           2 :       ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
     135           2 :       ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)};
     136           8 :   return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices);
     137             : }
     138             : 
     139           2 : Type *ShadowStackGCLowering::GetConcreteStackEntryType(Function &F) {
     140             :   // doInitialization creates the generic version of this type.
     141           4 :   std::vector<Type *> EltTys;
     142           4 :   EltTys.push_back(StackEntryTy);
     143          10 :   for (size_t I = 0; I != Roots.size(); I++)
     144           9 :     EltTys.push_back(Roots[I].second->getAllocatedType());
     145             : 
     146          12 :   return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str());
     147             : }
     148             : 
     149             : /// doInitialization - If this module uses the GC intrinsics, find them now. If
     150             : /// not, exit fast.
     151       16890 : bool ShadowStackGCLowering::doInitialization(Module &M) {
     152       16890 :   bool Active = false;
     153      230180 :   for (Function &F : M) {
     154      538595 :     if (F.hasGC() && F.getGC() == std::string("shadow-stack")) {
     155             :       Active = true;
     156             :       break;
     157             :     }
     158             :   }
     159       16890 :   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           2 :   std::vector<Type *> EltTys;
     168             :   // 32 bits is ok up to a 32GB stack frame. :)
     169           4 :   EltTys.push_back(Type::getInt32Ty(M.getContext()));
     170             :   // Specifies length of variable length array.
     171           4 :   EltTys.push_back(Type::getInt32Ty(M.getContext()));
     172           4 :   FrameMapTy = StructType::create(EltTys, "gc_map");
     173           4 :   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           2 :   StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
     182             : 
     183           2 :   EltTys.clear();
     184           6 :   EltTys.push_back(PointerType::getUnqual(StackEntryTy));
     185           4 :   EltTys.push_back(FrameMapPtrTy);
     186           4 :   StackEntryTy->setBody(EltTys);
     187           4 :   PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
     188             : 
     189             :   // Get the root chain if it already exists.
     190           4 :   Head = M.getGlobalVariable("llvm_gc_root_chain");
     191           2 :   if (!Head) {
     192             :     // If the root chain does not exist, insert a new one with linkonce
     193             :     // linkage!
     194           4 :     Head = new GlobalVariable(
     195             :         M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage,
     196           4 :         Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain");
     197           0 :   } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
     198           0 :     Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
     199           0 :     Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
     200             :   }
     201             : 
     202           2 :   return true;
     203             : }
     204             : 
     205             : bool ShadowStackGCLowering::IsNullValue(Value *V) {
     206           3 :   if (Constant *C = dyn_cast<Constant>(V))
     207           3 :     return C->isNullValue();
     208             :   return false;
     209             : }
     210             : 
     211           2 : 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           4 :   SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots;
     219             : 
     220           4 :   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
     221          16 :     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
     222          57 :       if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
     223           6 :         if (Function *F = CI->getCalledFunction())
     224           3 :           if (F->getIntrinsicID() == Intrinsic::gcroot) {
     225           6 :             std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
     226             :                 CI,
     227          15 :                 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
     228           9 :             if (IsNullValue(CI->getArgOperand(1)))
     229           3 :               Roots.push_back(Pair);
     230             :             else
     231           0 :               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          12 :   Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
     237           2 : }
     238             : 
     239           6 : GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
     240             :                                                     IRBuilder<> &B, Type *Ty,
     241             :                                                     Value *BasePtr, int Idx,
     242             :                                                     int Idx2,
     243             :                                                     const char *Name) {
     244           6 :   Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
     245           6 :                       ConstantInt::get(Type::getInt32Ty(Context), Idx),
     246          12 :                       ConstantInt::get(Type::getInt32Ty(Context), Idx2)};
     247          12 :   Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
     248             : 
     249             :   assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
     250             : 
     251           6 :   return dyn_cast<GetElementPtrInst>(Val);
     252             : }
     253             : 
     254           5 : GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
     255             :                                             IRBuilder<> &B, Type *Ty, Value *BasePtr,
     256             :                                             int Idx, const char *Name) {
     257           5 :   Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
     258           5 :                       ConstantInt::get(Type::getInt32Ty(Context), Idx)};
     259          10 :   Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
     260             : 
     261             :   assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
     262             : 
     263           5 :   return dyn_cast<GetElementPtrInst>(Val);
     264             : }
     265             : 
     266             : /// runOnFunction - Insert code to maintain the shadow stack.
     267      143176 : bool ShadowStackGCLowering::runOnFunction(Function &F) {
     268             :   // Quick exit for functions that do not use the shadow stack GC.
     269      429593 :   if (!F.hasGC() ||
     270      286547 :       F.getGC() != std::string("shadow-stack"))
     271             :     return false;
     272             :   
     273           2 :   LLVMContext &Context = F.getContext();
     274             : 
     275             :   // Find calls to llvm.gcroot.
     276           2 :   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           4 :   if (Roots.empty())
     281             :     return false;
     282             : 
     283             :   // Build the constant map and figure the type of the shadow stack entry.
     284           2 :   Value *FrameMap = GetFrameMap(F);
     285           2 :   Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
     286             : 
     287             :   // Build the shadow stack entry at the very start of the function.
     288           4 :   BasicBlock::iterator IP = F.getEntryBlock().begin();
     289           4 :   IRBuilder<> AtEntry(IP->getParent(), IP);
     290             : 
     291             :   Instruction *StackEntry =
     292           2 :       AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame");
     293             : 
     294           4 :   while (isa<AllocaInst>(IP))
     295             :     ++IP;
     296           2 :   AtEntry.SetInsertPoint(IP->getParent(), IP);
     297             : 
     298             :   // Initialize the map pointer and load the current head of the shadow stack.
     299           2 :   Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
     300             :   Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
     301           2 :                                        StackEntry, 0, 1, "gc_frame.map");
     302           2 :   AtEntry.CreateStore(FrameMap, EntryMapPtr);
     303             : 
     304             :   // After all the allocas...
     305           7 :   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
     306             :     // For each root, find the corresponding slot in the aggregate...
     307           3 :     Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
     308           6 :                                StackEntry, 1 + I, "gc_root");
     309             : 
     310             :     // And use it in lieu of the alloca.
     311           6 :     AllocaInst *OriginalAlloca = Roots[I].second;
     312           3 :     SlotPtr->takeName(OriginalAlloca);
     313           3 :     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           4 :   while (isa<StoreInst>(IP))
     321             :     ++IP;
     322           2 :   AtEntry.SetInsertPoint(IP->getParent(), IP);
     323             : 
     324             :   // Push the entry onto the shadow stack.
     325             :   Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
     326           2 :                                         StackEntry, 0, 0, "gc_frame.next");
     327             :   Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
     328           2 :                                       StackEntry, 0, "gc_newhead");
     329           2 :   AtEntry.CreateStore(CurrentHead, EntryNextPtr);
     330           2 :   AtEntry.CreateStore(NewHeadVal, Head);
     331             : 
     332             :   // For each instruction that escapes...
     333           2 :   EscapeEnumerator EE(F, "gc_cleanup");
     334           4 :   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 =
     338             :         CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0,
     339           2 :                   "gc_frame.next");
     340           2 :     Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
     341           2 :     AtExit->CreateStore(SavedHead, Head);
     342           2 :   }
     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           7 :   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
     348           6 :     Roots[I].first->eraseFromParent();
     349           6 :     Roots[I].second->eraseFromParent();
     350             :   }
     351             : 
     352           4 :   Roots.clear();
     353           2 :   return true;
     354             : }

Generated by: LCOV version 1.13