StackProtector.cpp 19 KB

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