blob: 746addeba44e41d1f4c872cebcf5c39c5f396fdf [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"
Bill Wendlingb2a42982008-11-06 02:29:10 +000023#include "llvm/Intrinsics.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000026#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 // Loop through the basic blocks that have return instructions. Convert this:
101 //
102 // return:
103 // ...
104 // ret ...
105 //
106 // into this:
107 //
108 // return:
109 // ...
110 // %1 = load __stack_chk_guard
111 // %2 = load <stored stack guard>
112 // %3 = cmp i1 %1, %2
Bill Wendlingb2a42982008-11-06 02:29:10 +0000113 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
Bill Wendling2b58ce52008-11-04 02:10:20 +0000114 //
Bill Wendlingb7c2c122008-11-04 22:51:24 +0000115 // SP_return:
Bill Wendling2b58ce52008-11-04 02:10:20 +0000116 // ret ...
117 //
118 // CallStackCheckFailBlk:
119 // call void @__stack_chk_fail()
120 // unreachable
121 //
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000122 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
123 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
124 Constant *StackGuardVar = 0; // The stack guard variable.
125
Bill Wendling72056772008-11-10 21:13:10 +0000126 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
Bill Wendling1fb615f2008-11-06 23:55:49 +0000127 BasicBlock *BB = I;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000128
Bill Wendling72056772008-11-10 21:13:10 +0000129 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000130 if (!FailBB) {
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000131 // Insert code into the entry block that stores the __stack_chk_guard
132 // variable onto the stack.
133 PointerType *PtrTy = PointerType::getUnqual(Type::Int8Ty);
134 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
135
136 BasicBlock &Entry = F->getEntryBlock();
137 Instruction *InsPt = &Entry.front();
138
139 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
140 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
141
142 Value *Args[] = { LI, AI };
143 CallInst::
144 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector_create),
145 &Args[0], array_endof(Args), "", InsPt);
Bill Wendling72056772008-11-10 21:13:10 +0000146
147 // Create the basic block to jump to when the guard check fails.
148 FailBB = CreateFailBB();
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000149 }
Bill Wendling2b58ce52008-11-04 02:10:20 +0000150
Bill Wendling72056772008-11-10 21:13:10 +0000151 ++I; // Skip to the next block so that we don't resplit the return block.
Bill Wendling1fb615f2008-11-06 23:55:49 +0000152
153 // Split the basic block before the return instruction.
154 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
155
Bill Wendling22511ed2008-11-10 23:38:59 +0000156 // Move the newly created basic block to the point right after the old
157 // basic block so that it's in the "fall through" position.
Bill Wendling1fb615f2008-11-06 23:55:49 +0000158 NewBB->removeFromParent();
Bill Wendling22511ed2008-11-10 23:38:59 +0000159 F->getBasicBlockList().insert(I, NewBB);
Bill Wendling1fb615f2008-11-06 23:55:49 +0000160
161 // Generate the stack protector instructions in the old basic block.
162 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
163 CallInst *CI = CallInst::
164 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector_check),
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000165 AI, "", BB);
Bill Wendling1fb615f2008-11-06 23:55:49 +0000166 ICmpInst *Cmp = new ICmpInst(CmpInst::ICMP_EQ, CI, LI1, "", BB);
167 BranchInst::Create(NewBB, FailBB, Cmp, BB);
Bill Wendling72056772008-11-10 21:13:10 +0000168 } else {
169 ++I;
Bill Wendling1fb615f2008-11-06 23:55:49 +0000170 }
Bill Wendling2b58ce52008-11-04 02:10:20 +0000171 }
Bill Wendling613f7742008-11-05 00:00:21 +0000172
Bill Wendling1fb615f2008-11-06 23:55:49 +0000173 // Return if we didn't modify any basic blocks. I.e., there are no return
174 // statements in the function.
175 if (!FailBB) return false;
176
Bill Wendling613f7742008-11-05 00:00:21 +0000177 return true;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000178}
179
180/// CreateFailBB - Create a basic block to jump to when the stack protector
181/// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +0000182BasicBlock *StackProtector::CreateFailBB() {
183 BasicBlock *FailBB = BasicBlock::Create("CallStackCheckFailBlk", F);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000184 Constant *StackChkFail =
Bill Wendling80a320d2008-11-04 21:53:09 +0000185 M->getOrInsertFunction("__stack_chk_fail", Type::VoidTy, NULL);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000186 CallInst::Create(StackChkFail, "", FailBB);
187 new UnreachableInst(FailBB);
Bill Wendling613f7742008-11-05 00:00:21 +0000188 return FailBB;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000189}
190
191/// RequiresStackProtector - Check whether or not this function needs a stack
Bill Wendling89c5cc62008-11-06 02:38:58 +0000192/// protector based upon the stack protector level. The heuristic we use is to
193/// add a guard variable to functions that call alloca, and functions with
194/// buffers larger than 8 bytes.
Bill Wendling80a320d2008-11-04 21:53:09 +0000195bool StackProtector::RequiresStackProtector() const {
Bill Wendling2b58ce52008-11-04 02:10:20 +0000196 switch (Level) {
197 default: return false;
Bill Wendling80a320d2008-11-04 21:53:09 +0000198 case SSP::ALL: return true;
199 case SSP::SOME: {
Bill Wendling80a320d2008-11-04 21:53:09 +0000200 const TargetData *TD = TLI->getTargetData();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000201
202 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
203 BasicBlock *BB = I;
204
205 for (BasicBlock::iterator
206 II = BB->begin(), IE = BB->end(); II != IE; ++II)
Bill Wendling80a320d2008-11-04 21:53:09 +0000207 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000208 if (AI->isArrayAllocation())
209 // This is a call to alloca with a variable size. Emit stack
210 // protectors.
211 return true;
Bill Wendling89c5cc62008-11-06 02:38:58 +0000212
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000213 if (const ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType()))
Bill Wendling703ccfe2008-11-06 22:18:44 +0000214 // If an array has more than 8 bytes of allocated space, then we
215 // emit stack protectors.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000216 if (SSPBufferSize <= TD->getABITypeSize(AT))
Bill Wendling80a320d2008-11-04 21:53:09 +0000217 return true;
Bill Wendling80a320d2008-11-04 21:53:09 +0000218 }
219 }
Bill Wendling2b58ce52008-11-04 02:10:20 +0000220
221 return false;
222 }
223 }
224}