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/GlobalValue.h"
29 #include "llvm/IR/GlobalVariable.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Target/TargetLowering.h"
39 STATISTIC(NumFunProtected, "Number of functions protected");
40 STATISTIC(NumAddrTaken, "Number of local variables that have their address"
44 class StackProtector : public FunctionPass {
45 const TargetMachine *TM;
47 /// TLI - Keep a pointer of a TargetLowering to consult for determining
48 /// target type sizes.
49 const TargetLoweringBase *TLI;
57 /// \brief The minimum size of buffers that will receive stack smashing
58 /// protection when -fstack-protection is used.
59 unsigned SSPBufferSize;
61 /// VisitedPHIs - The set of PHI nodes visited when determining
62 /// if a variable's reference has been taken. This set
63 /// is maintained to ensure we don't visit the same PHI node multiple
65 SmallPtrSet<const PHINode*, 16> VisitedPHIs;
67 /// InsertStackProtectors - Insert code into the prologue and epilogue of
70 /// - The prologue code loads and stores the stack guard onto the stack.
71 /// - The epilogue checks the value stored in the prologue against the
72 /// original value. It calls __stack_chk_fail if they differ.
73 bool InsertStackProtectors();
75 /// CreateFailBB - Create a basic block to jump to when the stack protector
77 BasicBlock *CreateFailBB();
79 /// ContainsProtectableArray - Check whether the type either is an array or
80 /// contains an array of sufficient size so that we need stack protectors
82 bool ContainsProtectableArray(Type *Ty, bool Strong = false,
83 bool InStruct = false) const;
85 /// \brief Check whether a stack allocation has its address taken.
86 bool HasAddressTaken(const Instruction *AI);
88 /// RequiresStackProtector - Check whether or not this function needs a
89 /// stack protector based upon the stack protector level.
90 bool RequiresStackProtector();
92 static char ID; // Pass identification, replacement for typeid.
93 StackProtector() : FunctionPass(ID), TM(0), TLI(0), SSPBufferSize(0) {
94 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
96 StackProtector(const TargetMachine *TM)
97 : FunctionPass(ID), TM(TM), TLI(0), Trip(TM->getTargetTriple()),
99 initializeStackProtectorPass(*PassRegistry::getPassRegistry());
102 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
103 AU.addPreserved<DominatorTree>();
106 virtual bool runOnFunction(Function &Fn);
108 } // end anonymous namespace
110 char StackProtector::ID = 0;
111 INITIALIZE_PASS(StackProtector, "stack-protector",
112 "Insert stack protectors", false, false)
114 FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
115 return new StackProtector(TM);
118 bool StackProtector::runOnFunction(Function &Fn) {
121 DT = getAnalysisIfAvailable<DominatorTree>();
122 TLI = TM->getTargetLowering();
124 if (!RequiresStackProtector()) return false;
127 Fn.getAttributes().getAttribute(AttributeSet::FunctionIndex,
128 "stack-protector-buffer-size");
129 if (Attr.isStringAttribute())
130 SSPBufferSize = atoi(Attr.getValueAsString().data());
133 return InsertStackProtectors();
136 /// ContainsProtectableArray - Check whether the type either is an array or
137 /// contains a char array of sufficient size so that we need stack protectors
139 bool StackProtector::ContainsProtectableArray(Type *Ty, bool Strong,
140 bool InStruct) const {
141 if (!Ty) return false;
142 if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
143 // In strong mode any array, regardless of type and size, triggers a
147 if (!AT->getElementType()->isIntegerTy(8)) {
148 // If we're on a non-Darwin platform or we're inside of a structure, don't
149 // add stack protectors unless the array is a character array.
150 if (InStruct || !Trip.isOSDarwin())
154 // If an array has more than SSPBufferSize bytes of allocated space, then we
155 // emit stack protectors.
156 if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT))
160 const StructType *ST = dyn_cast<StructType>(Ty);
161 if (!ST) return false;
163 for (StructType::element_iterator I = ST->element_begin(),
164 E = ST->element_end(); I != E; ++I)
165 if (ContainsProtectableArray(*I, Strong, true))
171 bool StackProtector::HasAddressTaken(const Instruction *AI) {
172 for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
175 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
176 if (AI == SI->getValueOperand())
178 } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
179 if (AI == SI->getOperand(0))
181 } else if (isa<CallInst>(U)) {
183 } else if (isa<InvokeInst>(U)) {
185 } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
186 if (HasAddressTaken(SI))
188 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
189 // Keep track of what PHI nodes we have already visited to ensure
190 // they are only visited once.
191 if (VisitedPHIs.insert(PN))
192 if (HasAddressTaken(PN))
194 } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
195 if (HasAddressTaken(GEP))
197 } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
198 if (HasAddressTaken(BI))
205 /// \brief Check whether or not this function needs a stack protector based
206 /// upon the stack protector level.
208 /// We use two heuristics: a standard (ssp) and strong (sspstrong).
209 /// The standard heuristic which will add a guard variable to functions that
210 /// call alloca with a either a variable size or a size >= SSPBufferSize,
211 /// functions with character buffers larger than SSPBufferSize, and functions
212 /// with aggregates containing character buffers larger than SSPBufferSize. The
213 /// strong heuristic will add a guard variables to functions that call alloca
214 /// regardless of size, functions with any buffer regardless of type and size,
215 /// functions with aggregates that contain any buffer regardless of type and
216 /// size, and functions that contain stack-based variables that have had their
218 bool StackProtector::RequiresStackProtector() {
220 if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
221 Attribute::StackProtectReq))
223 else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
224 Attribute::StackProtectStrong))
226 else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
227 Attribute::StackProtect))
230 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
233 for (BasicBlock::iterator
234 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
235 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
236 if (AI->isArrayAllocation()) {
237 // SSP-Strong: Enable protectors for any call to alloca, regardless
242 if (const ConstantInt *CI =
243 dyn_cast<ConstantInt>(AI->getArraySize())) {
244 if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize)
245 // A call to alloca with size >= SSPBufferSize requires
249 // A call to alloca with a variable size requires protectors.
254 if (ContainsProtectableArray(AI->getAllocatedType(), Strong))
257 if (Strong && HasAddressTaken(AI)) {
268 /// Insert code into the entry block that stores the __stack_chk_guard
269 /// variable onto the stack:
272 /// StackGuardSlot = alloca i8*
273 /// StackGuard = load __stack_chk_guard
274 /// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
276 static void CreatePrologue(Function *F, Module *M, ReturnInst *RI,
277 const TargetLoweringBase *TLI, const Triple &Trip,
278 AllocaInst *&AI, Value *&StackGuardVar) {
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,
288 } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
289 StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
290 cast<GlobalValue>(StackGuardVar)
291 ->setVisibility(GlobalValue::HiddenVisibility);
293 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
296 BasicBlock &Entry = F->getEntryBlock();
297 Instruction *InsPt = &Entry.front();
299 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
300 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
302 Value *Args[] = { LI, AI };
304 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
308 /// InsertStackProtectors - Insert code into the prologue and epilogue of the
311 /// - The prologue code loads and stores the stack guard onto the stack.
312 /// - The epilogue checks the value stored in the prologue against the original
313 /// value. It calls __stack_chk_fail if they differ.
314 bool StackProtector::InsertStackProtectors() {
315 BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
316 BasicBlock *FailBBDom = 0; // FailBB's dominator.
317 AllocaInst *AI = 0; // Place on stack that stores the stack guard.
318 Value *StackGuardVar = 0; // The stack guard variable.
320 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
321 BasicBlock *BB = I++;
322 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
326 CreatePrologue(F, M, RI, TLI, Trip, AI, StackGuardVar);
327 // Create the basic block to jump to when the guard check fails.
328 FailBB = CreateFailBB();
331 // For each block with a return instruction, convert this:
341 // %1 = load __stack_chk_guard
342 // %2 = load StackGuardSlot
343 // %3 = cmp i1 %1, %2
344 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
349 // CallStackCheckFailBlk:
350 // call void @__stack_chk_fail()
353 // Split the basic block before the return instruction.
354 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
356 if (DT && DT->isReachableFromEntry(BB)) {
357 DT->addNewBlock(NewBB, BB);
358 FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;
361 // Remove default branch instruction to the new BB.
362 BB->getTerminator()->eraseFromParent();
364 // Move the newly created basic block to the point right after the old basic
365 // block so that it's in the "fall through" position.
366 NewBB->moveAfter(BB);
368 // Generate the stack protector instructions in the old basic block.
369 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
370 LoadInst *LI2 = new LoadInst(AI, "", true, BB);
371 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
372 BranchInst::Create(NewBB, FailBB, Cmp, BB);
375 // Return if we didn't modify any basic blocks. I.e., there are no return
376 // statements in the function.
377 if (!FailBB) return false;
380 DT->addNewBlock(FailBB, FailBBDom);
385 /// CreateFailBB - Create a basic block to jump to when the stack protector
387 BasicBlock *StackProtector::CreateFailBB() {
388 LLVMContext &Context = F->getContext();
389 BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
390 if (Trip.getOS() == llvm::Triple::OpenBSD) {
391 Constant *StackChkFail = M->getOrInsertFunction(
392 "__stack_smash_handler", Type::getVoidTy(Context),
393 Type::getInt8PtrTy(Context), NULL);
395 Constant *NameStr = ConstantDataArray::getString(Context, F->getName());
397 new GlobalVariable(*M, NameStr->getType(), true,
398 GlobalVariable::PrivateLinkage, NameStr, "SSH");
400 SmallVector<Constant *, 2> IdxList;
401 IdxList.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
402 IdxList.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
404 SmallVector<Value *, 1> Args;
405 Args.push_back(ConstantExpr::getGetElementPtr(FuncName, IdxList));
407 CallInst::Create(StackChkFail, Args, "", FailBB);
409 Constant *StackChkFail = M->getOrInsertFunction(
410 "__stack_chk_fail", Type::getVoidTy(Context), NULL);
411 CallInst::Create(StackChkFail, "", FailBB);
413 new UnreachableInst(Context, FailBB);