1 //===-- StackProtector.cpp - Stack Protector Insertion --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass inserts stack protectors into functions which need them. A variable
11 // with a random value in it is stored onto the stack before the local variables
12 // are allocated. Upon exiting the block, the stored value is checked. If it's
13 // changed, then there was some sort of violation and the program aborts.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "stack-protector"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Attributes.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Module.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
33 // SSPBufferSize - The lower bound for a buffer to be considered for stack
34 // smashing protection.
35 static cl::opt<unsigned>
36 SSPBufferSize("stack-protector-buffer-size", cl::init(8),
37 cl::desc("Lower bound for a buffer to be considered for "
41 class StackProtector : public FunctionPass {
42 /// TLI - Keep a pointer of a TargetLowering to consult for determining
43 /// target type sizes.
44 const TargetLowering *TLI;
51 /// InsertStackProtectors - Insert code into the prologue and epilogue of
54 /// - The prologue code loads and stores the stack guard onto the stack.
55 /// - The epilogue checks the value stored in the prologue against the
56 /// original value. It calls __stack_chk_fail if they differ.
57 bool InsertStackProtectors();
59 /// CreateFailBB - Create a basic block to jump to when the stack protector
61 BasicBlock *CreateFailBB();
63 /// RequiresStackProtector - Check whether or not this function needs a
64 /// stack protector based upon the stack protector level.
65 bool RequiresStackProtector() const;
67 static char ID; // Pass identification, replacement for typeid.
68 StackProtector() : FunctionPass(ID), TLI(0) {
69 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
71 StackProtector(const TargetLowering *tli)
72 : FunctionPass(ID), TLI(tli) {
73 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.addPreserved<DominatorTree>();
80 virtual bool runOnFunction(Function &Fn);
82 } // end anonymous namespace
84 char StackProtector::ID = 0;
85 INITIALIZE_PASS(StackProtector, "stack-protector",
86 "Insert stack protectors", false, false)
88 FunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {
89 return new StackProtector(tli);
92 bool StackProtector::runOnFunction(Function &Fn) {
95 DT = getAnalysisIfAvailable<DominatorTree>();
97 if (!RequiresStackProtector()) return false;
99 return InsertStackProtectors();
102 /// RequiresStackProtector - Check whether or not this function needs a stack
103 /// protector based upon the stack protector level. The heuristic we use is to
104 /// add a guard variable to functions that call alloca, and functions with
105 /// buffers larger than SSPBufferSize bytes.
106 bool StackProtector::RequiresStackProtector() const {
107 if (F->hasFnAttr(Attribute::StackProtectReq))
110 if (!F->hasFnAttr(Attribute::StackProtect))
113 const TargetData *TD = TLI->getTargetData();
115 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
118 for (BasicBlock::iterator
119 II = BB->begin(), IE = BB->end(); II != IE; ++II)
120 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
121 if (AI->isArrayAllocation())
122 // This is a call to alloca with a variable size. Emit stack
126 if (ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType()))
127 // If an array has more than SSPBufferSize bytes of allocated space,
128 // then we emit stack protectors.
129 if (SSPBufferSize <= TD->getTypeAllocSize(AT))
137 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
140 /// - The prologue code loads and stores the stack guard onto the stack.
141 /// - The epilogue checks the value stored in the prologue against the original
142 /// value. It calls __stack_chk_fail if they differ.
143 bool StackProtector::InsertStackProtectors() {
144 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
145 BasicBlock *FailBBDom = 0; // FailBB's dominator.
146 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
147 Value *StackGuardVar = 0; // The stack guard variable.
149 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
150 BasicBlock *BB = I++;
151 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
155 // Insert code into the entry block that stores the __stack_chk_guard
156 // variable onto the stack:
159 // StackGuardSlot = alloca i8*
160 // StackGuard = load __stack_chk_guard
161 // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
163 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
164 unsigned AddressSpace, Offset;
165 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
166 Constant *OffsetVal =
167 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
169 StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
170 PointerType::get(PtrTy, AddressSpace));
172 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
175 BasicBlock &Entry = F->getEntryBlock();
176 Instruction *InsPt = &Entry.front();
178 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
179 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
181 Value *Args[] = { LI, AI };
183 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
186 // Create the basic block to jump to when the guard check fails.
187 FailBB = CreateFailBB();
190 // For each block with a return instruction, convert this:
200 // %1 = load __stack_chk_guard
201 // %2 = load StackGuardSlot
202 // %3 = cmp i1 %1, %2
203 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
208 // CallStackCheckFailBlk:
209 // call void @__stack_chk_fail()
212 // Split the basic block before the return instruction.
213 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
215 if (DT && DT->isReachableFromEntry(BB)) {
216 DT->addNewBlock(NewBB, BB);
217 FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;
220 // Remove default branch instruction to the new BB.
221 BB->getTerminator()->eraseFromParent();
223 // Move the newly created basic block to the point right after the old basic
224 // block so that it's in the "fall through" position.
225 NewBB->moveAfter(BB);
227 // Generate the stack protector instructions in the old basic block.
228 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
229 LoadInst *LI2 = new LoadInst(AI, "", true, BB);
230 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
231 BranchInst::Create(NewBB, FailBB, Cmp, BB);
234 // Return if we didn't modify any basic blocks. I.e., there are no return
235 // statements in the function.
236 if (!FailBB) return false;
239 DT->addNewBlock(FailBB, FailBBDom);
244 /// CreateFailBB - Create a basic block to jump to when the stack protector
246 BasicBlock *StackProtector::CreateFailBB() {
247 BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
248 "CallStackCheckFailBlk", F);
249 Constant *StackChkFail =
250 M->getOrInsertFunction("__stack_chk_fail",
251 Type::getVoidTy(F->getContext()), NULL);
252 CallInst::Create(StackChkFail, "", FailBB);
253 new UnreachableInst(F->getContext(), FailBB);