StackProtector.cpp 9.7 KB

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