StackProtector.cpp 18 KB

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