blob: fcaee4208ba3255fe6b36ccdcfea8fa0820521f5 [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"
Cameron Zwarich80f6a502011-01-08 17:01:52 +000019#include "llvm/Analysis/Dominators.h"
Bill Wendlinge9e6bdf2008-11-13 01:02:14 +000020#include "llvm/Attributes.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000021#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Function.h"
24#include "llvm/Instructions.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000025#include "llvm/Intrinsics.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000026#include "llvm/Module.h"
27#include "llvm/Pass.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000028#include "llvm/Support/CommandLine.h"
Bill Wendling80a320d2008-11-04 21:53:09 +000029#include "llvm/Target/TargetData.h"
30#include "llvm/Target/TargetLowering.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000031using namespace llvm;
32
Bill Wendlingf0eaa9a2008-11-05 00:46:15 +000033// SSPBufferSize - The lower bound for a buffer to be considered for stack
34// smashing protection.
Bill Wendling2b58ce52008-11-04 02:10:20 +000035static cl::opt<unsigned>
Bill Wendling80a320d2008-11-04 21:53:09 +000036SSPBufferSize("stack-protector-buffer-size", cl::init(8),
Bill Wendlingc3348a72008-11-18 05:32:11 +000037 cl::desc("Lower bound for a buffer to be considered for "
38 "stack protection"));
Bill Wendling2b58ce52008-11-04 02:10:20 +000039
40namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000041 class StackProtector : public FunctionPass {
Bill Wendling80a320d2008-11-04 21:53:09 +000042 /// TLI - Keep a pointer of a TargetLowering to consult for determining
43 /// target type sizes.
44 const TargetLowering *TLI;
Bill Wendling2b58ce52008-11-04 02:10:20 +000045
Bill Wendling2b58ce52008-11-04 02:10:20 +000046 Function *F;
47 Module *M;
48
Cameron Zwarich80f6a502011-01-08 17:01:52 +000049 DominatorTree* DT;
50
Bill Wendling613f7742008-11-05 00:00:21 +000051 /// InsertStackProtectors - Insert code into the prologue and epilogue of
52 /// the function.
53 ///
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();
Bill Wendling2b58ce52008-11-04 02:10:20 +000058
59 /// CreateFailBB - Create a basic block to jump to when the stack protector
60 /// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +000061 BasicBlock *CreateFailBB();
Bill Wendling2b58ce52008-11-04 02:10:20 +000062
63 /// RequiresStackProtector - Check whether or not this function needs a
64 /// stack protector based upon the stack protector level.
Bill Wendling80a320d2008-11-04 21:53:09 +000065 bool RequiresStackProtector() const;
Bill Wendling2b58ce52008-11-04 02:10:20 +000066 public:
67 static char ID; // Pass identification, replacement for typeid.
Owen Anderson081c34b2010-10-19 17:21:58 +000068 StackProtector() : FunctionPass(ID), TLI(0) {
69 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
70 }
Bill Wendlinge9e6bdf2008-11-13 01:02:14 +000071 StackProtector(const TargetLowering *tli)
Owen Anderson081c34b2010-10-19 17:21:58 +000072 : FunctionPass(ID), TLI(tli) {
73 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
74 }
Bill Wendling2b58ce52008-11-04 02:10:20 +000075
Cameron Zwarich80f6a502011-01-08 17:01:52 +000076 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.addPreserved<DominatorTree>();
78 }
79
Bill Wendling2b58ce52008-11-04 02:10:20 +000080 virtual bool runOnFunction(Function &Fn);
81 };
82} // end anonymous namespace
83
84char StackProtector::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000085INITIALIZE_PASS(StackProtector, "stack-protector",
Owen Andersonce665bd2010-10-07 22:25:06 +000086 "Insert stack protectors", false, false)
Bill Wendling2b58ce52008-11-04 02:10:20 +000087
Bill Wendlinge9e6bdf2008-11-13 01:02:14 +000088FunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {
89 return new StackProtector(tli);
Bill Wendling2b58ce52008-11-04 02:10:20 +000090}
91
92bool StackProtector::runOnFunction(Function &Fn) {
93 F = &Fn;
94 M = F->getParent();
Cameron Zwarich80f6a502011-01-08 17:01:52 +000095 DT = getAnalysisIfAvailable<DominatorTree>();
Bill Wendling2b58ce52008-11-04 02:10:20 +000096
97 if (!RequiresStackProtector()) return false;
98
Bill Wendling613f7742008-11-05 00:00:21 +000099 return InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000100}
101
Bill Wendlingc3348a72008-11-18 05:32:11 +0000102/// 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.
106bool StackProtector::RequiresStackProtector() const {
107 if (F->hasFnAttr(Attribute::StackProtectReq))
108 return true;
109
110 if (!F->hasFnAttr(Attribute::StackProtect))
111 return false;
112
113 const TargetData *TD = TLI->getTargetData();
114
115 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
116 BasicBlock *BB = I;
117
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
123 // protectors.
124 return true;
125
Bill Wendlingdfd85c12009-10-23 00:01:05 +0000126 if (const ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType())) {
127 // We apparently only care about character arrays.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000128 if (!AT->getElementType()->isIntegerTy(8))
Bill Wendlingdfd85c12009-10-23 00:01:05 +0000129 continue;
130
Bill Wendlingc3348a72008-11-18 05:32:11 +0000131 // If an array has more than SSPBufferSize bytes of allocated space,
132 // then we emit stack protectors.
Duncan Sands777d2302009-05-09 07:06:46 +0000133 if (SSPBufferSize <= TD->getTypeAllocSize(AT))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000134 return true;
Bill Wendlingdfd85c12009-10-23 00:01:05 +0000135 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000136 }
137 }
138
139 return false;
140}
141
Bill Wendling613f7742008-11-05 00:00:21 +0000142/// InsertStackProtectors - Insert code into the prologue and epilogue of the
143/// function.
144///
145/// - The prologue code loads and stores the stack guard onto the stack.
146/// - The epilogue checks the value stored in the prologue against the original
147/// value. It calls __stack_chk_fail if they differ.
148bool StackProtector::InsertStackProtectors() {
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000149 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000150 BasicBlock *FailBBDom = 0; // FailBB's dominator.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000151 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000152 Value *StackGuardVar = 0; // The stack guard variable.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000153
Bill Wendling72056772008-11-10 21:13:10 +0000154 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000155 BasicBlock *BB = I++;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000156
Bill Wendlingc3348a72008-11-18 05:32:11 +0000157 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
158 if (!RI) continue;
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000159
Bill Wendlingc3348a72008-11-18 05:32:11 +0000160 if (!FailBB) {
161 // Insert code into the entry block that stores the __stack_chk_guard
162 // variable onto the stack:
163 //
164 // entry:
165 // StackGuardSlot = alloca i8*
166 // StackGuard = load __stack_chk_guard
167 // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
168 //
Chris Lattnerf8bd3922010-07-06 15:59:27 +0000169 const PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000170 unsigned AddressSpace, Offset;
171 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
Chris Lattnerf8bd3922010-07-06 15:59:27 +0000172 Constant *OffsetVal =
173 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
174
175 StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
176 PointerType::get(PtrTy, AddressSpace));
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000177 } else {
Chris Lattnerf8bd3922010-07-06 15:59:27 +0000178 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000179 }
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000180
Bill Wendlingc3348a72008-11-18 05:32:11 +0000181 BasicBlock &Entry = F->getEntryBlock();
182 Instruction *InsPt = &Entry.front();
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000183
Owen Anderson50dead02009-07-15 23:53:25 +0000184 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
Bill Wendlingc3348a72008-11-18 05:32:11 +0000185 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
Bill Wendling72056772008-11-10 21:13:10 +0000186
Bill Wendlingc3348a72008-11-18 05:32:11 +0000187 Value *Args[] = { LI, AI };
188 CallInst::
Bill Wendling57344502008-11-18 11:01:33 +0000189 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
Bill Wendlingc3348a72008-11-18 05:32:11 +0000190 &Args[0], array_endof(Args), "", InsPt);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000191
Bill Wendlingc3348a72008-11-18 05:32:11 +0000192 // Create the basic block to jump to when the guard check fails.
193 FailBB = CreateFailBB();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000194 if (DT)
195 FailBBDom = DT->isReachableFromEntry(BB) ? BB : 0;
Bill Wendling1fb615f2008-11-06 23:55:49 +0000196 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000197
198 // For each block with a return instruction, convert this:
199 //
200 // return:
201 // ...
202 // ret ...
203 //
204 // into this:
205 //
206 // return:
207 // ...
208 // %1 = load __stack_chk_guard
Bill Wendling733bbc52008-11-18 07:30:57 +0000209 // %2 = load StackGuardSlot
Bill Wendlingc3348a72008-11-18 05:32:11 +0000210 // %3 = cmp i1 %1, %2
211 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
212 //
213 // SP_return:
214 // ret ...
215 //
216 // CallStackCheckFailBlk:
217 // call void @__stack_chk_fail()
218 // unreachable
219
220 // Split the basic block before the return instruction.
221 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000222 if (DT) {
223 DT->addNewBlock(NewBB, DT->isReachableFromEntry(BB) ? BB : 0);
224 FailBBDom = DT->findNearestCommonDominator(FailBBDom, BB);
225 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000226
Bill Wendling56016992009-03-06 01:41:15 +0000227 // Remove default branch instruction to the new BB.
228 BB->getTerminator()->eraseFromParent();
229
Bill Wendlingc3348a72008-11-18 05:32:11 +0000230 // Move the newly created basic block to the point right after the old basic
231 // block so that it's in the "fall through" position.
232 NewBB->moveAfter(BB);
233
234 // Generate the stack protector instructions in the old basic block.
Bill Wendling733bbc52008-11-18 07:30:57 +0000235 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
236 LoadInst *LI2 = new LoadInst(AI, "", true, BB);
Owen Anderson333c4002009-07-09 23:48:35 +0000237 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
Bill Wendlingc3348a72008-11-18 05:32:11 +0000238 BranchInst::Create(NewBB, FailBB, Cmp, BB);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000239 }
Bill Wendling613f7742008-11-05 00:00:21 +0000240
Bill Wendling1fb615f2008-11-06 23:55:49 +0000241 // Return if we didn't modify any basic blocks. I.e., there are no return
242 // statements in the function.
243 if (!FailBB) return false;
244
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000245 if (DT)
246 DT->addNewBlock(FailBB, FailBBDom);
247
Bill Wendling613f7742008-11-05 00:00:21 +0000248 return true;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000249}
250
251/// CreateFailBB - Create a basic block to jump to when the stack protector
252/// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +0000253BasicBlock *StackProtector::CreateFailBB() {
Owen Anderson1d0be152009-08-13 21:58:54 +0000254 BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
255 "CallStackCheckFailBlk", F);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000256 Constant *StackChkFail =
Owen Anderson1d0be152009-08-13 21:58:54 +0000257 M->getOrInsertFunction("__stack_chk_fail",
258 Type::getVoidTy(F->getContext()), NULL);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000259 CallInst::Create(StackChkFail, "", FailBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000260 new UnreachableInst(F->getContext(), FailBB);
Bill Wendling613f7742008-11-05 00:00:21 +0000261 return FailBB;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000262}