StackProtector.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/ADT/Triple.h"
  21. #include "llvm/Analysis/Dominators.h"
  22. #include "llvm/IR/Attributes.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/DerivedTypes.h"
  26. #include "llvm/IR/Function.h"
  27. #include "llvm/IR/Instructions.h"
  28. #include "llvm/IR/Intrinsics.h"
  29. #include "llvm/IR/Module.h"
  30. #include "llvm/Pass.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Target/TargetLowering.h"
  33. using namespace llvm;
  34. STATISTIC(NumFunProtected, "Number of functions protected");
  35. STATISTIC(NumAddrTaken, "Number of local variables that have their address"
  36. " taken.");
  37. namespace {
  38. class StackProtector : public FunctionPass {
  39. /// TLI - Keep a pointer of a TargetLowering to consult for determining
  40. /// target type sizes.
  41. const TargetLoweringBase *TLI;
  42. Function *F;
  43. Module *M;
  44. DominatorTree *DT;
  45. /// VisitedPHIs - The set of PHI nodes visited when determining
  46. /// if a variable's reference has been taken. This set
  47. /// is maintained to ensure we don't visit the same PHI node multiple
  48. /// times.
  49. SmallPtrSet<const PHINode*, 16> VisitedPHIs;
  50. /// InsertStackProtectors - Insert code into the prologue and epilogue of
  51. /// the function.
  52. ///
  53. /// - The prologue code loads and stores the stack guard onto the stack.
  54. /// - The epilogue checks the value stored in the prologue against the
  55. /// original value. It calls __stack_chk_fail if they differ.
  56. bool InsertStackProtectors();
  57. /// CreateFailBB - Create a basic block to jump to when the stack protector
  58. /// check fails.
  59. BasicBlock *CreateFailBB();
  60. /// ContainsProtectableArray - Check whether the type either is an array or
  61. /// contains an array of sufficient size so that we need stack protectors
  62. /// for it.
  63. bool ContainsProtectableArray(Type *Ty, bool Strong = false,
  64. bool InStruct = false) const;
  65. /// \brief Check whether a stack allocation has its address taken.
  66. bool HasAddressTaken(const Instruction *AI);
  67. /// RequiresStackProtector - Check whether or not this function needs a
  68. /// stack protector based upon the stack protector level.
  69. bool RequiresStackProtector();
  70. public:
  71. static char ID; // Pass identification, replacement for typeid.
  72. StackProtector() : FunctionPass(ID), TLI(0) {
  73. initializeStackProtectorPass(*PassRegistry::getPassRegistry());
  74. }
  75. StackProtector(const TargetLoweringBase *tli)
  76. : FunctionPass(ID), TLI(tli) {
  77. initializeStackProtectorPass(*PassRegistry::getPassRegistry());
  78. }
  79. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  80. AU.addPreserved<DominatorTree>();
  81. }
  82. virtual bool runOnFunction(Function &Fn);
  83. };
  84. } // end anonymous namespace
  85. char StackProtector::ID = 0;
  86. INITIALIZE_PASS(StackProtector, "stack-protector",
  87. "Insert stack protectors", false, false)
  88. FunctionPass *llvm::createStackProtectorPass(const TargetLoweringBase *tli) {
  89. return new StackProtector(tli);
  90. }
  91. bool StackProtector::runOnFunction(Function &Fn) {
  92. F = &Fn;
  93. M = F->getParent();
  94. DT = getAnalysisIfAvailable<DominatorTree>();
  95. if (!RequiresStackProtector()) return false;
  96. ++NumFunProtected;
  97. return InsertStackProtectors();
  98. }
  99. /// ContainsProtectableArray - Check whether the type either is an array or
  100. /// contains a char array of sufficient size so that we need stack protectors
  101. /// for it.
  102. bool StackProtector::ContainsProtectableArray(Type *Ty, bool Strong,
  103. bool InStruct) const {
  104. if (!Ty) return false;
  105. if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  106. // In strong mode any array, regardless of type and size, triggers a
  107. // protector
  108. if (Strong)
  109. return true;
  110. const TargetMachine &TM = TLI->getTargetMachine();
  111. if (!AT->getElementType()->isIntegerTy(8)) {
  112. Triple Trip(TM.getTargetTriple());
  113. // If we're on a non-Darwin platform or we're inside of a structure, don't
  114. // add stack protectors unless the array is a character array.
  115. if (InStruct || !Trip.isOSDarwin())
  116. return false;
  117. }
  118. // If an array has more than SSPBufferSize bytes of allocated space, then we
  119. // emit stack protectors.
  120. if (TM.Options.SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT))
  121. return true;
  122. }
  123. const StructType *ST = dyn_cast<StructType>(Ty);
  124. if (!ST) return false;
  125. for (StructType::element_iterator I = ST->element_begin(),
  126. E = ST->element_end(); I != E; ++I)
  127. if (ContainsProtectableArray(*I, Strong, true))
  128. return true;
  129. return false;
  130. }
  131. bool StackProtector::HasAddressTaken(const Instruction *AI) {
  132. for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
  133. UI != UE; ++UI) {
  134. const User *U = *UI;
  135. if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
  136. if (AI == SI->getValueOperand())
  137. return true;
  138. } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
  139. if (AI == SI->getOperand(0))
  140. return true;
  141. } else if (isa<CallInst>(U)) {
  142. return true;
  143. } else if (isa<InvokeInst>(U)) {
  144. return true;
  145. } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
  146. if (HasAddressTaken(SI))
  147. return true;
  148. } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
  149. // Keep track of what PHI nodes we have already visited to ensure
  150. // they are only visited once.
  151. if (VisitedPHIs.insert(PN))
  152. if (HasAddressTaken(PN))
  153. return true;
  154. } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  155. if (HasAddressTaken(GEP))
  156. return true;
  157. } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
  158. if (HasAddressTaken(BI))
  159. return true;
  160. }
  161. }
  162. return false;
  163. }
  164. /// \brief Check whether or not this function needs a stack protector based
  165. /// upon the stack protector level.
  166. ///
  167. /// We use two heuristics: a standard (ssp) and strong (sspstrong).
  168. /// The standard heuristic which will add a guard variable to functions that
  169. /// call alloca with a either a variable size or a size >= SSPBufferSize,
  170. /// functions with character buffers larger than SSPBufferSize, and functions
  171. /// with aggregates containing character buffers larger than SSPBufferSize. The
  172. /// strong heuristic will add a guard variables to functions that call alloca
  173. /// regardless of size, functions with any buffer regardless of type and size,
  174. /// functions with aggregates that contain any buffer regardless of type and
  175. /// size, and functions that contain stack-based variables that have had their
  176. /// address taken.
  177. bool StackProtector::RequiresStackProtector() {
  178. bool Strong = false;
  179. if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  180. Attribute::StackProtectReq))
  181. return true;
  182. else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  183. Attribute::StackProtectStrong))
  184. Strong = true;
  185. else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  186. Attribute::StackProtect))
  187. return false;
  188. for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
  189. BasicBlock *BB = I;
  190. for (BasicBlock::iterator
  191. II = BB->begin(), IE = BB->end(); II != IE; ++II) {
  192. if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
  193. if (AI->isArrayAllocation()) {
  194. // SSP-Strong: Enable protectors for any call to alloca, regardless
  195. // of size.
  196. if (Strong)
  197. return true;
  198. if (const ConstantInt *CI =
  199. dyn_cast<ConstantInt>(AI->getArraySize())) {
  200. unsigned BufferSize = TLI->getTargetMachine().Options.SSPBufferSize;
  201. if (CI->getLimitedValue(BufferSize) >= BufferSize)
  202. // A call to alloca with size >= SSPBufferSize requires
  203. // stack protectors.
  204. return true;
  205. } else // A call to alloca with a variable size requires protectors.
  206. return true;
  207. }
  208. if (ContainsProtectableArray(AI->getAllocatedType(), Strong))
  209. return true;
  210. if (Strong && HasAddressTaken(AI)) {
  211. ++NumAddrTaken;
  212. return true;
  213. }
  214. }
  215. }
  216. }
  217. return false;
  218. }
  219. /// InsertStackProtectors - Insert code into the prologue and epilogue of the
  220. /// function.
  221. ///
  222. /// - The prologue code loads and stores the stack guard onto the stack.
  223. /// - The epilogue checks the value stored in the prologue against the original
  224. /// value. It calls __stack_chk_fail if they differ.
  225. bool StackProtector::InsertStackProtectors() {
  226. BasicBlock *FailBB = 0; // The basic block to jump to if check fails.
  227. BasicBlock *FailBBDom = 0; // FailBB's dominator.
  228. AllocaInst *AI = 0; // Place on stack that stores the stack guard.
  229. Value *StackGuardVar = 0; // The stack guard variable.
  230. for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
  231. BasicBlock *BB = I++;
  232. ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
  233. if (!RI) continue;
  234. if (!FailBB) {
  235. // Insert code into the entry block that stores the __stack_chk_guard
  236. // variable onto the stack:
  237. //
  238. // entry:
  239. // StackGuardSlot = alloca i8*
  240. // StackGuard = load __stack_chk_guard
  241. // call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
  242. //
  243. PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
  244. unsigned AddressSpace, Offset;
  245. if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
  246. Constant *OffsetVal =
  247. ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
  248. StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
  249. PointerType::get(PtrTy, AddressSpace));
  250. } else {
  251. StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
  252. }
  253. BasicBlock &Entry = F->getEntryBlock();
  254. Instruction *InsPt = &Entry.front();
  255. AI = new AllocaInst(PtrTy, "StackGuardSlot", InsPt);
  256. LoadInst *LI = new LoadInst(StackGuardVar, "StackGuard", false, InsPt);
  257. Value *Args[] = { LI, AI };
  258. CallInst::
  259. Create(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
  260. Args, "", InsPt);
  261. // Create the basic block to jump to when the guard check fails.
  262. FailBB = CreateFailBB();
  263. }
  264. // For each block with a return instruction, convert this:
  265. //
  266. // return:
  267. // ...
  268. // ret ...
  269. //
  270. // into this:
  271. //
  272. // return:
  273. // ...
  274. // %1 = load __stack_chk_guard
  275. // %2 = load StackGuardSlot
  276. // %3 = cmp i1 %1, %2
  277. // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
  278. //
  279. // SP_return:
  280. // ret ...
  281. //
  282. // CallStackCheckFailBlk:
  283. // call void @__stack_chk_fail()
  284. // unreachable
  285. // Split the basic block before the return instruction.
  286. BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
  287. if (DT && DT->isReachableFromEntry(BB)) {
  288. DT->addNewBlock(NewBB, BB);
  289. FailBBDom = FailBBDom ? DT->findNearestCommonDominator(FailBBDom, BB) :BB;
  290. }
  291. // Remove default branch instruction to the new BB.
  292. BB->getTerminator()->eraseFromParent();
  293. // Move the newly created basic block to the point right after the old basic
  294. // block so that it's in the "fall through" position.
  295. NewBB->moveAfter(BB);
  296. // Generate the stack protector instructions in the old basic block.
  297. LoadInst *LI1 = new LoadInst(StackGuardVar, "", false, BB);
  298. LoadInst *LI2 = new LoadInst(AI, "", true, BB);
  299. ICmpInst *Cmp = new ICmpInst(*BB, CmpInst::ICMP_EQ, LI1, LI2, "");
  300. BranchInst::Create(NewBB, FailBB, Cmp, BB);
  301. }
  302. // Return if we didn't modify any basic blocks. I.e., there are no return
  303. // statements in the function.
  304. if (!FailBB) return false;
  305. if (DT && FailBBDom)
  306. DT->addNewBlock(FailBB, FailBBDom);
  307. return true;
  308. }
  309. /// CreateFailBB - Create a basic block to jump to when the stack protector
  310. /// check fails.
  311. BasicBlock *StackProtector::CreateFailBB() {
  312. BasicBlock *FailBB = BasicBlock::Create(F->getContext(),
  313. "CallStackCheckFailBlk", F);
  314. Constant *StackChkFail =
  315. M->getOrInsertFunction("__stack_chk_fail",
  316. Type::getVoidTy(F->getContext()), NULL);
  317. CallInst::Create(StackChkFail, "", FailBB);
  318. new UnreachableInst(F->getContext(), FailBB);
  319. return FailBB;
  320. }