blob: 17f715df19f0cea51c3b9d92f4bb12bf1aa33ef5 [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"
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
22#include "llvm/Instructions.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000023#include "llvm/Intrinsics.h"
Bill Wendling2b58ce52008-11-04 02:10:20 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
26#include "llvm/ADT/APInt.h"
27#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 Wendling2b58ce52008-11-04 02:10:20 +000036 cl::desc("The lower bound for a buffer to be considered for "
37 "stack smashing protection."));
38
39namespace {
40 class VISIBILITY_HIDDEN StackProtector : public FunctionPass {
Bill Wendling80a320d2008-11-04 21:53:09 +000041 /// Level - The level of stack protection.
42 SSP::StackProtectorLevel Level;
43
44 /// TLI - Keep a pointer of a TargetLowering to consult for determining
45 /// target type sizes.
46 const TargetLowering *TLI;
Bill Wendling2b58ce52008-11-04 02:10:20 +000047
Bill Wendling2b58ce52008-11-04 02:10:20 +000048 Function *F;
49 Module *M;
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.
Bill Wendling613f7742008-11-05 00:00:21 +000068 StackProtector() : FunctionPass(&ID), Level(SSP::OFF), TLI(0) {}
Bill Wendling80a320d2008-11-04 21:53:09 +000069 StackProtector(SSP::StackProtectorLevel lvl, const TargetLowering *tli)
Bill Wendling613f7742008-11-05 00:00:21 +000070 : FunctionPass(&ID), Level(lvl), TLI(tli) {}
Bill Wendling2b58ce52008-11-04 02:10:20 +000071
72 virtual bool runOnFunction(Function &Fn);
73 };
74} // end anonymous namespace
75
76char StackProtector::ID = 0;
77static RegisterPass<StackProtector>
78X("stack-protector", "Insert stack protectors");
79
Bill Wendling80a320d2008-11-04 21:53:09 +000080FunctionPass *llvm::createStackProtectorPass(SSP::StackProtectorLevel lvl,
81 const TargetLowering *tli) {
82 return new StackProtector(lvl, tli);
Bill Wendling2b58ce52008-11-04 02:10:20 +000083}
84
85bool StackProtector::runOnFunction(Function &Fn) {
86 F = &Fn;
87 M = F->getParent();
88
89 if (!RequiresStackProtector()) return false;
90
Bill Wendling613f7742008-11-05 00:00:21 +000091 return InsertStackProtectors();
Bill Wendling2b58ce52008-11-04 02:10:20 +000092}
93
Bill Wendling613f7742008-11-05 00:00:21 +000094/// InsertStackProtectors - Insert code into the prologue and epilogue of the
95/// function.
96///
97/// - The prologue code loads and stores the stack guard onto the stack.
98/// - The epilogue checks the value stored in the prologue against the original
99/// value. It calls __stack_chk_fail if they differ.
100bool StackProtector::InsertStackProtectors() {
Bill Wendling1fb615f2008-11-06 23:55:49 +0000101 Constant *StackGuardVar = 0; // The global variable for the stack guard.
102 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
Bill Wendling2b58ce52008-11-04 02:10:20 +0000103
104 // Loop through the basic blocks that have return instructions. Convert this:
105 //
106 // return:
107 // ...
108 // ret ...
109 //
110 // into this:
111 //
112 // return:
113 // ...
114 // %1 = load __stack_chk_guard
115 // %2 = load <stored stack guard>
116 // %3 = cmp i1 %1, %2
Bill Wendlingb2a42982008-11-06 02:29:10 +0000117 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
Bill Wendling2b58ce52008-11-04 02:10:20 +0000118 //
Bill Wendlingb7c2c122008-11-04 22:51:24 +0000119 // SP_return:
Bill Wendling2b58ce52008-11-04 02:10:20 +0000120 // ret ...
121 //
122 // CallStackCheckFailBlk:
123 // call void @__stack_chk_fail()
124 // unreachable
125 //
Bill Wendling1fb615f2008-11-06 23:55:49 +0000126 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
127 BasicBlock *BB = I;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000128
Bill Wendling1fb615f2008-11-06 23:55:49 +0000129 if (isa<ReturnInst>(BB->getTerminator())) {
130 // Create the basic block to jump to when the guard check fails.
131 if (!FailBB)
132 FailBB = CreateFailBB();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000133
Bill Wendling1fb615f2008-11-06 23:55:49 +0000134 if (!StackGuardVar)
135 StackGuardVar =
136 M->getOrInsertGlobal("__stack_chk_guard",
137 PointerType::getUnqual(Type::Int8Ty));
Bill Wendling2b58ce52008-11-04 02:10:20 +0000138
Bill Wendling1fb615f2008-11-06 23:55:49 +0000139 ReturnInst *RI = cast<ReturnInst>(BB->getTerminator());
140 Function::iterator InsPt = BB; ++InsPt; // Insertion point for new BB.
141 ++I;
142
143 // Split the basic block before the return instruction.
144 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
145
146 // Move the newly created basic block to the point right after the old basic
147 // block so that it's in the "fall through" position.
148 NewBB->removeFromParent();
149 F->getBasicBlockList().insert(InsPt, NewBB);
150
151 // Generate the stack protector instructions in the old basic block.
152 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
153 CallInst *CI = CallInst::
154 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector_check),
155 "", BB);
156 ICmpInst *Cmp = new ICmpInst(CmpInst::ICMP_EQ, CI, LI1, "", BB);
157 BranchInst::Create(NewBB, FailBB, Cmp, BB);
158 }
Bill Wendling2b58ce52008-11-04 02:10:20 +0000159 }
Bill Wendling613f7742008-11-05 00:00:21 +0000160
Bill Wendling1fb615f2008-11-06 23:55:49 +0000161 // Return if we didn't modify any basic blocks. I.e., there are no return
162 // statements in the function.
163 if (!FailBB) return false;
164
165 // Insert code into the entry block that stores the __stack_chk_guard variable
166 // onto the stack.
167 BasicBlock &Entry = F->getEntryBlock();
168 Instruction *InsertPt = &Entry.front();
169
170 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsertPt);
171 CallInst::
172 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector_create),
173 LI, "", InsertPt);
174
Bill Wendling613f7742008-11-05 00:00:21 +0000175 return true;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000176}
177
178/// CreateFailBB - Create a basic block to jump to when the stack protector
179/// check fails.
Bill Wendling613f7742008-11-05 00:00:21 +0000180BasicBlock *StackProtector::CreateFailBB() {
181 BasicBlock *FailBB = BasicBlock::Create("CallStackCheckFailBlk", F);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000182 Constant *StackChkFail =
Bill Wendling80a320d2008-11-04 21:53:09 +0000183 M->getOrInsertFunction("__stack_chk_fail", Type::VoidTy, NULL);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000184 CallInst::Create(StackChkFail, "", FailBB);
185 new UnreachableInst(FailBB);
Bill Wendling613f7742008-11-05 00:00:21 +0000186 return FailBB;
Bill Wendling2b58ce52008-11-04 02:10:20 +0000187}
188
189/// RequiresStackProtector - Check whether or not this function needs a stack
Bill Wendling89c5cc62008-11-06 02:38:58 +0000190/// protector based upon the stack protector level. The heuristic we use is to
191/// add a guard variable to functions that call alloca, and functions with
192/// buffers larger than 8 bytes.
Bill Wendling80a320d2008-11-04 21:53:09 +0000193bool StackProtector::RequiresStackProtector() const {
Bill Wendling2b58ce52008-11-04 02:10:20 +0000194 switch (Level) {
195 default: return false;
Bill Wendling80a320d2008-11-04 21:53:09 +0000196 case SSP::ALL: return true;
197 case SSP::SOME: {
Bill Wendling80a320d2008-11-04 21:53:09 +0000198 const TargetData *TD = TLI->getTargetData();
Bill Wendling2b58ce52008-11-04 02:10:20 +0000199
200 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
201 BasicBlock *BB = I;
202
203 for (BasicBlock::iterator
204 II = BB->begin(), IE = BB->end(); II != IE; ++II)
Bill Wendling80a320d2008-11-04 21:53:09 +0000205 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
Bill Wendling89c5cc62008-11-06 02:38:58 +0000206 if (!AI->isArrayAllocation()) continue; // Only care about arrays.
207
Bill Wendling2b58ce52008-11-04 02:10:20 +0000208 if (ConstantInt *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Bill Wendlingfa75dc62008-11-05 00:54:27 +0000209 const Type *Ty = AI->getAllocatedType();
210 uint64_t TySize = TD->getABITypeSize(Ty);
Bill Wendling2b58ce52008-11-04 02:10:20 +0000211
Bill Wendling703ccfe2008-11-06 22:18:44 +0000212 // If an array has more than 8 bytes of allocated space, then we
213 // emit stack protectors.
214 if (SSPBufferSize <= TySize * CI->getZExtValue())
Bill Wendling80a320d2008-11-04 21:53:09 +0000215 return true;
Bill Wendling89c5cc62008-11-06 02:38:58 +0000216 } else {
217 // This is a call to alloca with a variable size. Default to adding
218 // stack protectors.
219 return true;
Bill Wendling80a320d2008-11-04 21:53:09 +0000220 }
221 }
222 }
Bill Wendling2b58ce52008-11-04 02:10:20 +0000223
224 return false;
225 }
226 }
227}