StackProtector.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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/StackProtector.h"
  18. #include "llvm/CodeGen/Analysis.h"
  19. #include "llvm/CodeGen/Passes.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/Analysis/Dominators.h"
  23. #include "llvm/Analysis/ValueTracking.h"
  24. #include "llvm/IR/Attributes.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/DerivedTypes.h"
  28. #include "llvm/IR/Function.h"
  29. #include "llvm/IR/GlobalValue.h"
  30. #include "llvm/IR/GlobalVariable.h"
  31. #include "llvm/IR/IRBuilder.h"
  32. #include "llvm/IR/Instructions.h"
  33. #include "llvm/IR/IntrinsicInst.h"
  34. #include "llvm/IR/Intrinsics.h"
  35. #include "llvm/IR/Module.h"
  36. #include "llvm/Support/CommandLine.h"
  37. #include <cstdlib>
  38. using namespace llvm;
  39. STATISTIC(NumFunProtected, "Number of functions protected");
  40. STATISTIC(NumAddrTaken, "Number of local variables that have their address"
  41. " taken.");
  42. static cl::opt<bool>
  43. EnableSelectionDAGSP("enable-selectiondag-sp", cl::init(true),
  44. cl::Hidden);
  45. char StackProtector::ID = 0;
  46. INITIALIZE_PASS(StackProtector, "stack-protector",
  47. "Insert stack protectors", false, true)
  48. FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
  49. return new StackProtector(TM);
  50. }
  51. StackProtector::SSPLayoutKind StackProtector::getSSPLayout(const AllocaInst *AI)
  52. const {
  53. return AI ? Layout.lookup(AI) : SSPLK_None;
  54. }
  55. bool StackProtector::runOnFunction(Function &Fn) {
  56. F = &Fn;
  57. M = F->getParent();
  58. DT = getAnalysisIfAvailable<DominatorTree>();
  59. TLI = TM->getTargetLowering();
  60. if (!RequiresStackProtector()) return false;
  61. Attribute Attr =
  62. Fn.getAttributes().getAttribute(AttributeSet::FunctionIndex,
  63. "stack-protector-buffer-size");
  64. if (Attr.isStringAttribute())
  65. Attr.getValueAsString().getAsInteger(10, SSPBufferSize);
  66. ++NumFunProtected;
  67. return InsertStackProtectors();
  68. }
  69. /// \param [out] IsLarge is set to true if a protectable array is found and
  70. /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
  71. /// multiple arrays, this gets set if any of them is large.
  72. bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
  73. bool Strong, bool InStruct)
  74. const {
  75. if (!Ty) return false;
  76. if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  77. if (!AT->getElementType()->isIntegerTy(8)) {
  78. // If we're on a non-Darwin platform or we're inside of a structure, don't
  79. // add stack protectors unless the array is a character array.
  80. // However, in strong mode any array, regardless of type and size,
  81. // triggers a protector.
  82. if (!Strong && (InStruct || !Trip.isOSDarwin()))
  83. return false;
  84. }
  85. // If an array has more than SSPBufferSize bytes of allocated space, then we
  86. // emit stack protectors.
  87. if (SSPBufferSize <= TLI->getDataLayout()->getTypeAllocSize(AT)) {
  88. IsLarge = true;
  89. return true;
  90. }
  91. if (Strong)
  92. // Require a protector for all arrays in strong mode
  93. return true;
  94. }
  95. const StructType *ST = dyn_cast<StructType>(Ty);
  96. if (!ST) return false;
  97. bool NeedsProtector = false;
  98. for (StructType::element_iterator I = ST->element_begin(),
  99. E = ST->element_end(); I != E; ++I)
  100. if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
  101. // If the element is a protectable array and is large (>= SSPBufferSize)
  102. // then we are done. If the protectable array is not large, then
  103. // keep looking in case a subsequent element is a large array.
  104. if (IsLarge)
  105. return true;
  106. NeedsProtector = true;
  107. }
  108. return NeedsProtector;
  109. }
  110. bool StackProtector::HasAddressTaken(const Instruction *AI) {
  111. for (Value::const_use_iterator UI = AI->use_begin(), UE = AI->use_end();
  112. UI != UE; ++UI) {
  113. const User *U = *UI;
  114. if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
  115. if (AI == SI->getValueOperand())
  116. return true;
  117. } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
  118. if (AI == SI->getOperand(0))
  119. return true;
  120. } else if (isa<CallInst>(U)) {
  121. return true;
  122. } else if (isa<InvokeInst>(U)) {
  123. return true;
  124. } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
  125. if (HasAddressTaken(SI))
  126. return true;
  127. } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
  128. // Keep track of what PHI nodes we have already visited to ensure
  129. // they are only visited once.
  130. if (VisitedPHIs.insert(PN))
  131. if (HasAddressTaken(PN))
  132. return true;
  133. } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  134. if (HasAddressTaken(GEP))
  135. return true;
  136. } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
  137. if (HasAddressTaken(BI))
  138. return true;
  139. }
  140. }
  141. return false;
  142. }
  143. /// \brief Check whether or not this function needs a stack protector based
  144. /// upon the stack protector level.
  145. ///
  146. /// We use two heuristics: a standard (ssp) and strong (sspstrong).
  147. /// The standard heuristic which will add a guard variable to functions that
  148. /// call alloca with a either a variable size or a size >= SSPBufferSize,
  149. /// functions with character buffers larger than SSPBufferSize, and functions
  150. /// with aggregates containing character buffers larger than SSPBufferSize. The
  151. /// strong heuristic will add a guard variables to functions that call alloca
  152. /// regardless of size, functions with any buffer regardless of type and size,
  153. /// functions with aggregates that contain any buffer regardless of type and
  154. /// size, and functions that contain stack-based variables that have had their
  155. /// address taken.
  156. bool StackProtector::RequiresStackProtector() {
  157. bool Strong = false;
  158. bool NeedsProtector = false;
  159. if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  160. Attribute::StackProtectReq)) {
  161. NeedsProtector = true;
  162. Strong = true; // Use the same heuristic as strong to determine SSPLayout
  163. } else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  164. Attribute::StackProtectStrong))
  165. Strong = true;
  166. else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  167. Attribute::StackProtect))
  168. return false;
  169. for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
  170. BasicBlock *BB = I;
  171. for (BasicBlock::iterator
  172. II = BB->begin(), IE = BB->end(); II != IE; ++II) {
  173. if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
  174. if (AI->isArrayAllocation()) {
  175. // SSP-Strong: Enable protectors for any call to alloca, regardless
  176. // of size.
  177. if (Strong)
  178. return true;
  179. if (const ConstantInt *CI =
  180. dyn_cast<ConstantInt>(AI->getArraySize())) {
  181. if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
  182. // A call to alloca with size >= SSPBufferSize requires
  183. // stack protectors.
  184. Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
  185. NeedsProtector = true;
  186. } else if (Strong) {
  187. // Require protectors for all alloca calls in strong mode.
  188. Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
  189. NeedsProtector = true;
  190. }
  191. } else {
  192. // A call to alloca with a variable size requires protectors.
  193. Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
  194. NeedsProtector = true;
  195. }
  196. continue;
  197. }
  198. bool IsLarge = false;
  199. if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
  200. Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
  201. : SSPLK_SmallArray));
  202. NeedsProtector = true;
  203. continue;
  204. }
  205. if (Strong && HasAddressTaken(AI)) {
  206. ++NumAddrTaken;
  207. Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
  208. NeedsProtector = true;
  209. }
  210. }
  211. }
  212. }
  213. return NeedsProtector;
  214. }
  215. static bool InstructionWillNotHaveChain(const Instruction *I) {
  216. return !I->mayHaveSideEffects() && !I->mayReadFromMemory() &&
  217. isSafeToSpeculativelyExecute(I);
  218. }
  219. /// Identify if RI has a previous instruction in the "Tail Position" and return
  220. /// it. Otherwise return 0.
  221. ///
  222. /// This is based off of the code in llvm::isInTailCallPosition. The difference
  223. /// is that it inverts the first part of llvm::isInTailCallPosition since
  224. /// isInTailCallPosition is checking if a call is in a tail call position, and
  225. /// we are searching for an unknown tail call that might be in the tail call
  226. /// position. Once we find the call though, the code uses the same refactored
  227. /// code, returnTypeIsEligibleForTailCall.
  228. static CallInst *FindPotentialTailCall(BasicBlock *BB, ReturnInst *RI,
  229. const TargetLoweringBase *TLI) {
  230. // Establish a reasonable upper bound on the maximum amount of instructions we
  231. // will look through to find a tail call.
  232. unsigned SearchCounter = 0;
  233. const unsigned MaxSearch = 4;
  234. bool NoInterposingChain = true;
  235. for (BasicBlock::reverse_iterator I = llvm::next(BB->rbegin()), E = BB->rend();
  236. I != E && SearchCounter < MaxSearch; ++I) {
  237. Instruction *Inst = &*I;
  238. // Skip over debug intrinsics and do not allow them to affect our MaxSearch
  239. // counter.
  240. if (isa<DbgInfoIntrinsic>(Inst))
  241. continue;
  242. // If we find a call and the following conditions are satisifed, then we
  243. // have found a tail call that satisfies at least the target independent
  244. // requirements of a tail call:
  245. //
  246. // 1. The call site has the tail marker.
  247. //
  248. // 2. The call site either will not cause the creation of a chain or if a
  249. // chain is necessary there are no instructions in between the callsite and
  250. // the call which would create an interposing chain.
  251. //
  252. // 3. The return type of the function does not impede tail call
  253. // optimization.
  254. if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
  255. if (CI->isTailCall() &&
  256. (InstructionWillNotHaveChain(CI) || NoInterposingChain) &&
  257. returnTypeIsEligibleForTailCall(BB->getParent(), CI, RI, *TLI))
  258. return CI;
  259. }
  260. // If we did not find a call see if we have an instruction that may create
  261. // an interposing chain.
  262. NoInterposingChain = NoInterposingChain && InstructionWillNotHaveChain(Inst);
  263. // Increment max search.
  264. SearchCounter++;
  265. }
  266. return 0;
  267. }
  268. /// Insert code into the entry block that stores the __stack_chk_guard
  269. /// variable onto the stack:
  270. ///
  271. /// entry:
  272. /// StackGuardSlot = alloca i8*
  273. /// StackGuard = load __stack_chk_guard
  274. /// call void @llvm.stackprotect.create(StackGuard, StackGuardSlot)
  275. ///
  276. /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
  277. /// node.
  278. static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
  279. const TargetLoweringBase *TLI, const Triple &Trip,
  280. AllocaInst *&AI, Value *&StackGuardVar) {
  281. bool SupportsSelectionDAGSP = false;
  282. PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
  283. unsigned AddressSpace, Offset;
  284. if (TLI->getStackCookieLocation(AddressSpace, Offset)) {
  285. Constant *OffsetVal =
  286. ConstantInt::get(Type::getInt32Ty(RI->getContext()), Offset);
  287. StackGuardVar = ConstantExpr::getIntToPtr(OffsetVal,
  288. PointerType::get(PtrTy,
  289. AddressSpace));
  290. } else if (Trip.getOS() == llvm::Triple::OpenBSD) {
  291. StackGuardVar = M->getOrInsertGlobal("__guard_local", PtrTy);
  292. cast<GlobalValue>(StackGuardVar)
  293. ->setVisibility(GlobalValue::HiddenVisibility);
  294. } else {
  295. SupportsSelectionDAGSP = true;
  296. StackGuardVar = M->getOrInsertGlobal("__stack_chk_guard", PtrTy);
  297. }
  298. IRBuilder<> B(&F->getEntryBlock().front());
  299. AI = B.CreateAlloca(PtrTy, 0, "StackGuardSlot");
  300. LoadInst *LI = B.CreateLoad(StackGuardVar, "StackGuard");
  301. B.CreateCall2(Intrinsic::getDeclaration(M, Intrinsic::stackprotector), LI,
  302. AI);
  303. return SupportsSelectionDAGSP;
  304. }
  305. /// InsertStackProtectors - Insert code into the prologue and epilogue of the
  306. /// function.
  307. ///
  308. /// - The prologue code loads and stores the stack guard onto the stack.
  309. /// - The epilogue checks the value stored in the prologue against the original
  310. /// value. It calls __stack_chk_fail if they differ.
  311. bool StackProtector::InsertStackProtectors() {
  312. bool HasPrologue = false;
  313. bool SupportsSelectionDAGSP =
  314. EnableSelectionDAGSP && !TM->Options.EnableFastISel;
  315. AllocaInst *AI = 0; // Place on stack that stores the stack guard.
  316. Value *StackGuardVar = 0; // The stack guard variable.
  317. for (Function::iterator I = F->begin(), E = F->end(); I != E; ) {
  318. BasicBlock *BB = I++;
  319. ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
  320. if (!RI)
  321. continue;
  322. if (!HasPrologue) {
  323. HasPrologue = true;
  324. SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, Trip, AI,
  325. StackGuardVar);
  326. }
  327. if (SupportsSelectionDAGSP) {
  328. // Since we have a potential tail call, insert the special stack check
  329. // intrinsic.
  330. Instruction *InsertionPt = 0;
  331. if (CallInst *CI = FindPotentialTailCall(BB, RI, TLI)) {
  332. InsertionPt = CI;
  333. } else {
  334. InsertionPt = RI;
  335. // At this point we know that BB has a return statement so it *DOES*
  336. // have a terminator.
  337. assert(InsertionPt != 0 && "BB must have a terminator instruction at "
  338. "this point.");
  339. }
  340. Function *Intrinsic =
  341. Intrinsic::getDeclaration(M, Intrinsic::stackprotectorcheck);
  342. CallInst::Create(Intrinsic, StackGuardVar, "", InsertionPt);
  343. } else {
  344. // If we do not support SelectionDAG based tail calls, generate IR level
  345. // tail calls.
  346. //
  347. // For each block with a return instruction, convert this:
  348. //
  349. // return:
  350. // ...
  351. // ret ...
  352. //
  353. // into this:
  354. //
  355. // return:
  356. // ...
  357. // %1 = load __stack_chk_guard
  358. // %2 = load StackGuardSlot
  359. // %3 = cmp i1 %1, %2
  360. // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
  361. //
  362. // SP_return:
  363. // ret ...
  364. //
  365. // CallStackCheckFailBlk:
  366. // call void @__stack_chk_fail()
  367. // unreachable
  368. // Create the FailBB. We duplicate the BB every time since the MI tail
  369. // merge pass will merge together all of the various BB into one including
  370. // fail BB generated by the stack protector pseudo instruction.
  371. BasicBlock *FailBB = CreateFailBB();
  372. // Split the basic block before the return instruction.
  373. BasicBlock *NewBB = BB->splitBasicBlock(RI, "SP_return");
  374. // Update the dominator tree if we need to.
  375. if (DT && DT->isReachableFromEntry(BB)) {
  376. DT->addNewBlock(NewBB, BB);
  377. DT->addNewBlock(FailBB, BB);
  378. }
  379. // Remove default branch instruction to the new BB.
  380. BB->getTerminator()->eraseFromParent();
  381. // Move the newly created basic block to the point right after the old
  382. // basic block so that it's in the "fall through" position.
  383. NewBB->moveAfter(BB);
  384. // Generate the stack protector instructions in the old basic block.
  385. IRBuilder<> B(BB);
  386. LoadInst *LI1 = B.CreateLoad(StackGuardVar);
  387. LoadInst *LI2 = B.CreateLoad(AI);
  388. Value *Cmp = B.CreateICmpEQ(LI1, LI2);
  389. B.CreateCondBr(Cmp, NewBB, FailBB);
  390. }
  391. }
  392. // Return if we didn't modify any basic blocks. I.e., there are no return
  393. // statements in the function.
  394. if (!HasPrologue)
  395. return false;
  396. return true;
  397. }
  398. /// CreateFailBB - Create a basic block to jump to when the stack protector
  399. /// check fails.
  400. BasicBlock *StackProtector::CreateFailBB() {
  401. LLVMContext &Context = F->getContext();
  402. BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
  403. IRBuilder<> B(FailBB);
  404. if (Trip.getOS() == llvm::Triple::OpenBSD) {
  405. Constant *StackChkFail = M->getOrInsertFunction(
  406. "__stack_smash_handler", Type::getVoidTy(Context),
  407. Type::getInt8PtrTy(Context), NULL);
  408. B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
  409. } else {
  410. Constant *StackChkFail = M->getOrInsertFunction(
  411. "__stack_chk_fail", Type::getVoidTy(Context), NULL);
  412. B.CreateCall(StackChkFail);
  413. }
  414. B.CreateUnreachable();
  415. return FailBB;
  416. }