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