Coverage Report

Created: 2019-07-24 05:18

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