blob: 631760ad822ce9d87a070b25812b01090d8a1e92 [file] [log] [blame]
Bill Wendling2b58ce52008-11-04 02:10:20 +00001//===-- StackProtector.cpp - Stack Protector Insertion --------------------===//
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//
Bill Wendling80a320d2008-11-04 21:53:09 +000010// 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
Bill Wendling2b58ce52008-11-04 02:10:20 +000013// changed, then there was some sort of violation and the program aborts.
14//
15//===----------------------------------------------------------------------===//
16
17#define DEBUG_TYPE "stack-protector"
18#include "llvm/CodeGen/Passes.h"
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
22#include "llvm/Instructions.h"
23#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/ADT/APInt.h"
26#include "llvm/Support/CommandLine.h"
Bill Wendling80a320d2008-11-04 21:53:09 +000027#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetLowering.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000029using namespace llvm;
30
Bill Wendlingf0eaa9a2008-11-05 00:46:15 +000031// SSPBufferSize - The lower bound for a buffer to be considered for stack
32// smashing protection.
Bill Wendling2b58ce52008-11-04 02:10:20 +000033static cl::opt<unsigned>
Bill Wendling80a320d2008-11-04 21:53:09 +000034SSPBufferSize("stack-protector-buffer-size", cl::init(8),
Bill Wendling2b58ce52008-11-04 02:10:20 +000035 cl::desc("The lower bound for a buffer to be considered for "
36 "stack smashing protection."));
37
38namespace {
39 class VISIBILITY_HIDDEN StackProtector : public FunctionPass {
Bill Wendling80a320d2008-11-04 21:53:09 +000040 /// Level - The level of stack protection.
41 SSP::StackProtectorLevel Level;
42
43 /// TLI - Keep a pointer of a TargetLowering to consult for determining
44 /// target type sizes.
45 const TargetLowering *TLI;
Bill Wendling2b58ce52008-11-04 02:10:20 +000046
Bill Wendling2b58ce52008-11-04 02:10:20 +000047 Function *F;
48 Module *M;
49
Bill Wendling613f7742008-11-05 00:00:21 +000050 /// InsertStackProtectors - Insert code into the prologue and epilogue of
51 /// the function.
52 ///
53 /// - The prologue code loads and stores the stack guard onto the stack.
54 /// - The epilogue checks the value stored in the prologue against the
55 /// original value. It calls __stack_chk_fail if they differ.
56 bool InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +000057
58 /// CreateFailBB - Create a basic block to jump to when the stack protector
59 /// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +000060 BasicBlock *CreateFailBB();
Bill Wendling2b58ce52008-11-04 02:10:20 +000061
62 /// RequiresStackProtector - Check whether or not this function needs a
63 /// stack protector based upon the stack protector level.
Bill Wendling80a320d2008-11-04 21:53:09 +000064 bool RequiresStackProtector() const;
Bill Wendling2b58ce52008-11-04 02:10:20 +000065 public:
66 static char ID; // Pass identification, replacement for typeid.
Bill Wendling613f7742008-11-05 00:00:21 +000067 StackProtector() : FunctionPass(&ID), Level(SSP::OFF), TLI(0) {}
Bill Wendling80a320d2008-11-04 21:53:09 +000068 StackProtector(SSP::StackProtectorLevel lvl, const TargetLowering *tli)
Bill Wendling613f7742008-11-05 00:00:21 +000069 : FunctionPass(&ID), Level(lvl), TLI(tli) {}
Bill Wendling2b58ce52008-11-04 02:10:20 +000070
71 virtual bool runOnFunction(Function &Fn);
72 };
73} // end anonymous namespace
74
75char StackProtector::ID = 0;
76static RegisterPass<StackProtector>
77X("stack-protector", "Insert stack protectors");
78
Bill Wendling80a320d2008-11-04 21:53:09 +000079FunctionPass *llvm::createStackProtectorPass(SSP::StackProtectorLevel lvl,
80 const TargetLowering *tli) {
81 return new StackProtector(lvl, tli);
Bill Wendling2b58ce52008-11-04 02:10:20 +000082}
83
84bool StackProtector::runOnFunction(Function &Fn) {
85 F = &Fn;
86 M = F->getParent();
87
88 if (!RequiresStackProtector()) return false;
89
Bill Wendling613f7742008-11-05 00:00:21 +000090 return InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +000091}
92
Bill Wendling613f7742008-11-05 00:00:21 +000093/// InsertStackProtectors - Insert code into the prologue and epilogue of the
94/// function.
95///
96/// - The prologue code loads and stores the stack guard onto the stack.
97/// - The epilogue checks the value stored in the prologue against the original
98/// value. It calls __stack_chk_fail if they differ.
99bool StackProtector::InsertStackProtectors() {
Bill Wendling2b58ce52008-11-04 02:10:20 +0000100 std::vector<BasicBlock*> ReturnBBs;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000101
Bill Wendling613f7742008-11-05 00:00:21 +0000102 for (Function::iterator I = F->begin(); I != F->end(); ++I)
Bill Wendling80a320d2008-11-04 21:53:09 +0000103 if (isa<ReturnInst>(I->getTerminator()))
Bill Wendling2b58ce52008-11-04 02:10:20 +0000104 ReturnBBs.push_back(I);
105
Bill Wendling613f7742008-11-05 00:00:21 +0000106 // If this function doesn't return, don't bother with stack protectors.
107 if (ReturnBBs.empty()) return false;
108
109 // Insert code into the entry block that stores the __stack_chk_guard variable
110 // onto the stack.
111 BasicBlock &Entry = F->getEntryBlock();
112 Instruction *InsertPt = &Entry.front();
113 const PointerType *GuardTy = PointerType::getUnqual(Type::Int8Ty);
114
115 // The global variable for the stack guard.
116 Constant *StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", GuardTy);
117
118 // The place on the stack that the stack protector guard is kept.
119 AllocaInst *StackProtFrameSlot =
120 new AllocaInst(GuardTy, "StackProt_Frame", InsertPt);
121 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsertPt);
122 new StoreInst(LI, StackProtFrameSlot, false, InsertPt);
123
124 // Create the basic block to jump to when the guard check fails.
125 BasicBlock *FailBB = CreateFailBB();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000126
127 // Loop through the basic blocks that have return instructions. Convert this:
128 //
129 // return:
130 // ...
131 // ret ...
132 //
133 // into this:
134 //
135 // return:
136 // ...
137 // %1 = load __stack_chk_guard
138 // %2 = load <stored stack guard>
139 // %3 = cmp i1 %1, %2
140 // br i1 %3, label %SPRet, label %CallStackCheckFailBlk
141 //
Bill Wendlingb7c2c122008-11-04 22:51:24 +0000142 // SP_return:
Bill Wendling2b58ce52008-11-04 02:10:20 +0000143 // ret ...
144 //
145 // CallStackCheckFailBlk:
146 // call void @__stack_chk_fail()
147 // unreachable
148 //
149 for (std::vector<BasicBlock*>::iterator
Bill Wendling613f7742008-11-05 00:00:21 +0000150 I = ReturnBBs.begin(), E = ReturnBBs.end(); I != E; ++I) {
151 BasicBlock *BB = *I;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000152 ReturnInst *RI = cast<ReturnInst>(BB->getTerminator());
153 Function::iterator InsPt = BB; ++InsPt; // Insertion point for new BB.
154
Bill Wendlingb7c2c122008-11-04 22:51:24 +0000155 // Split the basic block before the return instruction.
156 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
Bill Wendling2b58ce52008-11-04 02:10:20 +0000157
Bill Wendlingb7c2c122008-11-04 22:51:24 +0000158 // Move the newly created basic block to the point right after the old basic
Bill Wendling613f7742008-11-05 00:00:21 +0000159 // block so that it's in the "fall through" position.
Bill Wendlingb7c2c122008-11-04 22:51:24 +0000160 NewBB->removeFromParent();
161 F->getBasicBlockList().insert(InsPt, NewBB);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000162
Bill Wendlingb7c2c122008-11-04 22:51:24 +0000163 // Generate the stack protector instructions in the old basic block.
Bill Wendling2b58ce52008-11-04 02:10:20 +0000164 LoadInst *LI2 = new LoadInst(StackGuardVar, "", false, BB);
165 LoadInst *LI1 = new LoadInst(StackProtFrameSlot, "", true, BB);
166 ICmpInst *Cmp = new ICmpInst(CmpInst::ICMP_EQ, LI1, LI2, "", BB);
167 BranchInst::Create(NewBB, FailBB, Cmp, BB);
168 }
Bill Wendling613f7742008-11-05 00:00:21 +0000169
170 return true;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000171}
172
173/// CreateFailBB - Create a basic block to jump to when the stack protector
174/// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +0000175BasicBlock *StackProtector::CreateFailBB() {
176 BasicBlock *FailBB = BasicBlock::Create("CallStackCheckFailBlk", F);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000177 std::vector<const Type*> Params;
178 Constant *StackChkFail =
Bill Wendling80a320d2008-11-04 21:53:09 +0000179 M->getOrInsertFunction("__stack_chk_fail", Type::VoidTy, NULL);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000180 CallInst::Create(StackChkFail, "", FailBB);
181 new UnreachableInst(FailBB);
Bill Wendling613f7742008-11-05 00:00:21 +0000182 return FailBB;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000183}
184
185/// RequiresStackProtector - Check whether or not this function needs a stack
186/// protector based upon the stack protector level.
Bill Wendling80a320d2008-11-04 21:53:09 +0000187bool StackProtector::RequiresStackProtector() const {
Bill Wendling2b58ce52008-11-04 02:10:20 +0000188 switch (Level) {
189 default: return false;
Bill Wendling80a320d2008-11-04 21:53:09 +0000190 case SSP::ALL: return true;
191 case SSP::SOME: {
Bill Wendling2b58ce52008-11-04 02:10:20 +0000192 // If the size of the local variables allocated on the stack is greater than
193 // SSPBufferSize, then we require a stack protector.
194 uint64_t StackSize = 0;
Bill Wendling80a320d2008-11-04 21:53:09 +0000195 const TargetData *TD = TLI->getTargetData();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000196
197 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
198 BasicBlock *BB = I;
199
200 for (BasicBlock::iterator
201 II = BB->begin(), IE = BB->end(); II != IE; ++II)
Bill Wendling80a320d2008-11-04 21:53:09 +0000202 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
Bill Wendling2b58ce52008-11-04 02:10:20 +0000203 if (ConstantInt *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Bill Wendlingfa75dc62008-11-05 00:54:27 +0000204 const Type *Ty = AI->getAllocatedType();
205 uint64_t TySize = TD->getABITypeSize(Ty);
206 StackSize += TySize * CI->getZExtValue(); // Total allocated size.
Bill Wendling2b58ce52008-11-04 02:10:20 +0000207
Bill Wendling80a320d2008-11-04 21:53:09 +0000208 if (SSPBufferSize <= StackSize)
209 return true;
210 }
211 }
212 }
Bill Wendling2b58ce52008-11-04 02:10:20 +0000213
214 return false;
215 }
216 }
217}