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 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/Passes.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/CodeGen/GCStrategy.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/IRBuilder.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/Module.h"
22
23 using namespace llvm;
24
25 #define DEBUG_TYPE "shadowstackgclowering"
26
27 namespace {
28
29 class ShadowStackGCLowering : public FunctionPass {
30 /// RootChain - This is the global linked-list that contains the chain of GC
31 /// roots.
32 GlobalVariable *Head;
33
34 /// StackEntryTy - Abstract type of a link in the shadow stack.
35 ///
36 StructType *StackEntryTy;
37 StructType *FrameMapTy;
38
39 /// Roots - GC roots in the current function. Each is a pair of the
40 /// intrinsic call and its corresponding alloca.
41 std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
42
43 public:
44 static char ID;
45 ShadowStackGCLowering();
46
47 bool doInitialization(Module &M) override;
48 bool runOnFunction(Function &F) override;
49
50 private:
51 bool IsNullValue(Value *V);
52 Constant *GetFrameMap(Function &F);
53 Type *GetConcreteStackEntryType(Function &F);
54 void CollectRoots(Function &F);
55 static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
56 Type *Ty, Value *BasePtr, int Idx1,
57 const char *Name);
58 static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
59 Type *Ty, Value *BasePtr, int Idx1, int Idx2,
60 const char *Name);
61 };
62 }
63
64 INITIALIZE_PASS_BEGIN(ShadowStackGCLowering, "shadow-stack-gc-lowering",
65 "Shadow Stack GC Lowering", false, false)
INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)66 INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
67 INITIALIZE_PASS_END(ShadowStackGCLowering, "shadow-stack-gc-lowering",
68 "Shadow Stack GC Lowering", false, false)
69
70 FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGCLowering(); }
71
72 char ShadowStackGCLowering::ID = 0;
73
ShadowStackGCLowering()74 ShadowStackGCLowering::ShadowStackGCLowering()
75 : FunctionPass(ID), Head(nullptr), StackEntryTy(nullptr),
76 FrameMapTy(nullptr) {
77 initializeShadowStackGCLoweringPass(*PassRegistry::getPassRegistry());
78 }
79
80 namespace {
81 /// EscapeEnumerator - This is a little algorithm to find all escape points
82 /// from a function so that "finally"-style code can be inserted. In addition
83 /// to finding the existing return and unwind instructions, it also (if
84 /// necessary) transforms any call instructions into invokes and sends them to
85 /// a landing pad.
86 ///
87 /// It's wrapped up in a state machine using the same transform C# uses for
88 /// 'yield return' enumerators, This transform allows it to be non-allocating.
89 class EscapeEnumerator {
90 Function &F;
91 const char *CleanupBBName;
92
93 // State.
94 int State;
95 Function::iterator StateBB, StateE;
96 IRBuilder<> Builder;
97
98 public:
EscapeEnumerator(Function & F,const char * N="cleanup")99 EscapeEnumerator(Function &F, const char *N = "cleanup")
100 : F(F), CleanupBBName(N), State(0), Builder(F.getContext()) {}
101
Next()102 IRBuilder<> *Next() {
103 switch (State) {
104 default:
105 return nullptr;
106
107 case 0:
108 StateBB = F.begin();
109 StateE = F.end();
110 State = 1;
111
112 case 1:
113 // Find all 'return', 'resume', and 'unwind' instructions.
114 while (StateBB != StateE) {
115 BasicBlock *CurBB = StateBB++;
116
117 // Branches and invokes do not escape, only unwind, resume, and return
118 // do.
119 TerminatorInst *TI = CurBB->getTerminator();
120 if (!isa<ReturnInst>(TI) && !isa<ResumeInst>(TI))
121 continue;
122
123 Builder.SetInsertPoint(TI->getParent(), TI);
124 return &Builder;
125 }
126
127 State = 2;
128
129 // Find all 'call' instructions.
130 SmallVector<Instruction *, 16> Calls;
131 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
132 for (BasicBlock::iterator II = BB->begin(), EE = BB->end(); II != EE;
133 ++II)
134 if (CallInst *CI = dyn_cast<CallInst>(II))
135 if (!CI->getCalledFunction() ||
136 !CI->getCalledFunction()->getIntrinsicID())
137 Calls.push_back(CI);
138
139 if (Calls.empty())
140 return nullptr;
141
142 // Create a cleanup block.
143 LLVMContext &C = F.getContext();
144 BasicBlock *CleanupBB = BasicBlock::Create(C, CleanupBBName, &F);
145 Type *ExnTy =
146 StructType::get(Type::getInt8PtrTy(C), Type::getInt32Ty(C), nullptr);
147 Constant *PersFn = F.getParent()->getOrInsertFunction(
148 "__gcc_personality_v0", FunctionType::get(Type::getInt32Ty(C), true));
149 LandingPadInst *LPad =
150 LandingPadInst::Create(ExnTy, PersFn, 1, "cleanup.lpad", CleanupBB);
151 LPad->setCleanup(true);
152 ResumeInst *RI = ResumeInst::Create(LPad, CleanupBB);
153
154 // Transform the 'call' instructions into 'invoke's branching to the
155 // cleanup block. Go in reverse order to make prettier BB names.
156 SmallVector<Value *, 16> Args;
157 for (unsigned I = Calls.size(); I != 0;) {
158 CallInst *CI = cast<CallInst>(Calls[--I]);
159
160 // Split the basic block containing the function call.
161 BasicBlock *CallBB = CI->getParent();
162 BasicBlock *NewBB =
163 CallBB->splitBasicBlock(CI, CallBB->getName() + ".cont");
164
165 // Remove the unconditional branch inserted at the end of CallBB.
166 CallBB->getInstList().pop_back();
167 NewBB->getInstList().remove(CI);
168
169 // Create a new invoke instruction.
170 Args.clear();
171 CallSite CS(CI);
172 Args.append(CS.arg_begin(), CS.arg_end());
173
174 InvokeInst *II =
175 InvokeInst::Create(CI->getCalledValue(), NewBB, CleanupBB, Args,
176 CI->getName(), CallBB);
177 II->setCallingConv(CI->getCallingConv());
178 II->setAttributes(CI->getAttributes());
179 CI->replaceAllUsesWith(II);
180 delete CI;
181 }
182
183 Builder.SetInsertPoint(RI->getParent(), RI);
184 return &Builder;
185 }
186 }
187 };
188 }
189
190
GetFrameMap(Function & F)191 Constant *ShadowStackGCLowering::GetFrameMap(Function &F) {
192 // doInitialization creates the abstract type of this value.
193 Type *VoidPtr = Type::getInt8PtrTy(F.getContext());
194
195 // Truncate the ShadowStackDescriptor if some metadata is null.
196 unsigned NumMeta = 0;
197 SmallVector<Constant *, 16> Metadata;
198 for (unsigned I = 0; I != Roots.size(); ++I) {
199 Constant *C = cast<Constant>(Roots[I].first->getArgOperand(1));
200 if (!C->isNullValue())
201 NumMeta = I + 1;
202 Metadata.push_back(ConstantExpr::getBitCast(C, VoidPtr));
203 }
204 Metadata.resize(NumMeta);
205
206 Type *Int32Ty = Type::getInt32Ty(F.getContext());
207
208 Constant *BaseElts[] = {
209 ConstantInt::get(Int32Ty, Roots.size(), false),
210 ConstantInt::get(Int32Ty, NumMeta, false),
211 };
212
213 Constant *DescriptorElts[] = {
214 ConstantStruct::get(FrameMapTy, BaseElts),
215 ConstantArray::get(ArrayType::get(VoidPtr, NumMeta), Metadata)};
216
217 Type *EltTys[] = {DescriptorElts[0]->getType(), DescriptorElts[1]->getType()};
218 StructType *STy = StructType::create(EltTys, "gc_map." + utostr(NumMeta));
219
220 Constant *FrameMap = ConstantStruct::get(STy, DescriptorElts);
221
222 // FIXME: Is this actually dangerous as WritingAnLLVMPass.html claims? Seems
223 // that, short of multithreaded LLVM, it should be safe; all that is
224 // necessary is that a simple Module::iterator loop not be invalidated.
225 // Appending to the GlobalVariable list is safe in that sense.
226 //
227 // All of the output passes emit globals last. The ExecutionEngine
228 // explicitly supports adding globals to the module after
229 // initialization.
230 //
231 // Still, if it isn't deemed acceptable, then this transformation needs
232 // to be a ModulePass (which means it cannot be in the 'llc' pipeline
233 // (which uses a FunctionPassManager (which segfaults (not asserts) if
234 // provided a ModulePass))).
235 Constant *GV = new GlobalVariable(*F.getParent(), FrameMap->getType(), true,
236 GlobalVariable::InternalLinkage, FrameMap,
237 "__gc_" + F.getName());
238
239 Constant *GEPIndices[2] = {
240 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0),
241 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0)};
242 return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices);
243 }
244
GetConcreteStackEntryType(Function & F)245 Type *ShadowStackGCLowering::GetConcreteStackEntryType(Function &F) {
246 // doInitialization creates the generic version of this type.
247 std::vector<Type *> EltTys;
248 EltTys.push_back(StackEntryTy);
249 for (size_t I = 0; I != Roots.size(); I++)
250 EltTys.push_back(Roots[I].second->getAllocatedType());
251
252 return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str());
253 }
254
255 /// doInitialization - If this module uses the GC intrinsics, find them now. If
256 /// not, exit fast.
doInitialization(Module & M)257 bool ShadowStackGCLowering::doInitialization(Module &M) {
258 bool Active = false;
259 for (Function &F : M) {
260 if (F.hasGC() && F.getGC() == std::string("shadow-stack")) {
261 Active = true;
262 break;
263 }
264 }
265 if (!Active)
266 return false;
267
268 // struct FrameMap {
269 // int32_t NumRoots; // Number of roots in stack frame.
270 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
271 // void *Meta[]; // May be absent for roots without metadata.
272 // };
273 std::vector<Type *> EltTys;
274 // 32 bits is ok up to a 32GB stack frame. :)
275 EltTys.push_back(Type::getInt32Ty(M.getContext()));
276 // Specifies length of variable length array.
277 EltTys.push_back(Type::getInt32Ty(M.getContext()));
278 FrameMapTy = StructType::create(EltTys, "gc_map");
279 PointerType *FrameMapPtrTy = PointerType::getUnqual(FrameMapTy);
280
281 // struct StackEntry {
282 // ShadowStackEntry *Next; // Caller's stack entry.
283 // FrameMap *Map; // Pointer to constant FrameMap.
284 // void *Roots[]; // Stack roots (in-place array, so we pretend).
285 // };
286
287 StackEntryTy = StructType::create(M.getContext(), "gc_stackentry");
288
289 EltTys.clear();
290 EltTys.push_back(PointerType::getUnqual(StackEntryTy));
291 EltTys.push_back(FrameMapPtrTy);
292 StackEntryTy->setBody(EltTys);
293 PointerType *StackEntryPtrTy = PointerType::getUnqual(StackEntryTy);
294
295 // Get the root chain if it already exists.
296 Head = M.getGlobalVariable("llvm_gc_root_chain");
297 if (!Head) {
298 // If the root chain does not exist, insert a new one with linkonce
299 // linkage!
300 Head = new GlobalVariable(
301 M, StackEntryPtrTy, false, GlobalValue::LinkOnceAnyLinkage,
302 Constant::getNullValue(StackEntryPtrTy), "llvm_gc_root_chain");
303 } else if (Head->hasExternalLinkage() && Head->isDeclaration()) {
304 Head->setInitializer(Constant::getNullValue(StackEntryPtrTy));
305 Head->setLinkage(GlobalValue::LinkOnceAnyLinkage);
306 }
307
308 return true;
309 }
310
IsNullValue(Value * V)311 bool ShadowStackGCLowering::IsNullValue(Value *V) {
312 if (Constant *C = dyn_cast<Constant>(V))
313 return C->isNullValue();
314 return false;
315 }
316
CollectRoots(Function & F)317 void ShadowStackGCLowering::CollectRoots(Function &F) {
318 // FIXME: Account for original alignment. Could fragment the root array.
319 // Approach 1: Null initialize empty slots at runtime. Yuck.
320 // Approach 2: Emit a map of the array instead of just a count.
321
322 assert(Roots.empty() && "Not cleaned up?");
323
324 SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots;
325
326 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
327 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;)
328 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
329 if (Function *F = CI->getCalledFunction())
330 if (F->getIntrinsicID() == Intrinsic::gcroot) {
331 std::pair<CallInst *, AllocaInst *> Pair = std::make_pair(
332 CI,
333 cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
334 if (IsNullValue(CI->getArgOperand(1)))
335 Roots.push_back(Pair);
336 else
337 MetaRoots.push_back(Pair);
338 }
339
340 // Number roots with metadata (usually empty) at the beginning, so that the
341 // FrameMap::Meta array can be elided.
342 Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
343 }
344
CreateGEP(LLVMContext & Context,IRBuilder<> & B,Type * Ty,Value * BasePtr,int Idx,int Idx2,const char * Name)345 GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
346 IRBuilder<> &B, Type *Ty,
347 Value *BasePtr, int Idx,
348 int Idx2,
349 const char *Name) {
350 Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
351 ConstantInt::get(Type::getInt32Ty(Context), Idx),
352 ConstantInt::get(Type::getInt32Ty(Context), Idx2)};
353 Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
354
355 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
356
357 return dyn_cast<GetElementPtrInst>(Val);
358 }
359
CreateGEP(LLVMContext & Context,IRBuilder<> & B,Type * Ty,Value * BasePtr,int Idx,const char * Name)360 GetElementPtrInst *ShadowStackGCLowering::CreateGEP(LLVMContext &Context,
361 IRBuilder<> &B, Type *Ty, Value *BasePtr,
362 int Idx, const char *Name) {
363 Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
364 ConstantInt::get(Type::getInt32Ty(Context), Idx)};
365 Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
366
367 assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
368
369 return dyn_cast<GetElementPtrInst>(Val);
370 }
371
372 /// runOnFunction - Insert code to maintain the shadow stack.
runOnFunction(Function & F)373 bool ShadowStackGCLowering::runOnFunction(Function &F) {
374 // Quick exit for functions that do not use the shadow stack GC.
375 if (!F.hasGC() ||
376 F.getGC() != std::string("shadow-stack"))
377 return false;
378
379 LLVMContext &Context = F.getContext();
380
381 // Find calls to llvm.gcroot.
382 CollectRoots(F);
383
384 // If there are no roots in this function, then there is no need to add a
385 // stack map entry for it.
386 if (Roots.empty())
387 return false;
388
389 // Build the constant map and figure the type of the shadow stack entry.
390 Value *FrameMap = GetFrameMap(F);
391 Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
392
393 // Build the shadow stack entry at the very start of the function.
394 BasicBlock::iterator IP = F.getEntryBlock().begin();
395 IRBuilder<> AtEntry(IP->getParent(), IP);
396
397 Instruction *StackEntry =
398 AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame");
399
400 while (isa<AllocaInst>(IP))
401 ++IP;
402 AtEntry.SetInsertPoint(IP->getParent(), IP);
403
404 // Initialize the map pointer and load the current head of the shadow stack.
405 Instruction *CurrentHead = AtEntry.CreateLoad(Head, "gc_currhead");
406 Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
407 StackEntry, 0, 1, "gc_frame.map");
408 AtEntry.CreateStore(FrameMap, EntryMapPtr);
409
410 // After all the allocas...
411 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
412 // For each root, find the corresponding slot in the aggregate...
413 Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
414 StackEntry, 1 + I, "gc_root");
415
416 // And use it in lieu of the alloca.
417 AllocaInst *OriginalAlloca = Roots[I].second;
418 SlotPtr->takeName(OriginalAlloca);
419 OriginalAlloca->replaceAllUsesWith(SlotPtr);
420 }
421
422 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
423 // really necessary (the collector would never see the intermediate state at
424 // runtime), but it's nicer not to push the half-initialized entry onto the
425 // shadow stack.
426 while (isa<StoreInst>(IP))
427 ++IP;
428 AtEntry.SetInsertPoint(IP->getParent(), IP);
429
430 // Push the entry onto the shadow stack.
431 Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
432 StackEntry, 0, 0, "gc_frame.next");
433 Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
434 StackEntry, 0, "gc_newhead");
435 AtEntry.CreateStore(CurrentHead, EntryNextPtr);
436 AtEntry.CreateStore(NewHeadVal, Head);
437
438 // For each instruction that escapes...
439 EscapeEnumerator EE(F, "gc_cleanup");
440 while (IRBuilder<> *AtExit = EE.Next()) {
441 // Pop the entry from the shadow stack. Don't reuse CurrentHead from
442 // AtEntry, since that would make the value live for the entire function.
443 Instruction *EntryNextPtr2 =
444 CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0,
445 "gc_frame.next");
446 Value *SavedHead = AtExit->CreateLoad(EntryNextPtr2, "gc_savedhead");
447 AtExit->CreateStore(SavedHead, Head);
448 }
449
450 // Delete the original allocas (which are no longer used) and the intrinsic
451 // calls (which are no longer valid). Doing this last avoids invalidating
452 // iterators.
453 for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
454 Roots[I].first->eraseFromParent();
455 Roots[I].second->eraseFromParent();
456 }
457
458 Roots.clear();
459 return true;
460 }
461