StackProtector.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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/ADT/SmallPtrSet.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/BranchProbabilityInfo.h"
  19. #include "llvm/Analysis/EHPersonalities.h"
  20. #include "llvm/CodeGen/Passes.h"
  21. #include "llvm/CodeGen/StackProtector.h"
  22. #include "llvm/IR/Attributes.h"
  23. #include "llvm/IR/BasicBlock.h"
  24. #include "llvm/IR/Constants.h"
  25. #include "llvm/IR/DataLayout.h"
  26. #include "llvm/IR/DebugInfo.h"
  27. #include "llvm/IR/DebugLoc.h"
  28. #include "llvm/IR/DerivedTypes.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/IR/IRBuilder.h"
  31. #include "llvm/IR/Instruction.h"
  32. #include "llvm/IR/Instructions.h"
  33. #include "llvm/IR/Intrinsics.h"
  34. #include "llvm/IR/MDBuilder.h"
  35. #include "llvm/IR/Module.h"
  36. #include "llvm/IR/Type.h"
  37. #include "llvm/IR/User.h"
  38. #include "llvm/Pass.h"
  39. #include "llvm/Support/Casting.h"
  40. #include "llvm/Support/CommandLine.h"
  41. #include "llvm/Target/TargetLowering.h"
  42. #include "llvm/Target/TargetMachine.h"
  43. #include "llvm/Target/TargetOptions.h"
  44. #include "llvm/Target/TargetSubtargetInfo.h"
  45. #include <utility>
  46. using namespace llvm;
  47. #define DEBUG_TYPE "stack-protector"
  48. STATISTIC(NumFunProtected, "Number of functions protected");
  49. STATISTIC(NumAddrTaken, "Number of local variables that have their address"
  50. " taken.");
  51. static cl::opt<bool> EnableSelectionDAGSP("enable-selectiondag-sp",
  52. cl::init(true), cl::Hidden);
  53. char StackProtector::ID = 0;
  54. INITIALIZE_TM_PASS(StackProtector, "stack-protector", "Insert stack protectors",
  55. false, true)
  56. FunctionPass *llvm::createStackProtectorPass(const TargetMachine *TM) {
  57. return new StackProtector(TM);
  58. }
  59. StackProtector::SSPLayoutKind
  60. StackProtector::getSSPLayout(const AllocaInst *AI) const {
  61. return AI ? Layout.lookup(AI) : SSPLK_None;
  62. }
  63. void StackProtector::adjustForColoring(const AllocaInst *From,
  64. const AllocaInst *To) {
  65. // When coloring replaces one alloca with another, transfer the SSPLayoutKind
  66. // tag from the remapped to the target alloca. The remapped alloca should
  67. // have a size smaller than or equal to the replacement alloca.
  68. SSPLayoutMap::iterator I = Layout.find(From);
  69. if (I != Layout.end()) {
  70. SSPLayoutKind Kind = I->second;
  71. Layout.erase(I);
  72. // Transfer the tag, but make sure that SSPLK_AddrOf does not overwrite
  73. // SSPLK_SmallArray or SSPLK_LargeArray, and make sure that
  74. // SSPLK_SmallArray does not overwrite SSPLK_LargeArray.
  75. I = Layout.find(To);
  76. if (I == Layout.end())
  77. Layout.insert(std::make_pair(To, Kind));
  78. else if (I->second != SSPLK_LargeArray && Kind != SSPLK_AddrOf)
  79. I->second = Kind;
  80. }
  81. }
  82. bool StackProtector::runOnFunction(Function &Fn) {
  83. F = &Fn;
  84. M = F->getParent();
  85. DominatorTreeWrapperPass *DTWP =
  86. getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  87. DT = DTWP ? &DTWP->getDomTree() : nullptr;
  88. TLI = TM->getSubtargetImpl(Fn)->getTargetLowering();
  89. HasPrologue = false;
  90. HasIRCheck = false;
  91. Attribute Attr = Fn.getFnAttribute("stack-protector-buffer-size");
  92. if (Attr.isStringAttribute() &&
  93. Attr.getValueAsString().getAsInteger(10, SSPBufferSize))
  94. return false; // Invalid integer string
  95. if (!RequiresStackProtector())
  96. return false;
  97. // TODO(etienneb): Functions with funclets are not correctly supported now.
  98. // Do nothing if this is funclet-based personality.
  99. if (Fn.hasPersonalityFn()) {
  100. EHPersonality Personality = classifyEHPersonality(Fn.getPersonalityFn());
  101. if (isFuncletEHPersonality(Personality))
  102. return false;
  103. }
  104. ++NumFunProtected;
  105. return InsertStackProtectors();
  106. }
  107. /// \param [out] IsLarge is set to true if a protectable array is found and
  108. /// it is "large" ( >= ssp-buffer-size). In the case of a structure with
  109. /// multiple arrays, this gets set if any of them is large.
  110. bool StackProtector::ContainsProtectableArray(Type *Ty, bool &IsLarge,
  111. bool Strong,
  112. bool InStruct) const {
  113. if (!Ty)
  114. return false;
  115. if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  116. if (!AT->getElementType()->isIntegerTy(8)) {
  117. // If we're on a non-Darwin platform or we're inside of a structure, don't
  118. // add stack protectors unless the array is a character array.
  119. // However, in strong mode any array, regardless of type and size,
  120. // triggers a protector.
  121. if (!Strong && (InStruct || !Trip.isOSDarwin()))
  122. return false;
  123. }
  124. // If an array has more than SSPBufferSize bytes of allocated space, then we
  125. // emit stack protectors.
  126. if (SSPBufferSize <= M->getDataLayout().getTypeAllocSize(AT)) {
  127. IsLarge = true;
  128. return true;
  129. }
  130. if (Strong)
  131. // Require a protector for all arrays in strong mode
  132. return true;
  133. }
  134. const StructType *ST = dyn_cast<StructType>(Ty);
  135. if (!ST)
  136. return false;
  137. bool NeedsProtector = false;
  138. for (StructType::element_iterator I = ST->element_begin(),
  139. E = ST->element_end();
  140. I != E; ++I)
  141. if (ContainsProtectableArray(*I, IsLarge, Strong, true)) {
  142. // If the element is a protectable array and is large (>= SSPBufferSize)
  143. // then we are done. If the protectable array is not large, then
  144. // keep looking in case a subsequent element is a large array.
  145. if (IsLarge)
  146. return true;
  147. NeedsProtector = true;
  148. }
  149. return NeedsProtector;
  150. }
  151. bool StackProtector::HasAddressTaken(const Instruction *AI) {
  152. for (const User *U : AI->users()) {
  153. if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
  154. if (AI == SI->getValueOperand())
  155. return true;
  156. } else if (const PtrToIntInst *SI = dyn_cast<PtrToIntInst>(U)) {
  157. if (AI == SI->getOperand(0))
  158. return true;
  159. } else if (isa<CallInst>(U)) {
  160. return true;
  161. } else if (isa<InvokeInst>(U)) {
  162. return true;
  163. } else if (const SelectInst *SI = dyn_cast<SelectInst>(U)) {
  164. if (HasAddressTaken(SI))
  165. return true;
  166. } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
  167. // Keep track of what PHI nodes we have already visited to ensure
  168. // they are only visited once.
  169. if (VisitedPHIs.insert(PN).second)
  170. if (HasAddressTaken(PN))
  171. return true;
  172. } else if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  173. if (HasAddressTaken(GEP))
  174. return true;
  175. } else if (const BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
  176. if (HasAddressTaken(BI))
  177. return true;
  178. }
  179. }
  180. return false;
  181. }
  182. /// \brief Check whether or not this function needs a stack protector based
  183. /// upon the stack protector level.
  184. ///
  185. /// We use two heuristics: a standard (ssp) and strong (sspstrong).
  186. /// The standard heuristic which will add a guard variable to functions that
  187. /// call alloca with a either a variable size or a size >= SSPBufferSize,
  188. /// functions with character buffers larger than SSPBufferSize, and functions
  189. /// with aggregates containing character buffers larger than SSPBufferSize. The
  190. /// strong heuristic will add a guard variables to functions that call alloca
  191. /// regardless of size, functions with any buffer regardless of type and size,
  192. /// functions with aggregates that contain any buffer regardless of type and
  193. /// size, and functions that contain stack-based variables that have had their
  194. /// address taken.
  195. bool StackProtector::RequiresStackProtector() {
  196. bool Strong = false;
  197. bool NeedsProtector = false;
  198. for (const BasicBlock &BB : *F)
  199. for (const Instruction &I : BB)
  200. if (const CallInst *CI = dyn_cast<CallInst>(&I))
  201. if (CI->getCalledFunction() ==
  202. Intrinsic::getDeclaration(F->getParent(),
  203. Intrinsic::stackprotector))
  204. HasPrologue = true;
  205. if (F->hasFnAttribute(Attribute::SafeStack))
  206. return false;
  207. if (F->hasFnAttribute(Attribute::StackProtectReq)) {
  208. NeedsProtector = true;
  209. Strong = true; // Use the same heuristic as strong to determine SSPLayout
  210. } else if (F->hasFnAttribute(Attribute::StackProtectStrong))
  211. Strong = true;
  212. else if (HasPrologue)
  213. NeedsProtector = true;
  214. else if (!F->hasFnAttribute(Attribute::StackProtect))
  215. return false;
  216. for (const BasicBlock &BB : *F) {
  217. for (const Instruction &I : BB) {
  218. if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
  219. if (AI->isArrayAllocation()) {
  220. if (const auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) {
  221. if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize) {
  222. // A call to alloca with size >= SSPBufferSize requires
  223. // stack protectors.
  224. Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
  225. NeedsProtector = true;
  226. } else if (Strong) {
  227. // Require protectors for all alloca calls in strong mode.
  228. Layout.insert(std::make_pair(AI, SSPLK_SmallArray));
  229. NeedsProtector = true;
  230. }
  231. } else {
  232. // A call to alloca with a variable size requires protectors.
  233. Layout.insert(std::make_pair(AI, SSPLK_LargeArray));
  234. NeedsProtector = true;
  235. }
  236. continue;
  237. }
  238. bool IsLarge = false;
  239. if (ContainsProtectableArray(AI->getAllocatedType(), IsLarge, Strong)) {
  240. Layout.insert(std::make_pair(AI, IsLarge ? SSPLK_LargeArray
  241. : SSPLK_SmallArray));
  242. NeedsProtector = true;
  243. continue;
  244. }
  245. if (Strong && HasAddressTaken(AI)) {
  246. ++NumAddrTaken;
  247. Layout.insert(std::make_pair(AI, SSPLK_AddrOf));
  248. NeedsProtector = true;
  249. }
  250. }
  251. }
  252. }
  253. return NeedsProtector;
  254. }
  255. /// Create a stack guard loading and populate whether SelectionDAG SSP is
  256. /// supported.
  257. static Value *getStackGuard(const TargetLoweringBase *TLI, Module *M,
  258. IRBuilder<> &B,
  259. bool *SupportsSelectionDAGSP = nullptr) {
  260. if (Value *Guard = TLI->getIRStackGuard(B))
  261. return B.CreateLoad(Guard, true, "StackGuard");
  262. // Use SelectionDAG SSP handling, since there isn't an IR guard.
  263. //
  264. // This is more or less weird, since we optionally output whether we
  265. // should perform a SelectionDAG SP here. The reason is that it's strictly
  266. // defined as !TLI->getIRStackGuard(B), where getIRStackGuard is also
  267. // mutating. There is no way to get this bit without mutating the IR, so
  268. // getting this bit has to happen in this right time.
  269. //
  270. // We could have define a new function TLI::supportsSelectionDAGSP(), but that
  271. // will put more burden on the backends' overriding work, especially when it
  272. // actually conveys the same information getIRStackGuard() already gives.
  273. if (SupportsSelectionDAGSP)
  274. *SupportsSelectionDAGSP = true;
  275. TLI->insertSSPDeclarations(*M);
  276. return B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackguard));
  277. }
  278. /// Insert code into the entry block that stores the stack guard
  279. /// variable onto the stack:
  280. ///
  281. /// entry:
  282. /// StackGuardSlot = alloca i8*
  283. /// StackGuard = <stack guard>
  284. /// call void @llvm.stackprotector(StackGuard, StackGuardSlot)
  285. ///
  286. /// Returns true if the platform/triple supports the stackprotectorcreate pseudo
  287. /// node.
  288. static bool CreatePrologue(Function *F, Module *M, ReturnInst *RI,
  289. const TargetLoweringBase *TLI, AllocaInst *&AI) {
  290. bool SupportsSelectionDAGSP = false;
  291. IRBuilder<> B(&F->getEntryBlock().front());
  292. PointerType *PtrTy = Type::getInt8PtrTy(RI->getContext());
  293. AI = B.CreateAlloca(PtrTy, nullptr, "StackGuardSlot");
  294. Value *GuardSlot = getStackGuard(TLI, M, B, &SupportsSelectionDAGSP);
  295. B.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackprotector),
  296. {GuardSlot, AI});
  297. return SupportsSelectionDAGSP;
  298. }
  299. /// InsertStackProtectors - Insert code into the prologue and epilogue of the
  300. /// function.
  301. ///
  302. /// - The prologue code loads and stores the stack guard onto the stack.
  303. /// - The epilogue checks the value stored in the prologue against the original
  304. /// value. It calls __stack_chk_fail if they differ.
  305. bool StackProtector::InsertStackProtectors() {
  306. bool SupportsSelectionDAGSP =
  307. EnableSelectionDAGSP && !TM->Options.EnableFastISel;
  308. AllocaInst *AI = nullptr; // Place on stack that stores the stack guard.
  309. for (Function::iterator I = F->begin(), E = F->end(); I != E;) {
  310. BasicBlock *BB = &*I++;
  311. ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
  312. if (!RI)
  313. continue;
  314. // Generate prologue instrumentation if not already generated.
  315. if (!HasPrologue) {
  316. HasPrologue = true;
  317. SupportsSelectionDAGSP &= CreatePrologue(F, M, RI, TLI, AI);
  318. }
  319. // SelectionDAG based code generation. Nothing else needs to be done here.
  320. // The epilogue instrumentation is postponed to SelectionDAG.
  321. if (SupportsSelectionDAGSP)
  322. break;
  323. // Set HasIRCheck to true, so that SelectionDAG will not generate its own
  324. // version. SelectionDAG called 'shouldEmitSDCheck' to check whether
  325. // instrumentation has already been generated.
  326. HasIRCheck = true;
  327. // Generate epilogue instrumentation. The epilogue intrumentation can be
  328. // function-based or inlined depending on which mechanism the target is
  329. // providing.
  330. if (Value* GuardCheck = TLI->getSSPStackGuardCheck(*M)) {
  331. // Generate the function-based epilogue instrumentation.
  332. // The target provides a guard check function, generate a call to it.
  333. IRBuilder<> B(RI);
  334. LoadInst *Guard = B.CreateLoad(AI, true, "Guard");
  335. CallInst *Call = B.CreateCall(GuardCheck, {Guard});
  336. llvm::Function *Function = cast<llvm::Function>(GuardCheck);
  337. Call->setAttributes(Function->getAttributes());
  338. Call->setCallingConv(Function->getCallingConv());
  339. } else {
  340. // Generate the epilogue with inline instrumentation.
  341. // If we do not support SelectionDAG based tail calls, generate IR level
  342. // tail calls.
  343. //
  344. // For each block with a return instruction, convert this:
  345. //
  346. // return:
  347. // ...
  348. // ret ...
  349. //
  350. // into this:
  351. //
  352. // return:
  353. // ...
  354. // %1 = <stack guard>
  355. // %2 = load StackGuardSlot
  356. // %3 = cmp i1 %1, %2
  357. // br i1 %3, label %SP_return, label %CallStackCheckFailBlk
  358. //
  359. // SP_return:
  360. // ret ...
  361. //
  362. // CallStackCheckFailBlk:
  363. // call void @__stack_chk_fail()
  364. // unreachable
  365. // Create the FailBB. We duplicate the BB every time since the MI tail
  366. // merge pass will merge together all of the various BB into one including
  367. // fail BB generated by the stack protector pseudo instruction.
  368. BasicBlock *FailBB = CreateFailBB();
  369. // Split the basic block before the return instruction.
  370. BasicBlock *NewBB = BB->splitBasicBlock(RI->getIterator(), "SP_return");
  371. // Update the dominator tree if we need to.
  372. if (DT && DT->isReachableFromEntry(BB)) {
  373. DT->addNewBlock(NewBB, BB);
  374. DT->addNewBlock(FailBB, BB);
  375. }
  376. // Remove default branch instruction to the new BB.
  377. BB->getTerminator()->eraseFromParent();
  378. // Move the newly created basic block to the point right after the old
  379. // basic block so that it's in the "fall through" position.
  380. NewBB->moveAfter(BB);
  381. // Generate the stack protector instructions in the old basic block.
  382. IRBuilder<> B(BB);
  383. Value *Guard = getStackGuard(TLI, M, B);
  384. LoadInst *LI2 = B.CreateLoad(AI, true);
  385. Value *Cmp = B.CreateICmpEQ(Guard, LI2);
  386. auto SuccessProb =
  387. BranchProbabilityInfo::getBranchProbStackProtector(true);
  388. auto FailureProb =
  389. BranchProbabilityInfo::getBranchProbStackProtector(false);
  390. MDNode *Weights = MDBuilder(F->getContext())
  391. .createBranchWeights(SuccessProb.getNumerator(),
  392. FailureProb.getNumerator());
  393. B.CreateCondBr(Cmp, NewBB, FailBB, Weights);
  394. }
  395. }
  396. // Return if we didn't modify any basic blocks. i.e., there are no return
  397. // statements in the function.
  398. return HasPrologue;
  399. }
  400. /// CreateFailBB - Create a basic block to jump to when the stack protector
  401. /// check fails.
  402. BasicBlock *StackProtector::CreateFailBB() {
  403. LLVMContext &Context = F->getContext();
  404. BasicBlock *FailBB = BasicBlock::Create(Context, "CallStackCheckFailBlk", F);
  405. IRBuilder<> B(FailBB);
  406. B.SetCurrentDebugLocation(DebugLoc::get(0, 0, F->getSubprogram()));
  407. if (Trip.isOSOpenBSD()) {
  408. Constant *StackChkFail =
  409. M->getOrInsertFunction("__stack_smash_handler",
  410. Type::getVoidTy(Context),
  411. Type::getInt8PtrTy(Context), nullptr);
  412. B.CreateCall(StackChkFail, B.CreateGlobalStringPtr(F->getName(), "SSH"));
  413. } else {
  414. Constant *StackChkFail =
  415. M->getOrInsertFunction("__stack_chk_fail", Type::getVoidTy(Context),
  416. nullptr);
  417. B.CreateCall(StackChkFail, {});
  418. }
  419. B.CreateUnreachable();
  420. return FailBB;
  421. }
  422. bool StackProtector::shouldEmitSDCheck(const BasicBlock &BB) const {
  423. return HasPrologue && !HasIRCheck && dyn_cast<ReturnInst>(BB.getTerminator());
  424. }