blob: 1a12303e95cd18696e98afae45f1c4384c008767 [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 Wendling12994222012-08-07 20:59:05 +000031#include "llvm/ADT/Triple.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000032using namespace llvm;
33
Bill Wendlingf0eaa9a2008-11-05 00:46:15 +000034// SSPBufferSize - The lower bound for a buffer to be considered for stack
35// smashing protection.
Bill Wendling2b58ce52008-11-04 02:10:20 +000036static cl::opt<unsigned>
Bill Wendling80a320d2008-11-04 21:53:09 +000037SSPBufferSize("stack-protector-buffer-size", cl::init(8),
Bill Wendlingc3348a72008-11-18 05:32:11 +000038 cl::desc("Lower bound for a buffer to be considered for "
39 "stack protection"));
Bill Wendling2b58ce52008-11-04 02:10:20 +000040
41namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000042 class StackProtector : public FunctionPass {
Bill Wendling80a320d2008-11-04 21:53:09 +000043 /// 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
Cameron Zwarich80f6a502011-01-08 17:01:52 +000050 DominatorTree* DT;
51
Bill Wendling613f7742008-11-05 00:00:21 +000052 /// InsertStackProtectors - Insert code into the prologue and epilogue of
53 /// the function.
54 ///
55 /// - The prologue code loads and stores the stack guard onto the stack.
56 /// - The epilogue checks the value stored in the prologue against the
57 /// original value. It calls __stack_chk_fail if they differ.
58 bool InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +000059
60 /// CreateFailBB - Create a basic block to jump to when the stack protector
61 /// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +000062 BasicBlock *CreateFailBB();
Bill Wendling2b58ce52008-11-04 02:10:20 +000063
64 /// RequiresStackProtector - Check whether or not this function needs a
65 /// stack protector based upon the stack protector level.
Bill Wendling80a320d2008-11-04 21:53:09 +000066 bool RequiresStackProtector() const;
Bill Wendling2b58ce52008-11-04 02:10:20 +000067 public:
68 static char ID; // Pass identification, replacement for typeid.
Owen Anderson081c34b2010-10-19 17:21:58 +000069 StackProtector() : FunctionPass(ID), TLI(0) {
70 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
71 }
Bill Wendlinge9e6bdf2008-11-13 01:02:14 +000072 StackProtector(const TargetLowering *tli)
Owen Anderson081c34b2010-10-19 17:21:58 +000073 : FunctionPass(ID), TLI(tli) {
74 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
75 }
Bill Wendling2b58ce52008-11-04 02:10:20 +000076
Cameron Zwarich80f6a502011-01-08 17:01:52 +000077 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addPreserved<DominatorTree>();
79 }
80
Bill Wendling2b58ce52008-11-04 02:10:20 +000081 virtual bool runOnFunction(Function &Fn);
82 };
83} // end anonymous namespace
84
85char StackProtector::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000086INITIALIZE_PASS(StackProtector, "stack-protector",
Owen Andersonce665bd2010-10-07 22:25:06 +000087 "Insert stack protectors", false, false)
Bill Wendling2b58ce52008-11-04 02:10:20 +000088
Bill Wendlinge9e6bdf2008-11-13 01:02:14 +000089FunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {
90 return new StackProtector(tli);
Bill Wendling2b58ce52008-11-04 02:10:20 +000091}
92
93bool StackProtector::runOnFunction(Function &Fn) {
94 F = &Fn;
95 M = F->getParent();
Cameron Zwarich80f6a502011-01-08 17:01:52 +000096 DT = getAnalysisIfAvailable<DominatorTree>();
Bill Wendling2b58ce52008-11-04 02:10:20 +000097
98 if (!RequiresStackProtector()) return false;
99
Bill Wendling613f7742008-11-05 00:00:21 +0000100 return InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000101}
102
Bill Wendlingc3348a72008-11-18 05:32:11 +0000103/// RequiresStackProtector - Check whether or not this function needs a stack
104/// protector based upon the stack protector level. The heuristic we use is to
105/// add a guard variable to functions that call alloca, and functions with
106/// buffers larger than SSPBufferSize bytes.
107bool StackProtector::RequiresStackProtector() const {
108 if (F->hasFnAttr(Attribute::StackProtectReq))
109 return true;
110
111 if (!F->hasFnAttr(Attribute::StackProtect))
112 return false;
113
114 const TargetData *TD = TLI->getTargetData();
Bill Wendling12994222012-08-07 20:59:05 +0000115 const TargetMachine &TM = TLI->getTargetMachine();
116 Triple Trip(TM.getTargetTriple());
Bill Wendlingc3348a72008-11-18 05:32:11 +0000117
118 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
119 BasicBlock *BB = I;
120
121 for (BasicBlock::iterator
122 II = BB->begin(), IE = BB->end(); II != IE; ++II)
123 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
124 if (AI->isArrayAllocation())
125 // This is a call to alloca with a variable size. Emit stack
126 // protectors.
127 return true;
128
Bill Wendling12994222012-08-07 20:59:05 +0000129 if (ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType())) {
130 // If we're on a non-Darwin platform, don't add stack protectors
131 // unless the array is a character array.
132 if (!Trip.isOSDarwin() && !AT->getElementType()->isIntegerTy(8))
133 continue;
134
Bill Wendlingc3348a72008-11-18 05:32:11 +0000135 // If an array has more than SSPBufferSize bytes of allocated space,
136 // then we emit stack protectors.
Duncan Sands777d2302009-05-09 07:06:46 +0000137 if (SSPBufferSize <= TD->getTypeAllocSize(AT))
Bill Wendlingc3348a72008-11-18 05:32:11 +0000138 return true;
Bill Wendling12994222012-08-07 20:59:05 +0000139 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000140 }
141 }
142
143 return false;
144}
145
Bill Wendling613f7742008-11-05 00:00:21 +0000146/// InsertStackProtectors - Insert code into the prologue and epilogue of the
147/// function.
148///
149/// - The prologue code loads and stores the stack guard onto the stack.
150/// - The epilogue checks the value stored in the prologue against the original
151/// value. It calls __stack_chk_fail if they differ.
152bool StackProtector::InsertStackProtectors() {
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000153 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000154 BasicBlock *FailBBDom = 0; // FailBB's dominator.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000155 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000156 Value *StackGuardVar = 0; // The stack guard variable.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000157
Bill Wendling72056772008-11-10 21:13:10 +0000158 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000159 BasicBlock *BB = I++;
Bill Wendlingc3348a72008-11-18 05:32:11 +0000160 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
161 if (!RI) continue;
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000162
Bill Wendlingc3348a72008-11-18 05:32:11 +0000163 if (!FailBB) {
164 // Insert code into the entry block that stores the __stack_chk_guard
165 // variable onto the stack:
166 //
167 // entry:
168 // StackGuardSlot = alloca i8*
169 // StackGuard = load __stack_chk_guard
170 // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
171 //
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000172 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000173 unsigned AddressSpace, Offset;
174 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
Chris Lattnerf8bd3922010-07-06 15:59:27 +0000175 Constant *OffsetVal =
176 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
177
178 StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
179 PointerType::get(PtrTy, AddressSpace));
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000180 } else {
Chris Lattnerf8bd3922010-07-06 15:59:27 +0000181 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000182 }
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000183
Bill Wendling3c288b92011-03-29 07:28:52 +0000184 BasicBlock &Entry = F->getEntryBlock();
Bill Wendlingc3348a72008-11-18 05:32:11 +0000185 Instruction *InsPt = &Entry.front();
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000186
Owen Anderson50dead02009-07-15 23:53:25 +0000187 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
Bill Wendlingc3348a72008-11-18 05:32:11 +0000188 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
Bill Wendling72056772008-11-10 21:13:10 +0000189
Bill Wendlingc3348a72008-11-18 05:32:11 +0000190 Value *Args[] = { LI, AI };
191 CallInst::
Bill Wendling57344502008-11-18 11:01:33 +0000192 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
Jay Foada3efbb12011-07-15 08:37:34 +0000193 Args, "", InsPt);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000194
Bill Wendlingc3348a72008-11-18 05:32:11 +0000195 // Create the basic block to jump to when the guard check fails.
196 FailBB = CreateFailBB();
Bill Wendling1fb615f2008-11-06 23:55:49 +0000197 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000198
199 // For each block with a return instruction, convert this:
200 //
201 // return:
202 // ...
203 // ret ...
204 //
205 // into this:
206 //
207 // return:
208 // ...
209 // %1 = load __stack_chk_guard
Bill Wendling733bbc52008-11-18 07:30:57 +0000210 // %2 = load StackGuardSlot
Bill Wendlingc3348a72008-11-18 05:32:11 +0000211 // %3 = cmp i1 %1, %2
212 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
213 //
214 // SP_return:
215 // ret ...
216 //
217 // CallStackCheckFailBlk:
218 // call void @__stack_chk_fail()
219 // unreachable
220
221 // Split the basic block before the return instruction.
222 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
Bill Wendling3c288b92011-03-29 07:28:52 +0000223
Bill Wendling3f782f42011-03-29 17:12:55 +0000224 if (DT && DT->isReachableFromEntry(BB)) {
Cameron Zwarich53aac152011-03-11 21:51:56 +0000225 DT->addNewBlock(NewBB, BB);
Bill Wendling3c288b92011-03-29 07:28:52 +0000226 FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000227 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000228
Bill Wendling56016992009-03-06 01:41:15 +0000229 // Remove default branch instruction to the new BB.
230 BB->getTerminator()->eraseFromParent();
231
Bill Wendlingc3348a72008-11-18 05:32:11 +0000232 // Move the newly created basic block to the point right after the old basic
233 // block so that it's in the "fall through" position.
234 NewBB->moveAfter(BB);
235
236 // Generate the stack protector instructions in the old basic block.
Bill Wendling733bbc52008-11-18 07:30:57 +0000237 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
238 LoadInst *LI2 = new LoadInst(AI, "", true, BB);
Owen Anderson333c4002009-07-09 23:48:35 +0000239 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
Bill Wendlingc3348a72008-11-18 05:32:11 +0000240 BranchInst::Create(NewBB, FailBB, Cmp, BB);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000241 }
Bill Wendling613f7742008-11-05 00:00:21 +0000242
Bill Wendling1fb615f2008-11-06 23:55:49 +0000243 // Return if we didn't modify any basic blocks. I.e., there are no return
244 // statements in the function.
245 if (!FailBB) return false;
246
Cameron Zwarich53aac152011-03-11 21:51:56 +0000247 if (DT && FailBBDom)
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000248 DT->addNewBlock(FailBB, FailBBDom);
249
Bill Wendling613f7742008-11-05 00:00:21 +0000250 return true;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000251}
252
253/// CreateFailBB - Create a basic block to jump to when the stack protector
254/// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +0000255BasicBlock *StackProtector::CreateFailBB() {
Owen Anderson1d0be152009-08-13 21:58:54 +0000256 BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
257 "CallStackCheckFailBlk", F);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000258 Constant *StackChkFail =
Owen Anderson1d0be152009-08-13 21:58:54 +0000259 M->getOrInsertFunction("__stack_chk_fail",
260 Type::getVoidTy(F->getContext()), NULL);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000261 CallInst::Create(StackChkFail, "", FailBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000262 new UnreachableInst(F->getContext(), FailBB);
Bill Wendling613f7742008-11-05 00:00:21 +0000263 return FailBB;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000264}