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/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetOptions.h"
37 STATISTIC(NumFunProtected, "Number of functions protected");
38 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
42 class StackProtector : public FunctionPass {
43 /// TLI - Keep a pointer of a TargetLowering to consult for determining
44 /// target type sizes.
45 const TargetLoweringBase *TLI;
52 /// VisitedPHIs - The set of PHI nodes visited when determining
53 /// if a variable's reference has been taken. This set
54 /// is maintained to ensure we don't visit the same PHI node multiple
56 SmallPtrSet<const PHINode*, 16> VisitedPHIs;
58 /// InsertStackProtectors - Insert code into the prologue and epilogue of
61 /// - The prologue code loads and stores the stack guard onto the stack.
62 /// - The epilogue checks the value stored in the prologue against the
63 /// original value. It calls __stack_chk_fail if they differ.
64 bool InsertStackProtectors();
66 /// CreateFailBB - Create a basic block to jump to when the stack protector
68 BasicBlock *CreateFailBB();
70 /// ContainsProtectableArray - Check whether the type either is an array or
71 /// contains an array of sufficient size so that we need stack protectors
73 bool ContainsProtectableArray(Type *Ty, bool Strong = false,
74 bool InStruct = false) const;
76 /// \brief Check whether a stack allocation has its address taken.
77 bool HasAddressTaken(const Instruction *AI);
79 /// RequiresStackProtector - Check whether or not this function needs a
80 /// stack protector based upon the stack protector level.
81 bool RequiresStackProtector();
83 static char ID; // Pass identification, replacement for typeid.
84 StackProtector() : FunctionPass(ID), TLI(0) {
85 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
87 StackProtector(const TargetLoweringBase *tli)
88 : FunctionPass(ID), TLI(tli) {
89 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
92 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
93 AU.addPreserved<DominatorTree>();
96 virtual bool runOnFunction(Function &Fn);
98 } // end anonymous namespace
100 char StackProtector::ID = 0;
101 INITIALIZE_PASS(StackProtector, "stack-protector",
102 "Insert stack protectors", false, false)
104 FunctionPass *llvm::createStackProtectorPass(const TargetLoweringBase *tli) {
105 return new StackProtector(tli);
108 bool StackProtector::runOnFunction(Function &Fn) {
111 DT = getAnalysisIfAvailable<DominatorTree>();
113 if (!RequiresStackProtector()) return false;
116 return InsertStackProtectors();
119 /// ContainsProtectableArray - Check whether the type either is an array or
120 /// contains a char array of sufficient size so that we need stack protectors
122 bool StackProtector::ContainsProtectableArray(Type *Ty, bool Strong,
123 bool InStruct) const {
124 if (!Ty) return false;
125 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
126 // In strong mode any array, regardless of type and size, triggers a
130 const TargetMachine &TM = TLI->getTargetMachine();
131 if (!AT->getElementType()->isIntegerTy(8)) {
132 Triple Trip(TM.getTargetTriple());
134 // If we're on a non-Darwin platform or we're inside of a structure, don't
135 // add stack protectors unless the array is a character array.
136 if (InStruct || !Trip.isOSDarwin())
140 // If an array has more than SSPBufferSize bytes of allocated space, then we
141 // emit stack protectors.
142 if (TM.Options.SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT))
146 const StructType *ST = dyn_cast<StructType>(Ty);
147 if (!ST) return false;
149 for (StructType::element_iterator I = ST->element_begin(),
150 E = ST->element_end(); I != E; ++I)
151 if (ContainsProtectableArray(*I, Strong, true))
157 bool StackProtector::HasAddressTaken(const Instruction *AI) {
158 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
161 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
162 if (AI == SI->getValueOperand())
164 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
165 if (AI == SI->getOperand(0))
167 } else if (isa<CallInst>(U)) {
169 } else if (isa<InvokeInst>(U)) {
171 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
172 if (HasAddressTaken(SI))
174 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
175 // Keep track of what PHI nodes we have already visited to ensure
176 // they are only visited once.
177 if (VisitedPHIs.insert(PN))
178 if (HasAddressTaken(PN))
180 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
181 if (HasAddressTaken(GEP))
183 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
184 if (HasAddressTaken(BI))
191 /// \brief Check whether or not this function needs a stack protector based
192 /// upon the stack protector level.
194 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
195 /// The standard heuristic which will add a guard variable to functions that
196 /// call alloca with a either a variable size or a size >= SSPBufferSize,
197 /// functions with character buffers larger than SSPBufferSize, and functions
198 /// with aggregates containing character buffers larger than SSPBufferSize. The
199 /// strong heuristic will add a guard variables to functions that call alloca
200 /// regardless of size, functions with any buffer regardless of type and size,
201 /// functions with aggregates that contain any buffer regardless of type and
202 /// size, and functions that contain stack-based variables that have had their
204 bool StackProtector::RequiresStackProtector() {
206 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
207 Attribute::StackProtectReq))
209 else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
210 Attribute::StackProtectStrong))
212 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
213 Attribute::StackProtect))
216 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
219 for (BasicBlock::iterator
220 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
221 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
222 if (AI->isArrayAllocation()) {
223 // SSP-Strong: Enable protectors for any call to alloca, regardless
228 if (const ConstantInt *CI =
229 dyn_cast<ConstantInt>(AI->getArraySize())) {
230 unsigned BufferSize = TLI->getTargetMachine().Options.SSPBufferSize;
231 if (CI->getLimitedValue(BufferSize) >= BufferSize)
232 // A call to alloca with size >= SSPBufferSize requires
235 } else // A call to alloca with a variable size requires protectors.
239 if (ContainsProtectableArray(AI->getAllocatedType(), Strong))
242 if (Strong && HasAddressTaken(AI)) {
253 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
256 /// - The prologue code loads and stores the stack guard onto the stack.
257 /// - The epilogue checks the value stored in the prologue against the original
258 /// value. It calls __stack_chk_fail if they differ.
259 bool StackProtector::InsertStackProtectors() {
260 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
261 BasicBlock *FailBBDom = 0; // FailBB's dominator.
262 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
263 Value *StackGuardVar = 0; // The stack guard variable.
265 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
266 BasicBlock *BB = I++;
267 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
271 // Insert code into the entry block that stores the __stack_chk_guard
272 // variable onto the stack:
275 // StackGuardSlot = alloca i8*
276 // StackGuard = load __stack_chk_guard
277 // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
279 PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
280 unsigned AddressSpace, Offset;
281 if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
282 Constant *OffsetVal =
283 ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
285 StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
286 PointerType::get(PtrTy, AddressSpace));
288 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
291 BasicBlock &Entry = F->getEntryBlock();
292 Instruction *InsPt = &Entry.front();
294 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
295 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
297 Value *Args[] = { LI, AI };
299 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
302 // Create the basic block to jump to when the guard check fails.
303 FailBB = CreateFailBB();
306 // For each block with a return instruction, convert this:
316 // %1 = load __stack_chk_guard
317 // %2 = load StackGuardSlot
318 // %3 = cmp i1 %1, %2
319 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
324 // CallStackCheckFailBlk:
325 // call void @__stack_chk_fail()
328 // Split the basic block before the return instruction.
329 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
331 if (DT && DT->isReachableFromEntry(BB)) {
332 DT->addNewBlock(NewBB, BB);
333 FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;
336 // Remove default branch instruction to the new BB.
337 BB->getTerminator()->eraseFromParent();
339 // Move the newly created basic block to the point right after the old basic
340 // block so that it's in the "fall through" position.
341 NewBB->moveAfter(BB);
343 // Generate the stack protector instructions in the old basic block.
344 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
345 LoadInst *LI2 = new LoadInst(AI, "", true, BB);
346 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
347 BranchInst::Create(NewBB, FailBB, Cmp, BB);
350 // Return if we didn't modify any basic blocks. I.e., there are no return
351 // statements in the function.
352 if (!FailBB) return false;
355 DT->addNewBlock(FailBB, FailBBDom);
360 /// CreateFailBB - Create a basic block to jump to when the stack protector
362 BasicBlock *StackProtector::CreateFailBB() {
363 BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
364 "CallStackCheckFailBlk", F);
365 Constant *StackChkFail =
366 M->getOrInsertFunction("__stack_chk_fail",
367 Type::getVoidTy(F->getContext()), NULL);
368 CallInst::Create(StackChkFail, "", FailBB);
369 new UnreachableInst(F->getContext(), FailBB);