StackProtector.cpp revision b0bc6c361da9009e8414efde317d9bbff755f6c0
1//===-- 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// 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. 14// 15//===----------------------------------------------------------------------===// 16 17#define DEBUG_TYPE "stack-protector" 18#include "llvm/CodeGen/Passes.h" 19#include "llvm/Attributes.h" 20#include "llvm/Constants.h" 21#include "llvm/DerivedTypes.h" 22#include "llvm/Function.h" 23#include "llvm/Instructions.h" 24#include "llvm/Intrinsics.h" 25#include "llvm/Module.h" 26#include "llvm/Pass.h" 27#include "llvm/Support/CommandLine.h" 28#include "llvm/Target/TargetData.h" 29#include "llvm/Target/TargetLowering.h" 30using namespace llvm; 31 32// SSPBufferSize - The lower bound for a buffer to be considered for stack 33// smashing protection. 34static cl::opt<unsigned> 35SSPBufferSize("stack-protector-buffer-size", cl::init(8), 36 cl::desc("Lower bound for a buffer to be considered for " 37 "stack protection")); 38 39namespace { 40 class StackProtector : public FunctionPass { 41 /// TLI - Keep a pointer of a TargetLowering to consult for determining 42 /// target type sizes. 43 const TargetLowering *TLI; 44 45 Function *F; 46 Module *M; 47 48 /// InsertStackProtectors - Insert code into the prologue and epilogue of 49 /// the function. 50 /// 51 /// - The prologue code loads and stores the stack guard onto the stack. 52 /// - The epilogue checks the value stored in the prologue against the 53 /// original value. It calls __stack_chk_fail if they differ. 54 bool InsertStackProtectors(); 55 56 /// CreateFailBB - Create a basic block to jump to when the stack protector 57 /// check fails. 58 BasicBlock *CreateFailBB(); 59 60 /// RequiresStackProtector - Check whether or not this function needs a 61 /// stack protector based upon the stack protector level. 62 bool RequiresStackProtector() const; 63 public: 64 static char ID; // Pass identification, replacement for typeid. 65 StackProtector() : FunctionPass(&ID), TLI(0) {} 66 StackProtector(const TargetLowering *tli) 67 : FunctionPass(&ID), TLI(tli) {} 68 69 virtual bool runOnFunction(Function &Fn); 70 }; 71} // end anonymous namespace 72 73char StackProtector::ID = 0; 74static RegisterPass<StackProtector> 75X("stack-protector", "Insert stack protectors"); 76 77FunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) { 78 return new StackProtector(tli); 79} 80 81bool StackProtector::runOnFunction(Function &Fn) { 82 F = &Fn; 83 M = F->getParent(); 84 85 if (!RequiresStackProtector()) return false; 86 87 return InsertStackProtectors(); 88} 89 90/// RequiresStackProtector - Check whether or not this function needs a stack 91/// protector based upon the stack protector level. The heuristic we use is to 92/// add a guard variable to functions that call alloca, and functions with 93/// buffers larger than SSPBufferSize bytes. 94bool StackProtector::RequiresStackProtector() const { 95 if (F->hasFnAttr(Attribute::StackProtectReq)) 96 return true; 97 98 if (!F->hasFnAttr(Attribute::StackProtect)) 99 return false; 100 101 const TargetData *TD = TLI->getTargetData(); 102 103 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) { 104 BasicBlock *BB = I; 105 106 for (BasicBlock::iterator 107 II = BB->begin(), IE = BB->end(); II != IE; ++II) 108 if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) { 109 if (AI->isArrayAllocation()) 110 // This is a call to alloca with a variable size. Emit stack 111 // protectors. 112 return true; 113 114 if (const ArrayType *AT = dyn_cast<ArrayType>(AI->getAllocatedType())) { 115 // We apparently only care about character arrays. 116 if (!AT->getElementType()->isIntegerTy(8)) 117 continue; 118 119 // If an array has more than SSPBufferSize bytes of allocated space, 120 // then we emit stack protectors. 121 if (SSPBufferSize <= TD->getTypeAllocSize(AT)) 122 return true; 123 } 124 } 125 } 126 127 return false; 128} 129 130/// InsertStackProtectors - Insert code into the prologue and epilogue of the 131/// function. 132/// 133/// - The prologue code loads and stores the stack guard onto the stack. 134/// - The epilogue checks the value stored in the prologue against the original 135/// value. It calls __stack_chk_fail if they differ. 136bool StackProtector::InsertStackProtectors() { 137 BasicBlock *FailBB = 0; // The basic block to jump to if check fails. 138 AllocaInst *AI = 0; // Place on stack that stores the stack guard. 139 Constant *StackGuardVar = 0; // The stack guard variable. 140 141 for (Function::iterator I = F->begin(), E = F->end(); I != E; ) { 142 BasicBlock *BB = I++; 143 144 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); 145 if (!RI) continue; 146 147 if (!FailBB) { 148 // Insert code into the entry block that stores the __stack_chk_guard 149 // variable onto the stack: 150 // 151 // entry: 152 // StackGuardSlot = alloca i8* 153 // StackGuard = load __stack_chk_guard 154 // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot) 155 // 156 PointerType *PtrTy = PointerType::getUnqual( 157 Type::getInt8Ty(RI->getContext())); 158 StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy); 159 160 BasicBlock &Entry = F->getEntryBlock(); 161 Instruction *InsPt = &Entry.front(); 162 163 AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt); 164 LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt); 165 166 Value *Args[] = { LI, AI }; 167 CallInst:: 168 Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), 169 &Args[0], array_endof(Args), "", InsPt); 170 171 // Create the basic block to jump to when the guard check fails. 172 FailBB = CreateFailBB(); 173 } 174 175 // For each block with a return instruction, convert this: 176 // 177 // return: 178 // ... 179 // ret ... 180 // 181 // into this: 182 // 183 // return: 184 // ... 185 // %1 = load __stack_chk_guard 186 // %2 = load StackGuardSlot 187 // %3 = cmp i1 %1, %2 188 // br i1 %3, label %SP_return, label %CallStackCheckFailBlk 189 // 190 // SP_return: 191 // ret ... 192 // 193 // CallStackCheckFailBlk: 194 // call void @__stack_chk_fail() 195 // unreachable 196 197 // Split the basic block before the return instruction. 198 BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return"); 199 200 // Remove default branch instruction to the new BB. 201 BB->getTerminator()->eraseFromParent(); 202 203 // Move the newly created basic block to the point right after the old basic 204 // block so that it's in the "fall through" position. 205 NewBB->moveAfter(BB); 206 207 // Generate the stack protector instructions in the old basic block. 208 LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB); 209 LoadInst *LI2 = new LoadInst(AI, "", true, BB); 210 ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, ""); 211 BranchInst::Create(NewBB, FailBB, Cmp, BB); 212 } 213 214 // Return if we didn't modify any basic blocks. I.e., there are no return 215 // statements in the function. 216 if (!FailBB) return false; 217 218 return true; 219} 220 221/// CreateFailBB - Create a basic block to jump to when the stack protector 222/// check fails. 223BasicBlock *StackProtector::CreateFailBB() { 224 BasicBlock *FailBB = BasicBlock::Create(F->getContext(), 225 "CallStackCheckFailBlk", F); 226 Constant *StackChkFail = 227 M->getOrInsertFunction("__stack_chk_fail", 228 Type::getVoidTy(F->getContext()), NULL); 229 CallInst::Create(StackChkFail, "", FailBB); 230 new UnreachableInst(F->getContext(), FailBB); 231 return FailBB; 232} 233