blob: 9f51778da756241d7e43b761edfa97de37fee038 [file] [log] [blame]
Bill Wendlingdac9f712008-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 Wendling30ef3e32008-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 Wendlingdac9f712008-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 Wendling3e13ce52008-11-13 01:02:14 +000019#include "llvm/Attributes.h"
Bill Wendlingdac9f712008-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 Wendling6d54ef92008-11-06 02:29:10 +000024#include "llvm/Intrinsics.h"
Bill Wendlingdac9f712008-11-04 02:10:20 +000025#include "llvm/Module.h"
26#include "llvm/Pass.h"
Bill Wendlingdac9f712008-11-04 02:10:20 +000027#include "llvm/Support/CommandLine.h"
Bill Wendling30ef3e32008-11-04 21:53:09 +000028#include "llvm/Target/TargetData.h"
29#include "llvm/Target/TargetLowering.h"
Bill Wendlingdac9f712008-11-04 02:10:20 +000030using namespace llvm;
31
Bill Wendling71b251c2008-11-05 00:46:15 +000032// SSPBufferSize - The lower bound for a buffer to be considered for stack
33// smashing protection.
Bill Wendlingdac9f712008-11-04 02:10:20 +000034static cl::opt<unsigned>
Bill Wendling30ef3e32008-11-04 21:53:09 +000035SSPBufferSize("stack-protector-buffer-size", cl::init(8),
Bill Wendling05225152008-11-18 05:32:11 +000036 cl::desc("Lower bound for a buffer to be considered for "
37 "stack protection"));
Bill Wendlingdac9f712008-11-04 02:10:20 +000038
39namespace {
Nick Lewycky492d06e2009-10-25 06:33:48 +000040 class StackProtector : public FunctionPass {
Bill Wendling30ef3e32008-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 Wendlingdac9f712008-11-04 02:10:20 +000044
Bill Wendlingdac9f712008-11-04 02:10:20 +000045 Function *F;
46 Module *M;
47
Bill Wendlingd57982b2008-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 Wendlingdac9f712008-11-04 02:10:20 +000055
56 /// CreateFailBB - Create a basic block to jump to when the stack protector
57 /// check fails.
Bill Wendlingd57982b2008-11-05 00:00:21 +000058 BasicBlock *CreateFailBB();
Bill Wendlingdac9f712008-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 Wendling30ef3e32008-11-04 21:53:09 +000062 bool RequiresStackProtector() const;
Bill Wendlingdac9f712008-11-04 02:10:20 +000063 public:
64 static char ID; // Pass identification, replacement for typeid.
Owen Anderson75693222010-08-06 18:33:48 +000065 StackProtector() : FunctionPass(ID), TLI(0) {}
Bill Wendling3e13ce52008-11-13 01:02:14 +000066 StackProtector(const TargetLowering *tli)
Owen Anderson75693222010-08-06 18:33:48 +000067 : FunctionPass(ID), TLI(tli) {}
Bill Wendlingdac9f712008-11-04 02:10:20 +000068
69 virtual bool runOnFunction(Function &Fn);
70 };
71} // end anonymous namespace
72
73char StackProtector::ID = 0;
Owen Anderson6374c3d2010-07-21 22:09:45 +000074INITIALIZE_PASS(StackProtector, "stack-protector",
75 "Insert stack protectors", false, false);
Bill Wendlingdac9f712008-11-04 02:10:20 +000076
Bill Wendling3e13ce52008-11-13 01:02:14 +000077FunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {
78 return new StackProtector(tli);
Bill Wendlingdac9f712008-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 Wendlingd57982b2008-11-05 00:00:21 +000087 return InsertStackProtectors();
Bill Wendlingdac9f712008-11-04 02:10:20 +000088}
89
Bill Wendling05225152008-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
Bill Wendling68e02132009-10-23 00:01:05 +0000114 if (const ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType())) {
115 // We apparently only care about character arrays.
Duncan Sandse92dee12010-02-15 16:12:20 +0000116 if (!AT->getElementType()->isIntegerTy(8))
Bill Wendling68e02132009-10-23 00:01:05 +0000117 continue;
118
Bill Wendling05225152008-11-18 05:32:11 +0000119 // If an array has more than SSPBufferSize bytes of allocated space,
120 // then we emit stack protectors.
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000121 if (SSPBufferSize <= TD->getTypeAllocSize(AT))
Bill Wendling05225152008-11-18 05:32:11 +0000122 return true;
Bill Wendling68e02132009-10-23 00:01:05 +0000123 }
Bill Wendling05225152008-11-18 05:32:11 +0000124 }
125 }
126
127 return false;
128}
129
Bill Wendlingd57982b2008-11-05 00:00:21 +0000130/// InsertStackProtectors - Insert code into the prologue and epilogue of the
131/// function.
132///
133/// - The prologue code loads and stores the stack guard onto the stack.
134/// - The epilogue checks the value stored in the prologue against the original
135/// value. It calls __stack_chk_fail if they differ.
136bool StackProtector::InsertStackProtectors() {
Bill Wendling8126a3f2008-11-07 01:23:58 +0000137 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
138 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
Eric Christopher2c36e552010-07-06 05:18:56 +0000139 Value *StackGuardVar = 0; // The stack guard variable.
Bill Wendling8126a3f2008-11-07 01:23:58 +0000140
Bill Wendlinga91e7822008-11-10 21:13:10 +0000141 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
Bill Wendling05225152008-11-18 05:32:11 +0000142 BasicBlock *BB = I++;
Bill Wendlingdac9f712008-11-04 02:10:20 +0000143
Bill Wendling05225152008-11-18 05:32:11 +0000144 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
145 if (!RI) continue;
Bill Wendling8126a3f2008-11-07 01:23:58 +0000146
Bill Wendling05225152008-11-18 05:32:11 +0000147 if (!FailBB) {
148 // Insert code into the entry block that stores the __stack_chk_guard
149 // variable onto the stack:
150 //
151 // entry:
152 // StackGuardSlot = alloca i8*
153 // StackGuard = load __stack_chk_guard
154 // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
155 //
Chris Lattner8d338e22010-07-06 15:59:27 +0000156 const PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
Eric Christopher2c36e552010-07-06 05:18:56 +0000157 unsigned AddressSpace, Offset;
158 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
Chris Lattner8d338e22010-07-06 15:59:27 +0000159 Constant *OffsetVal =
160 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
161
162 StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
163 PointerType::get(PtrTy, AddressSpace));
Eric Christopher2c36e552010-07-06 05:18:56 +0000164 } else {
Chris Lattner8d338e22010-07-06 15:59:27 +0000165 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
Eric Christopher2c36e552010-07-06 05:18:56 +0000166 }
Bill Wendling8126a3f2008-11-07 01:23:58 +0000167
Bill Wendling05225152008-11-18 05:32:11 +0000168 BasicBlock &Entry = F->getEntryBlock();
169 Instruction *InsPt = &Entry.front();
Bill Wendling8126a3f2008-11-07 01:23:58 +0000170
Owen Anderson140166d2009-07-15 23:53:25 +0000171 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
Bill Wendling05225152008-11-18 05:32:11 +0000172 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
Bill Wendlinga91e7822008-11-10 21:13:10 +0000173
Bill Wendling05225152008-11-18 05:32:11 +0000174 Value *Args[] = { LI, AI };
175 CallInst::
Bill Wendling0ac36702008-11-18 11:01:33 +0000176 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
Bill Wendling05225152008-11-18 05:32:11 +0000177 &Args[0], array_endof(Args), "", InsPt);
Bill Wendlingdac9f712008-11-04 02:10:20 +0000178
Bill Wendling05225152008-11-18 05:32:11 +0000179 // Create the basic block to jump to when the guard check fails.
180 FailBB = CreateFailBB();
Bill Wendlingd7fff9f2008-11-06 23:55:49 +0000181 }
Bill Wendling05225152008-11-18 05:32:11 +0000182
183 // For each block with a return instruction, convert this:
184 //
185 // return:
186 // ...
187 // ret ...
188 //
189 // into this:
190 //
191 // return:
192 // ...
193 // %1 = load __stack_chk_guard
Bill Wendling34dfafc2008-11-18 07:30:57 +0000194 // %2 = load StackGuardSlot
Bill Wendling05225152008-11-18 05:32:11 +0000195 // %3 = cmp i1 %1, %2
196 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
197 //
198 // SP_return:
199 // ret ...
200 //
201 // CallStackCheckFailBlk:
202 // call void @__stack_chk_fail()
203 // unreachable
204
205 // Split the basic block before the return instruction.
206 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
207
Bill Wendling4e14b652009-03-06 01:41:15 +0000208 // Remove default branch instruction to the new BB.
209 BB->getTerminator()->eraseFromParent();
210
Bill Wendling05225152008-11-18 05:32:11 +0000211 // Move the newly created basic block to the point right after the old basic
212 // block so that it's in the "fall through" position.
213 NewBB->moveAfter(BB);
214
215 // Generate the stack protector instructions in the old basic block.
Bill Wendling34dfafc2008-11-18 07:30:57 +0000216 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
217 LoadInst *LI2 = new LoadInst(AI, "", true, BB);
Owen Anderson6601fcd2009-07-09 23:48:35 +0000218 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
Bill Wendling05225152008-11-18 05:32:11 +0000219 BranchInst::Create(NewBB, FailBB, Cmp, BB);
Bill Wendlingdac9f712008-11-04 02:10:20 +0000220 }
Bill Wendlingd57982b2008-11-05 00:00:21 +0000221
Bill Wendlingd7fff9f2008-11-06 23:55:49 +0000222 // Return if we didn't modify any basic blocks. I.e., there are no return
223 // statements in the function.
224 if (!FailBB) return false;
225
Bill Wendlingd57982b2008-11-05 00:00:21 +0000226 return true;
Bill Wendlingdac9f712008-11-04 02:10:20 +0000227}
228
229/// CreateFailBB - Create a basic block to jump to when the stack protector
230/// check fails.
Bill Wendlingd57982b2008-11-05 00:00:21 +0000231BasicBlock *StackProtector::CreateFailBB() {
Owen Anderson35b47072009-08-13 21:58:54 +0000232 BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
233 "CallStackCheckFailBlk", F);
Bill Wendlingdac9f712008-11-04 02:10:20 +0000234 Constant *StackChkFail =
Owen Anderson35b47072009-08-13 21:58:54 +0000235 M->getOrInsertFunction("__stack_chk_fail",
236 Type::getVoidTy(F->getContext()), NULL);
Bill Wendlingdac9f712008-11-04 02:10:20 +0000237 CallInst::Create(StackChkFail, "", FailBB);
Owen Anderson35b47072009-08-13 21:58:54 +0000238 new UnreachableInst(F->getContext(), FailBB);
Bill Wendlingd57982b2008-11-05 00:00:21 +0000239 return FailBB;
Bill Wendlingdac9f712008-11-04 02:10:20 +0000240}