1 //===-- StackProtector.cpp - Stack Protector Insertion --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // 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
13 // changed, then there was some sort of violation and the program aborts.
15 //===----------------------------------------------------------------------===//
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"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetLowering.h"
31 // SSPBufferSize - The lower bound for a buffer to be considered for stack
32 // smashing protection.
33 static cl::opt<unsigned>
34 SSPBufferSize("stack-protector-buffer-size", cl::init(8),
35 cl::desc("The lower bound for a buffer to be considered for "
36 "stack smashing protection."));
39 class VISIBILITY_HIDDEN StackProtector : public FunctionPass {
40 /// Level - The level of stack protection.
41 SSP::StackProtectorLevel Level;
43 /// TLI - Keep a pointer of a TargetLowering to consult for determining
44 /// target type sizes.
45 const TargetLowering *TLI;
50 /// InsertStackProtectors - Insert code into the prologue and epilogue of
53 /// - The prologue code loads and stores the stack guard onto the stack.
54 /// - The epilogue checks the value stored in the prologue against the
55 /// original value. It calls __stack_chk_fail if they differ.
56 bool InsertStackProtectors();
58 /// CreateFailBB - Create a basic block to jump to when the stack protector
60 BasicBlock *CreateFailBB();
62 /// RequiresStackProtector - Check whether or not this function needs a
63 /// stack protector based upon the stack protector level.
64 bool RequiresStackProtector() const;
66 static char ID; // Pass identification, replacement for typeid.
67 StackProtector() : FunctionPass(&ID), Level(SSP::OFF), TLI(0) {}
68 StackProtector(SSP::StackProtectorLevel lvl, const TargetLowering *tli)
69 : FunctionPass(&ID), Level(lvl), TLI(tli) {}
71 virtual bool runOnFunction(Function &Fn);
73 } // end anonymous namespace
75 char StackProtector::ID = 0;
76 static RegisterPass<StackProtector>
77 X("stack-protector", "Insert stack protectors");
79 FunctionPass *llvm::createStackProtectorPass(SSP::StackProtectorLevel lvl,
80 const TargetLowering *tli) {
81 return new StackProtector(lvl, tli);
84 bool StackProtector::runOnFunction(Function &Fn) {
88 if (!RequiresStackProtector()) return false;
90 return InsertStackProtectors();
93 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
96 /// - The prologue code loads and stores the stack guard onto the stack.
97 /// - The epilogue checks the value stored in the prologue against the original
98 /// value. It calls __stack_chk_fail if they differ.
99 bool StackProtector::InsertStackProtectors() {
100 Constant *StackGuardVar = 0; // The global variable for the stack guard.
101 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
103 // Loop through the basic blocks that have return instructions. Convert this:
113 // %1 = load __stack_chk_guard
114 // %2 = load <stored stack guard>
115 // %3 = cmp i1 %1, %2
116 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
121 // CallStackCheckFailBlk:
122 // call void @__stack_chk_fail()
125 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
128 if (isa<ReturnInst>(BB->getTerminator())) {
129 // Create the basic block to jump to when the guard check fails.
131 FailBB = CreateFailBB();
135 M->getOrInsertGlobal("__stack_chk_guard",
136 PointerType::getUnqual(Type::Int8Ty));
138 ReturnInst *RI = cast<ReturnInst>(BB->getTerminator());
139 Function::iterator InsPt = BB; ++InsPt; // Insertion point for new BB.
142 // Split the basic block before the return instruction.
143 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
145 // Move the newly created basic block to the point right after the old basic
146 // block so that it's in the "fall through" position.
147 NewBB->removeFromParent();
148 F->getBasicBlockList().insert(InsPt, NewBB);
150 // Generate the stack protector instructions in the old basic block.
151 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
152 CallInst *CI = CallInst::
153 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector_check),
155 ICmpInst *Cmp = new ICmpInst(CmpInst::ICMP_EQ, CI, LI1, "", BB);
156 BranchInst::Create(NewBB, FailBB, Cmp, BB);
160 // Return if we didn't modify any basic blocks. I.e., there are no return
161 // statements in the function.
162 if (!FailBB) return false;
164 // Insert code into the entry block that stores the __stack_chk_guard variable
166 BasicBlock &Entry = F->getEntryBlock();
167 Instruction *InsertPt = &Entry.front();
169 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsertPt);
171 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector_create),
177 /// CreateFailBB - Create a basic block to jump to when the stack protector
179 BasicBlock *StackProtector::CreateFailBB() {
180 BasicBlock *FailBB = BasicBlock::Create("CallStackCheckFailBlk", F);
181 Constant *StackChkFail =
182 M->getOrInsertFunction("__stack_chk_fail", Type::VoidTy, NULL);
183 CallInst::Create(StackChkFail, "", FailBB);
184 new UnreachableInst(FailBB);
188 /// RequiresStackProtector - Check whether or not this function needs a stack
189 /// protector based upon the stack protector level. The heuristic we use is to
190 /// add a guard variable to functions that call alloca, and functions with
191 /// buffers larger than 8 bytes.
192 bool StackProtector::RequiresStackProtector() const {
194 default: return false;
195 case SSP::ALL: return true;
197 const TargetData *TD = TLI->getTargetData();
199 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
202 for (BasicBlock::iterator
203 II = BB->begin(), IE = BB->end(); II != IE; ++II)
204 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
205 if (!AI->isArrayAllocation()) continue; // Only care about arrays.
207 if (ConstantInt *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
208 const Type *Ty = AI->getAllocatedType();
209 uint64_t TySize = TD->getABITypeSize(Ty);
211 // If an array has more than 8 bytes of allocated space, then we
212 // emit stack protectors.
213 if (SSPBufferSize <= TySize * CI->getZExtValue())
216 // This is a call to alloca with a variable size. Default to adding