StackProtector.cpp 20 KB

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