StackProtector.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. #define DEBUG_TYPE "stack-protector"
  17. #include "llvm/CodeGen/Passes.h"
  18. #include "llvm/Analysis/Dominators.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"
  30. #include "llvm/ADT/Triple.h"
  31. using namespace llvm;
  32. // SSPBufferSize - The lower bound for a buffer to be considered for stack
  33. // smashing protection.
  34. static cl::opt<unsigned>
  35. SSPBufferSize("stack-protector-buffer-size", cl::init(8),
  36. cl::desc("Lower bound for a buffer to be considered for "
  37. "stack protection"));
  38. namespace {
  39. class StackProtector : public FunctionPass {
  40. /// TLI - Keep a pointer of a TargetLowering to consult for determining
  41. /// target type sizes.
  42. const TargetLowering *TLI;
  43. Function *F;
  44. Module *M;
  45. DominatorTree *DT;
  46. /// InsertStackProtectors - Insert code into the prologue and epilogue of
  47. /// the function.
  48. ///
  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();
  53. /// CreateFailBB - Create a basic block to jump to when the stack protector
  54. /// check fails.
  55. BasicBlock *CreateFailBB();
  56. /// ContainsProtectableArray - Check whether the type either is an array or
  57. /// contains an array of sufficient size so that we need stack protectors
  58. /// for it.
  59. bool ContainsProtectableArray(Type *Ty, bool InStruct = false) const;
  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. initializeStackProtectorPass(*PassRegistry::getPassRegistry());
  67. }
  68. StackProtector(const TargetLowering *tli)
  69. : FunctionPass(ID), TLI(tli) {
  70. initializeStackProtectorPass(*PassRegistry::getPassRegistry());
  71. }
  72. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  73. AU.addPreserved<DominatorTree>();
  74. }
  75. virtual bool runOnFunction(Function &Fn);
  76. };
  77. } // end anonymous namespace
  78. char StackProtector::ID = 0;
  79. INITIALIZE_PASS(StackProtector, "stack-protector",
  80. "Insert stack protectors", false, false)
  81. FunctionPass *llvm::createStackProtectorPass(const TargetLowering *tli) {
  82. return new StackProtector(tli);
  83. }
  84. bool StackProtector::runOnFunction(Function &Fn) {
  85. F = &Fn;
  86. M = F->getParent();
  87. DT = getAnalysisIfAvailable<DominatorTree>();
  88. if (!RequiresStackProtector()) return false;
  89. return InsertStackProtectors();
  90. }
  91. /// ContainsProtectableArray - Check whether the type either is an array or
  92. /// contains a char array of sufficient size so that we need stack protectors
  93. /// for it.
  94. bool StackProtector::ContainsProtectableArray(Type *Ty, bool InStruct) const {
  95. if (!Ty) return false;
  96. if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  97. if (!AT->getElementType()->isIntegerTy(8)) {
  98. const TargetMachine &TM = TLI->getTargetMachine();
  99. Triple Trip(TM.getTargetTriple());
  100. // If we're on a non-Darwin platform or we're inside of a structure, don't
  101. // add stack protectors unless the array is a character array.
  102. if (InStruct || !Trip.isOSDarwin())
  103. return false;
  104. }
  105. // If an array has more than SSPBufferSize bytes of allocated space, then we
  106. // emit stack protectors.
  107. if (SSPBufferSize <= TLI->getTargetData()->getTypeAllocSize(AT))
  108. return true;
  109. }
  110. const StructType *ST = dyn_cast<StructType>(Ty);
  111. if (!ST) return false;
  112. for (StructType::element_iterator I = ST->element_begin(),
  113. E = ST->element_end(); I != E; ++I)
  114. if (ContainsProtectableArray(*I, true))
  115. return true;
  116. return false;
  117. }
  118. /// RequiresStackProtector - Check whether or not this function needs a stack
  119. /// protector based upon the stack protector level. The heuristic we use is to
  120. /// add a guard variable to functions that call alloca, and functions with
  121. /// buffers larger than SSPBufferSize bytes.
  122. bool StackProtector::RequiresStackProtector() const {
  123. if (F->hasFnAttr(Attribute::StackProtectReq))
  124. return true;
  125. if (!F->hasFnAttr(Attribute::StackProtect))
  126. return false;
  127. for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
  128. BasicBlock *BB = I;
  129. for (BasicBlock::iterator
  130. II = BB->begin(), IE = BB->end(); II != IE; ++II)
  131. if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
  132. if (AI->isArrayAllocation())
  133. // This is a call to alloca with a variable size. Emit stack
  134. // protectors.
  135. return true;
  136. if (ContainsProtectableArray(AI->getAllocatedType()))
  137. return true;
  138. }
  139. }
  140. return false;
  141. }
  142. /// InsertStackProtectors - Insert code into the prologue and epilogue of the
  143. /// function.
  144. ///
  145. /// - The prologue code loads and stores the stack guard onto the stack.
  146. /// - The epilogue checks the value stored in the prologue against the original
  147. /// value. It calls __stack_chk_fail if they differ.
  148. bool StackProtector::InsertStackProtectors() {
  149. BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
  150. BasicBlock *FailBBDom = 0; // FailBB's dominator.
  151. AllocaInst *AI = 0; // Place on stack that stores the stack guard.
  152. Value *StackGuardVar = 0; // The stack guard variable.
  153. for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
  154. BasicBlock *BB = I++;
  155. ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
  156. if (!RI) continue;
  157. if (!FailBB) {
  158. // Insert code into the entry block that stores the __stack_chk_guard
  159. // variable onto the stack:
  160. //
  161. // entry:
  162. // StackGuardSlot = alloca i8*
  163. // StackGuard = load __stack_chk_guard
  164. // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
  165. //
  166. PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
  167. unsigned AddressSpace, Offset;
  168. if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
  169. Constant *OffsetVal =
  170. ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
  171. StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
  172. PointerType::get(PtrTy, AddressSpace));
  173. } else {
  174. StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
  175. }
  176. BasicBlock &Entry = F->getEntryBlock();
  177. Instruction *InsPt = &Entry.front();
  178. AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
  179. LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
  180. Value *Args[] = { LI, AI };
  181. CallInst::
  182. Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
  183. Args, "", InsPt);
  184. // Create the basic block to jump to when the guard check fails.
  185. FailBB = CreateFailBB();
  186. }
  187. // For each block with a return instruction, convert this:
  188. //
  189. // return:
  190. // ...
  191. // ret ...
  192. //
  193. // into this:
  194. //
  195. // return:
  196. // ...
  197. // %1 = load __stack_chk_guard
  198. // %2 = load StackGuardSlot
  199. // %3 = cmp i1 %1, %2
  200. // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
  201. //
  202. // SP_return:
  203. // ret ...
  204. //
  205. // CallStackCheckFailBlk:
  206. // call void @__stack_chk_fail()
  207. // unreachable
  208. // Split the basic block before the return instruction.
  209. BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
  210. if (DT && DT->isReachableFromEntry(BB)) {
  211. DT->addNewBlock(NewBB, BB);
  212. FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;
  213. }
  214. // Remove default branch instruction to the new BB.
  215. BB->getTerminator()->eraseFromParent();
  216. // Move the newly created basic block to the point right after the old basic
  217. // block so that it's in the "fall through" position.
  218. NewBB->moveAfter(BB);
  219. // Generate the stack protector instructions in the old basic block.
  220. LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
  221. LoadInst *LI2 = new LoadInst(AI, "", true, BB);
  222. ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
  223. BranchInst::Create(NewBB, FailBB, Cmp, BB);
  224. }
  225. // Return if we didn't modify any basic blocks. I.e., there are no return
  226. // statements in the function.
  227. if (!FailBB) return false;
  228. if (DT && FailBBDom)
  229. DT->addNewBlock(FailBB, FailBBDom);
  230. return true;
  231. }
  232. /// CreateFailBB - Create a basic block to jump to when the stack protector
  233. /// check fails.
  234. BasicBlock *StackProtector::CreateFailBB() {
  235. BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
  236. "CallStackCheckFailBlk", F);
  237. Constant *StackChkFail =
  238. M->getOrInsertFunction("__stack_chk_fail",
  239. Type::getVoidTy(F->getContext()), NULL);
  240. CallInst::Create(StackChkFail, "", FailBB);
  241. new UnreachableInst(F->getContext(), FailBB);
  242. return FailBB;
  243. }