StackProtector.cpp 7.8 KB

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