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/Analysis/Dominators.h"
20 #include "llvm/Attributes.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Module.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/DataLayout.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/Triple.h"
36 class StackProtector : public FunctionPass {
37 /// TLI - Keep a pointer of a TargetLowering to consult for determining
38 /// target type sizes.
39 const TargetLowering *TLI;
46 /// InsertStackProtectors - Insert code into the prologue and epilogue of
49 /// - The prologue code loads and stores the stack guard onto the stack.
50 /// - The epilogue checks the value stored in the prologue against the
51 /// original value. It calls __stack_chk_fail if they differ.
52 bool InsertStackProtectors();
54 /// CreateFailBB - Create a basic block to jump to when the stack protector
56 BasicBlock *CreateFailBB();
58 /// ContainsProtectableArray - Check whether the type either is an array or
59 /// contains an array of sufficient size so that we need stack protectors
61 bool ContainsProtectableArray(Type *Ty, bool InStruct = false) const;
63 /// RequiresStackProtector - Check whether or not this function needs a
64 /// stack protector based upon the stack protector level.
65 bool RequiresStackProtector() const;
67 static char ID; // Pass identification, replacement for typeid.
68 StackProtector() : FunctionPass(ID), TLI(0) {
69 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
71 StackProtector(const TargetLowering *tli)
72 : FunctionPass(ID), TLI(tli) {
73 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.addPreserved<DominatorTree>();
80 virtual bool runOnFunction(Function &Fn);
82 } // end anonymous namespace
84 char StackProtector::ID = 0;
85 INITIALIZE_PASS(StackProtector, "stack-protector",
86 "Insert stack protectors", false, false)
88 FunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {
89 return new StackProtector(tli);
92 bool StackProtector::runOnFunction(Function &Fn) {
95 DT = getAnalysisIfAvailable<DominatorTree>();
97 if (!RequiresStackProtector()) return false;
99 return InsertStackProtectors();
102 /// ContainsProtectableArray - Check whether the type either is an array or
103 /// contains a char array of sufficient size so that we need stack protectors
105 bool StackProtector::ContainsProtectableArray(Type *Ty, bool InStruct) const {
106 if (!Ty) return false;
107 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
108 const TargetMachine &TM = TLI->getTargetMachine();
109 if (!AT->getElementType()->isIntegerTy(8)) {
110 Triple Trip(TM.getTargetTriple());
112 // If we're on a non-Darwin platform or we're inside of a structure, don't
113 // add stack protectors unless the array is a character array.
114 if (InStruct || !Trip.isOSDarwin())
118 // If an array has more than SSPBufferSize bytes of allocated space, then we
119 // emit stack protectors.
120 if (TM.Options.SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT))
124 const StructType *ST = dyn_cast<StructType>(Ty);
125 if (!ST) return false;
127 for (StructType::element_iterator I = ST->element_begin(),
128 E = ST->element_end(); I != E; ++I)
129 if (ContainsProtectableArray(*I, true))
135 /// RequiresStackProtector - Check whether or not this function needs a stack
136 /// protector based upon the stack protector level. The heuristic we use is to
137 /// add a guard variable to functions that call alloca, and functions with
138 /// buffers larger than SSPBufferSize bytes.
139 bool StackProtector::RequiresStackProtector() const {
140 if (F->getFnAttributes().hasAttribute(Attributes::StackProtectReq))
143 if (!F->getFnAttributes().hasAttribute(Attributes::StackProtect))
146 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
149 for (BasicBlock::iterator
150 II = BB->begin(), IE = BB->end(); II != IE; ++II)
151 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
152 if (AI->isArrayAllocation())
153 // This is a call to alloca with a variable size. Emit stack
157 if (ContainsProtectableArray(AI->getAllocatedType()))
165 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
168 /// - The prologue code loads and stores the stack guard onto the stack.
169 /// - The epilogue checks the value stored in the prologue against the original
170 /// value. It calls __stack_chk_fail if they differ.
171 bool StackProtector::InsertStackProtectors() {
172 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
173 BasicBlock *FailBBDom = 0; // FailBB's dominator.
174 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
175 Value *StackGuardVar = 0; // The stack guard variable.
177 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
178 BasicBlock *BB = I++;
179 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
183 // Insert code into the entry block that stores the __stack_chk_guard
184 // variable onto the stack:
187 // StackGuardSlot = alloca i8*
188 // StackGuard = load __stack_chk_guard
189 // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
191 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
192 unsigned AddressSpace, Offset;
193 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
194 Constant *OffsetVal =
195 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
197 StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
198 PointerType::get(PtrTy, AddressSpace));
200 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
203 BasicBlock &Entry = F->getEntryBlock();
204 Instruction *InsPt = &Entry.front();
206 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
207 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
209 Value *Args[] = { LI, AI };
211 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
214 // Create the basic block to jump to when the guard check fails.
215 FailBB = CreateFailBB();
218 // For each block with a return instruction, convert this:
228 // %1 = load __stack_chk_guard
229 // %2 = load StackGuardSlot
230 // %3 = cmp i1 %1, %2
231 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
236 // CallStackCheckFailBlk:
237 // call void @__stack_chk_fail()
240 // Split the basic block before the return instruction.
241 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
243 if (DT && DT->isReachableFromEntry(BB)) {
244 DT->addNewBlock(NewBB, BB);
245 FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;
248 // Remove default branch instruction to the new BB.
249 BB->getTerminator()->eraseFromParent();
251 // Move the newly created basic block to the point right after the old basic
252 // block so that it's in the "fall through" position.
253 NewBB->moveAfter(BB);
255 // Generate the stack protector instructions in the old basic block.
256 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
257 LoadInst *LI2 = new LoadInst(AI, "", true, BB);
258 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
259 BranchInst::Create(NewBB, FailBB, Cmp, BB);
262 // Return if we didn't modify any basic blocks. I.e., there are no return
263 // statements in the function.
264 if (!FailBB) return false;
267 DT->addNewBlock(FailBB, FailBBDom);
272 /// CreateFailBB - Create a basic block to jump to when the stack protector
274 BasicBlock *StackProtector::CreateFailBB() {
275 BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
276 "CallStackCheckFailBlk", F);
277 Constant *StackChkFail =
278 M->getOrInsertFunction("__stack_chk_fail",
279 Type::getVoidTy(F->getContext()), NULL);
280 CallInst::Create(StackChkFail, "", FailBB);
281 new UnreachableInst(F->getContext(), FailBB);