blob: b31db5f8691df6976334f74a11fc608f16c5d023 [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
Bill Wendling6d86f3c2012-08-13 21:20:43 +000050 DominatorTree *DT;
Cameron Zwarich80f6a502011-01-08 17:01:52 +000051
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
Bill Wendlinga67eda72012-08-17 20:59:56 +000064 /// ContainsProtectableArray - Check whether the type either is an array or
65 /// contains an array of sufficient size so that we need stack protectors
66 /// for it.
67 bool ContainsProtectableArray(Type *Ty, bool InStruct = false) const;
68
Bill Wendling2b58ce52008-11-04 02:10:20 +000069 /// RequiresStackProtector - Check whether or not this function needs a
70 /// stack protector based upon the stack protector level.
Bill Wendling80a320d2008-11-04 21:53:09 +000071 bool RequiresStackProtector() const;
Bill Wendling2b58ce52008-11-04 02:10:20 +000072 public:
73 static char ID; // Pass identification, replacement for typeid.
Owen Anderson081c34b2010-10-19 17:21:58 +000074 StackProtector() : FunctionPass(ID), TLI(0) {
75 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
76 }
Bill Wendlinge9e6bdf2008-11-13 01:02:14 +000077 StackProtector(const TargetLowering *tli)
Owen Anderson081c34b2010-10-19 17:21:58 +000078 : FunctionPass(ID), TLI(tli) {
Bill Wendling6d86f3c2012-08-13 21:20:43 +000079 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
80 }
Bill Wendling2b58ce52008-11-04 02:10:20 +000081
Cameron Zwarich80f6a502011-01-08 17:01:52 +000082 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
83 AU.addPreserved<DominatorTree>();
84 }
85
Bill Wendling2b58ce52008-11-04 02:10:20 +000086 virtual bool runOnFunction(Function &Fn);
87 };
88} // end anonymous namespace
89
90char StackProtector::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000091INITIALIZE_PASS(StackProtector, "stack-protector",
Owen Andersonce665bd2010-10-07 22:25:06 +000092 "Insert stack protectors", false, false)
Bill Wendling2b58ce52008-11-04 02:10:20 +000093
Bill Wendlinge9e6bdf2008-11-13 01:02:14 +000094FunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {
95 return new StackProtector(tli);
Bill Wendling2b58ce52008-11-04 02:10:20 +000096}
97
98bool StackProtector::runOnFunction(Function &Fn) {
99 F = &Fn;
100 M = F->getParent();
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000101 DT = getAnalysisIfAvailable<DominatorTree>();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000102
103 if (!RequiresStackProtector()) return false;
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000104
Bill Wendling613f7742008-11-05 00:00:21 +0000105 return InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000106}
107
Bill Wendlinga67eda72012-08-17 20:59:56 +0000108/// ContainsProtectableArray - Check whether the type either is an array or
109/// contains a char array of sufficient size so that we need stack protectors
110/// for it.
111bool StackProtector::ContainsProtectableArray(Type *Ty, bool InStruct) const {
112 if (!Ty) return false;
113 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
114 if (!AT->getElementType()->isIntegerTy(8)) {
115 const TargetMachine &TM = TLI->getTargetMachine();
116 Triple Trip(TM.getTargetTriple());
117
118 // If we're on a non-Darwin platform or we're inside of a structure, don't
119 // add stack protectors unless the array is a character array.
120 if (InStruct || !Trip.isOSDarwin())
121 return false;
122 }
123
124 // If an array has more than SSPBufferSize bytes of allocated space, then we
125 // emit stack protectors.
126 if (SSPBufferSize <= TLI->getTargetData()->getTypeAllocSize(AT))
127 return true;
128 }
129
130 const StructType *ST = dyn_cast<StructType>(Ty);
131 if (!ST) return false;
132
133 for (StructType::element_iterator I = ST->element_begin(),
134 E = ST->element_end(); I != E; ++I)
135 if (ContainsProtectableArray(*I, true))
136 return true;
137
138 return false;
139}
140
Bill Wendlingc3348a72008-11-18 05:32:11 +0000141/// RequiresStackProtector - Check whether or not this function needs a stack
142/// protector based upon the stack protector level. The heuristic we use is to
143/// add a guard variable to functions that call alloca, and functions with
144/// buffers larger than SSPBufferSize bytes.
145bool StackProtector::RequiresStackProtector() const {
146 if (F->hasFnAttr(Attribute::StackProtectReq))
147 return true;
148
149 if (!F->hasFnAttr(Attribute::StackProtect))
150 return false;
151
Bill Wendlingc3348a72008-11-18 05:32:11 +0000152 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
153 BasicBlock *BB = I;
154
155 for (BasicBlock::iterator
156 II = BB->begin(), IE = BB->end(); II != IE; ++II)
157 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
158 if (AI->isArrayAllocation())
159 // This is a call to alloca with a variable size. Emit stack
160 // protectors.
161 return true;
162
Bill Wendlinga67eda72012-08-17 20:59:56 +0000163 if (ContainsProtectableArray(AI->getAllocatedType()))
164 return true;
Bill Wendlingc3348a72008-11-18 05:32:11 +0000165 }
166 }
167
168 return false;
169}
170
Bill Wendling613f7742008-11-05 00:00:21 +0000171/// InsertStackProtectors - Insert code into the prologue and epilogue of the
172/// function.
173///
174/// - The prologue code loads and stores the stack guard onto the stack.
175/// - The epilogue checks the value stored in the prologue against the original
176/// value. It calls __stack_chk_fail if they differ.
177bool StackProtector::InsertStackProtectors() {
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000178 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000179 BasicBlock *FailBBDom = 0; // FailBB's dominator.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000180 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000181 Value *StackGuardVar = 0; // The stack guard variable.
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000182
Bill Wendling72056772008-11-10 21:13:10 +0000183 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
Bill Wendlingc3348a72008-11-18 05:32:11 +0000184 BasicBlock *BB = I++;
Bill Wendlingc3348a72008-11-18 05:32:11 +0000185 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
186 if (!RI) continue;
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000187
Bill Wendlingc3348a72008-11-18 05:32:11 +0000188 if (!FailBB) {
189 // Insert code into the entry block that stores the __stack_chk_guard
190 // variable onto the stack:
191 //
192 // entry:
193 // StackGuardSlot = alloca i8*
194 // StackGuard = load __stack_chk_guard
195 // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000196 //
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000197 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000198 unsigned AddressSpace, Offset;
199 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
Chris Lattnerf8bd3922010-07-06 15:59:27 +0000200 Constant *OffsetVal =
201 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000202
Chris Lattnerf8bd3922010-07-06 15:59:27 +0000203 StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
204 PointerType::get(PtrTy, AddressSpace));
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000205 } else {
Bill Wendling6d86f3c2012-08-13 21:20:43 +0000206 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
Eric Christopherf7a0c7b2010-07-06 05:18:56 +0000207 }
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000208
Bill Wendling3c288b92011-03-29 07:28:52 +0000209 BasicBlock &Entry = F->getEntryBlock();
Bill Wendlingc3348a72008-11-18 05:32:11 +0000210 Instruction *InsPt = &Entry.front();
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +0000211
Owen Anderson50dead02009-07-15 23:53:25 +0000212 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
Bill Wendlingc3348a72008-11-18 05:32:11 +0000213 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
Bill Wendling72056772008-11-10 21:13:10 +0000214
Bill Wendlingc3348a72008-11-18 05:32:11 +0000215 Value *Args[] = { LI, AI };
216 CallInst::
Bill Wendling57344502008-11-18 11:01:33 +0000217 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
Jay Foada3efbb12011-07-15 08:37:34 +0000218 Args, "", InsPt);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000219
Bill Wendlingc3348a72008-11-18 05:32:11 +0000220 // Create the basic block to jump to when the guard check fails.
221 FailBB = CreateFailBB();
Bill Wendling1fb615f2008-11-06 23:55:49 +0000222 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000223
224 // For each block with a return instruction, convert this:
225 //
226 // return:
227 // ...
228 // ret ...
229 //
230 // into this:
231 //
232 // return:
233 // ...
234 // %1 = load __stack_chk_guard
Bill Wendling733bbc52008-11-18 07:30:57 +0000235 // %2 = load StackGuardSlot
Bill Wendlingc3348a72008-11-18 05:32:11 +0000236 // %3 = cmp i1 %1, %2
237 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
238 //
239 // SP_return:
240 // ret ...
241 //
242 // CallStackCheckFailBlk:
243 // call void @__stack_chk_fail()
244 // unreachable
245
246 // Split the basic block before the return instruction.
247 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
Bill Wendling3c288b92011-03-29 07:28:52 +0000248
Bill Wendling3f782f42011-03-29 17:12:55 +0000249 if (DT && DT->isReachableFromEntry(BB)) {
Cameron Zwarich53aac152011-03-11 21:51:56 +0000250 DT->addNewBlock(NewBB, BB);
Bill Wendling3c288b92011-03-29 07:28:52 +0000251 FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000252 }
Bill Wendlingc3348a72008-11-18 05:32:11 +0000253
Bill Wendling56016992009-03-06 01:41:15 +0000254 // Remove default branch instruction to the new BB.
255 BB->getTerminator()->eraseFromParent();
256
Bill Wendlingc3348a72008-11-18 05:32:11 +0000257 // Move the newly created basic block to the point right after the old basic
258 // block so that it's in the "fall through" position.
259 NewBB->moveAfter(BB);
260
261 // Generate the stack protector instructions in the old basic block.
Bill Wendling733bbc52008-11-18 07:30:57 +0000262 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
263 LoadInst *LI2 = new LoadInst(AI, "", true, BB);
Owen Anderson333c4002009-07-09 23:48:35 +0000264 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
Bill Wendlingc3348a72008-11-18 05:32:11 +0000265 BranchInst::Create(NewBB, FailBB, Cmp, BB);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000266 }
Bill Wendling613f7742008-11-05 00:00:21 +0000267
Bill Wendling1fb615f2008-11-06 23:55:49 +0000268 // Return if we didn't modify any basic blocks. I.e., there are no return
269 // statements in the function.
270 if (!FailBB) return false;
271
Cameron Zwarich53aac152011-03-11 21:51:56 +0000272 if (DT && FailBBDom)
Cameron Zwarich80f6a502011-01-08 17:01:52 +0000273 DT->addNewBlock(FailBB, FailBBDom);
274
Bill Wendling613f7742008-11-05 00:00:21 +0000275 return true;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000276}
277
278/// CreateFailBB - Create a basic block to jump to when the stack protector
279/// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +0000280BasicBlock *StackProtector::CreateFailBB() {
Owen Anderson1d0be152009-08-13 21:58:54 +0000281 BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
282 "CallStackCheckFailBlk", F);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000283 Constant *StackChkFail =
Owen Anderson1d0be152009-08-13 21:58:54 +0000284 M->getOrInsertFunction("__stack_chk_fail",
285 Type::getVoidTy(F->getContext()), NULL);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000286 CallInst::Create(StackChkFail, "", FailBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000287 new UnreachableInst(F->getContext(), FailBB);
Bill Wendling613f7742008-11-05 00:00:21 +0000288 return FailBB;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000289}