StackProtector.cpp 19 KB

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