StackProtector.cpp 18 KB

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