blob: 9043b89e354e8650265295defe23e23d055bddc0 [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"
Bill Wendlinge9e6bdf2008-11-13 01:02:14 +000019#include "llvm/Attributes.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
23#include "llvm/Instructions.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000024#include "llvm/Intrinsics.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000025#include "llvm/Module.h"
26#include "llvm/Pass.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000027#include "llvm/Support/CommandLine.h"
Bill Wendling80a320d2008-11-04 21:53:09 +000028#include "llvm/Target/TargetData.h"
29#include "llvm/Target/TargetLowering.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000030using namespace llvm;
31
Bill Wendlingf0eaa9a2008-11-05 00:46:15 +000032// SSPBufferSize - The lower bound for a buffer to be considered for stack
33// smashing protection.
Bill Wendling2b58ce52008-11-04 02:10:20 +000034static cl::opt<unsigned>
Bill Wendling80a320d2008-11-04 21:53:09 +000035SSPBufferSize("stack-protector-buffer-size", cl::init(8),
Bill Wendlingc3348a72008-11-18 05:32:11 +000036 cl::desc("Lower bound for a buffer to be considered for "
37 "stack protection"));
Bill Wendling2b58ce52008-11-04 02:10:20 +000038
39namespace {
40 class VISIBILITY_HIDDEN StackProtector : public FunctionPass {
Bill Wendling80a320d2008-11-04 21:53:09 +000041 /// TLI - Keep a pointer of a TargetLowering to consult for determining
42 /// target type sizes.
43 const TargetLowering *TLI;
Bill Wendling2b58ce52008-11-04 02:10:20 +000044
Bill Wendling2b58ce52008-11-04 02:10:20 +000045 Function *F;
46 Module *M;
47
Bill Wendling613f7742008-11-05 00:00:21 +000048 /// InsertStackProtectors - Insert code into the prologue and epilogue of
49 /// the function.
50 ///
51 /// - The prologue code loads and stores the stack guard onto the stack.
52 /// - The epilogue checks the value stored in the prologue against the
53 /// original value. It calls __stack_chk_fail if they differ.
54 bool InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +000055
56 /// CreateFailBB - Create a basic block to jump to when the stack protector
57 /// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +000058 BasicBlock *CreateFailBB();
Bill Wendling2b58ce52008-11-04 02:10:20 +000059
60 /// RequiresStackProtector - Check whether or not this function needs a
61 /// stack protector based upon the stack protector level.
Bill Wendling80a320d2008-11-04 21:53:09 +000062 bool RequiresStackProtector() const;
Bill Wendling2b58ce52008-11-04 02:10:20 +000063 public:
64 static char ID; // Pass identification, replacement for typeid.
Bill Wendlinge9e6bdf2008-11-13 01:02:14 +000065 StackProtector() : FunctionPass(&ID), TLI(0) {}
66 StackProtector(const TargetLowering *tli)
67 : FunctionPass(&ID), TLI(tli) {}
Bill Wendling2b58ce52008-11-04 02:10:20 +000068
69 virtual bool runOnFunction(Function &Fn);
70 };
71} // end anonymous namespace
72
73char StackProtector::ID = 0;
74static RegisterPass<StackProtector>
75X("stack-protector", "Insert stack protectors");
76
Bill Wendlinge9e6bdf2008-11-13 01:02:14 +000077FunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {
78 return new StackProtector(tli);
Bill Wendling2b58ce52008-11-04 02:10:20 +000079}
80
81bool StackProtector::runOnFunction(Function &Fn) {
82 F = &Fn;
83 M = F->getParent();
84
85 if (!RequiresStackProtector()) return false;
86
Bill Wendling613f7742008-11-05 00:00:21 +000087 return InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +000088}
89
Bill Wendlingc3348a72008-11-18 05:32:11 +000090/// RequiresStackProtector - Check whether or not this function needs a stack
91/// protector based upon the stack protector level. The heuristic we use is to
92/// add a guard variable to functions that call alloca, and functions with
93/// buffers larger than SSPBufferSize bytes.
94bool StackProtector::RequiresStackProtector() const {
95 if (F->hasFnAttr(Attribute::StackProtectReq))
96 return true;
97
98 if (!F->hasFnAttr(Attribute::StackProtect))
99 return false;
100
101 const TargetData *TD = TLI->getTargetData();
102
103 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
104 BasicBlock *BB = I;
105
106 for (BasicBlock::iterator
107 II = BB->begin(), IE = BB->end(); II != IE; ++II)
108 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
109 if (AI->isArrayAllocation())
110 // This is a call to alloca with a variable size. Emit stack
111 // protectors.
112 return true;
113
114 if (const ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType()))
115 // If an array has more than SSPBufferSize bytes of allocated space,
116 // then we emit stack protectors.
Duncan Sands777d2302009-05-09 07:06:46 +0000117 if (SSPBufferSize <= TD->getTypeAllocSize(AT))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000118 return true;
119 }
120 }
121
122 return false;
123}
124
Bill Wendling613f7742008-11-05 00:00:21 +0000125/// InsertStackProtectors - Insert code into the prologue and epilogue of the
126/// function.
127///
128/// - The prologue code loads and stores the stack guard onto the stack.
129/// - The epilogue checks the value stored in the prologue against the original
130/// value. It calls __stack_chk_fail if they differ.
131bool StackProtector::InsertStackProtectors() {
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000132 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
133 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
134 Constant *StackGuardVar = 0; // The stack guard variable.
135
Bill Wendling72056772008-11-10 21:13:10 +0000136 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000137 BasicBlock *BB = I++;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000138
Bill Wendlingc3348a72008-11-18 05:32:11 +0000139 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
140 if (!RI) continue;
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000141
Bill Wendlingc3348a72008-11-18 05:32:11 +0000142 if (!FailBB) {
143 // Insert code into the entry block that stores the __stack_chk_guard
144 // variable onto the stack:
145 //
146 // entry:
147 // StackGuardSlot = alloca i8*
148 // StackGuard = load __stack_chk_guard
149 // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
150 //
151 PointerType *PtrTy = PointerType::getUnqual(Type::Int8Ty);
152 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000153
Bill Wendlingc3348a72008-11-18 05:32:11 +0000154 BasicBlock &Entry = F->getEntryBlock();
155 Instruction *InsPt = &Entry.front();
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000156
Bill Wendlingc3348a72008-11-18 05:32:11 +0000157 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
158 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
Bill Wendling72056772008-11-10 21:13:10 +0000159
Bill Wendlingc3348a72008-11-18 05:32:11 +0000160 Value *Args[] = { LI, AI };
161 CallInst::
Bill Wendling57344502008-11-18 11:01:33 +0000162 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
Bill Wendlingc3348a72008-11-18 05:32:11 +0000163 &Args[0], array_endof(Args), "", InsPt);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000164
Bill Wendlingc3348a72008-11-18 05:32:11 +0000165 // Create the basic block to jump to when the guard check fails.
166 FailBB = CreateFailBB();
Bill Wendling1fb615f2008-11-06 23:55:49 +0000167 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000168
169 // For each block with a return instruction, convert this:
170 //
171 // return:
172 // ...
173 // ret ...
174 //
175 // into this:
176 //
177 // return:
178 // ...
179 // %1 = load __stack_chk_guard
Bill Wendling733bbc52008-11-18 07:30:57 +0000180 // %2 = load StackGuardSlot
Bill Wendlingc3348a72008-11-18 05:32:11 +0000181 // %3 = cmp i1 %1, %2
182 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
183 //
184 // SP_return:
185 // ret ...
186 //
187 // CallStackCheckFailBlk:
188 // call void @__stack_chk_fail()
189 // unreachable
190
191 // Split the basic block before the return instruction.
192 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
193
Bill Wendling56016992009-03-06 01:41:15 +0000194 // Remove default branch instruction to the new BB.
195 BB->getTerminator()->eraseFromParent();
196
Bill Wendlingc3348a72008-11-18 05:32:11 +0000197 // Move the newly created basic block to the point right after the old basic
198 // block so that it's in the "fall through" position.
199 NewBB->moveAfter(BB);
200
201 // Generate the stack protector instructions in the old basic block.
Bill Wendling733bbc52008-11-18 07:30:57 +0000202 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
203 LoadInst *LI2 = new LoadInst(AI, "", true, BB);
Owen Anderson333c4002009-07-09 23:48:35 +0000204 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
Bill Wendlingc3348a72008-11-18 05:32:11 +0000205 BranchInst::Create(NewBB, FailBB, Cmp, BB);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000206 }
Bill Wendling613f7742008-11-05 00:00:21 +0000207
Bill Wendling1fb615f2008-11-06 23:55:49 +0000208 // Return if we didn't modify any basic blocks. I.e., there are no return
209 // statements in the function.
210 if (!FailBB) return false;
211
Bill Wendling613f7742008-11-05 00:00:21 +0000212 return true;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000213}
214
215/// CreateFailBB - Create a basic block to jump to when the stack protector
216/// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +0000217BasicBlock *StackProtector::CreateFailBB() {
218 BasicBlock *FailBB = BasicBlock::Create("CallStackCheckFailBlk", F);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000219 Constant *StackChkFail =
Bill Wendling80a320d2008-11-04 21:53:09 +0000220 M->getOrInsertFunction("__stack_chk_fail", Type::VoidTy, NULL);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000221 CallInst::Create(StackChkFail, "", FailBB);
222 new UnreachableInst(FailBB);
Bill Wendling613f7742008-11-05 00:00:21 +0000223 return FailBB;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000224}