SafeStack.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. //===-- SafeStack.cpp - Safe Stack 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 splits the stack into the safe stack (kept as-is for LLVM backend)
  11. // and the unsafe stack (explicitly allocated and managed through the runtime
  12. // support library).
  13. //
  14. // http://clang.llvm.org/docs/SafeStack.html
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "SafeStackColoring.h"
  18. #include "SafeStackLayout.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/ADT/Triple.h"
  21. #include "llvm/Analysis/AssumptionCache.h"
  22. #include "llvm/Analysis/BranchProbabilityInfo.h"
  23. #include "llvm/Analysis/ScalarEvolution.h"
  24. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  25. #include "llvm/CodeGen/Passes.h"
  26. #include "llvm/CodeGen/TargetPassConfig.h"
  27. #include "llvm/IR/Constants.h"
  28. #include "llvm/IR/DIBuilder.h"
  29. #include "llvm/IR/DataLayout.h"
  30. #include "llvm/IR/DerivedTypes.h"
  31. #include "llvm/IR/Function.h"
  32. #include "llvm/IR/IRBuilder.h"
  33. #include "llvm/IR/InstIterator.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/IntrinsicInst.h"
  36. #include "llvm/IR/Intrinsics.h"
  37. #include "llvm/IR/MDBuilder.h"
  38. #include "llvm/IR/Module.h"
  39. #include "llvm/Pass.h"
  40. #include "llvm/Support/CommandLine.h"
  41. #include "llvm/Support/Debug.h"
  42. #include "llvm/Support/Format.h"
  43. #include "llvm/Support/MathExtras.h"
  44. #include "llvm/Support/raw_os_ostream.h"
  45. #include "llvm/Target/TargetLowering.h"
  46. #include "llvm/Target/TargetSubtargetInfo.h"
  47. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  48. #include "llvm/Transforms/Utils/Local.h"
  49. #include "llvm/Transforms/Utils/ModuleUtils.h"
  50. using namespace llvm;
  51. using namespace llvm::safestack;
  52. #define DEBUG_TYPE "safestack"
  53. namespace llvm {
  54. STATISTIC(NumFunctions, "Total number of functions");
  55. STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
  56. STATISTIC(NumUnsafeStackRestorePointsFunctions,
  57. "Number of functions that use setjmp or exceptions");
  58. STATISTIC(NumAllocas, "Total number of allocas");
  59. STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
  60. STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
  61. STATISTIC(NumUnsafeByValArguments, "Number of unsafe byval arguments");
  62. STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
  63. } // namespace llvm
  64. namespace {
  65. /// Rewrite an SCEV expression for a memory access address to an expression that
  66. /// represents offset from the given alloca.
  67. ///
  68. /// The implementation simply replaces all mentions of the alloca with zero.
  69. class AllocaOffsetRewriter : public SCEVRewriteVisitor<AllocaOffsetRewriter> {
  70. const Value *AllocaPtr;
  71. public:
  72. AllocaOffsetRewriter(ScalarEvolution &SE, const Value *AllocaPtr)
  73. : SCEVRewriteVisitor(SE), AllocaPtr(AllocaPtr) {}
  74. const SCEV *visitUnknown(const SCEVUnknown *Expr) {
  75. if (Expr->getValue() == AllocaPtr)
  76. return SE.getZero(Expr->getType());
  77. return Expr;
  78. }
  79. };
  80. /// The SafeStack pass splits the stack of each function into the safe
  81. /// stack, which is only accessed through memory safe dereferences (as
  82. /// determined statically), and the unsafe stack, which contains all
  83. /// local variables that are accessed in ways that we can't prove to
  84. /// be safe.
  85. class SafeStack {
  86. Function &F;
  87. const TargetLoweringBase &TL;
  88. const DataLayout &DL;
  89. ScalarEvolution &SE;
  90. Type *StackPtrTy;
  91. Type *IntPtrTy;
  92. Type *Int32Ty;
  93. Type *Int8Ty;
  94. Value *UnsafeStackPtr = nullptr;
  95. /// Unsafe stack alignment. Each stack frame must ensure that the stack is
  96. /// aligned to this value. We need to re-align the unsafe stack if the
  97. /// alignment of any object on the stack exceeds this value.
  98. ///
  99. /// 16 seems like a reasonable upper bound on the alignment of objects that we
  100. /// might expect to appear on the stack on most common targets.
  101. enum { StackAlignment = 16 };
  102. /// \brief Return the value of the stack canary.
  103. Value *getStackGuard(IRBuilder<> &IRB, Function &F);
  104. /// \brief Load stack guard from the frame and check if it has changed.
  105. void checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
  106. AllocaInst *StackGuardSlot, Value *StackGuard);
  107. /// \brief Find all static allocas, dynamic allocas, return instructions and
  108. /// stack restore points (exception unwind blocks and setjmp calls) in the
  109. /// given function and append them to the respective vectors.
  110. void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
  111. SmallVectorImpl<AllocaInst *> &DynamicAllocas,
  112. SmallVectorImpl<Argument *> &ByValArguments,
  113. SmallVectorImpl<ReturnInst *> &Returns,
  114. SmallVectorImpl<Instruction *> &StackRestorePoints);
  115. /// \brief Calculate the allocation size of a given alloca. Returns 0 if the
  116. /// size can not be statically determined.
  117. uint64_t getStaticAllocaAllocationSize(const AllocaInst* AI);
  118. /// \brief Allocate space for all static allocas in \p StaticAllocas,
  119. /// replace allocas with pointers into the unsafe stack and generate code to
  120. /// restore the stack pointer before all return instructions in \p Returns.
  121. ///
  122. /// \returns A pointer to the top of the unsafe stack after all unsafe static
  123. /// allocas are allocated.
  124. Value *moveStaticAllocasToUnsafeStack(IRBuilder<> &IRB, Function &F,
  125. ArrayRef<AllocaInst *> StaticAllocas,
  126. ArrayRef<Argument *> ByValArguments,
  127. ArrayRef<ReturnInst *> Returns,
  128. Instruction *BasePointer,
  129. AllocaInst *StackGuardSlot);
  130. /// \brief Generate code to restore the stack after all stack restore points
  131. /// in \p StackRestorePoints.
  132. ///
  133. /// \returns A local variable in which to maintain the dynamic top of the
  134. /// unsafe stack if needed.
  135. AllocaInst *
  136. createStackRestorePoints(IRBuilder<> &IRB, Function &F,
  137. ArrayRef<Instruction *> StackRestorePoints,
  138. Value *StaticTop, bool NeedDynamicTop);
  139. /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
  140. /// space dynamically on the unsafe stack and store the dynamic unsafe stack
  141. /// top to \p DynamicTop if non-null.
  142. void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
  143. AllocaInst *DynamicTop,
  144. ArrayRef<AllocaInst *> DynamicAllocas);
  145. bool IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize);
  146. bool IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
  147. const Value *AllocaPtr, uint64_t AllocaSize);
  148. bool IsAccessSafe(Value *Addr, uint64_t Size, const Value *AllocaPtr,
  149. uint64_t AllocaSize);
  150. public:
  151. SafeStack(Function &F, const TargetLoweringBase &TL, const DataLayout &DL,
  152. ScalarEvolution &SE)
  153. : F(F), TL(TL), DL(DL), SE(SE),
  154. StackPtrTy(Type::getInt8PtrTy(F.getContext())),
  155. IntPtrTy(DL.getIntPtrType(F.getContext())),
  156. Int32Ty(Type::getInt32Ty(F.getContext())),
  157. Int8Ty(Type::getInt8Ty(F.getContext())) {}
  158. // Run the transformation on the associated function.
  159. // Returns whether the function was changed.
  160. bool run();
  161. };
  162. uint64_t SafeStack::getStaticAllocaAllocationSize(const AllocaInst* AI) {
  163. uint64_t Size = DL.getTypeAllocSize(AI->getAllocatedType());
  164. if (AI->isArrayAllocation()) {
  165. auto C = dyn_cast<ConstantInt>(AI->getArraySize());
  166. if (!C)
  167. return 0;
  168. Size *= C->getZExtValue();
  169. }
  170. return Size;
  171. }
  172. bool SafeStack::IsAccessSafe(Value *Addr, uint64_t AccessSize,
  173. const Value *AllocaPtr, uint64_t AllocaSize) {
  174. AllocaOffsetRewriter Rewriter(SE, AllocaPtr);
  175. const SCEV *Expr = Rewriter.visit(SE.getSCEV(Addr));
  176. uint64_t BitWidth = SE.getTypeSizeInBits(Expr->getType());
  177. ConstantRange AccessStartRange = SE.getUnsignedRange(Expr);
  178. ConstantRange SizeRange =
  179. ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AccessSize));
  180. ConstantRange AccessRange = AccessStartRange.add(SizeRange);
  181. ConstantRange AllocaRange =
  182. ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, AllocaSize));
  183. bool Safe = AllocaRange.contains(AccessRange);
  184. DEBUG(dbgs() << "[SafeStack] "
  185. << (isa<AllocaInst>(AllocaPtr) ? "Alloca " : "ByValArgument ")
  186. << *AllocaPtr << "\n"
  187. << " Access " << *Addr << "\n"
  188. << " SCEV " << *Expr
  189. << " U: " << SE.getUnsignedRange(Expr)
  190. << ", S: " << SE.getSignedRange(Expr) << "\n"
  191. << " Range " << AccessRange << "\n"
  192. << " AllocaRange " << AllocaRange << "\n"
  193. << " " << (Safe ? "safe" : "unsafe") << "\n");
  194. return Safe;
  195. }
  196. bool SafeStack::IsMemIntrinsicSafe(const MemIntrinsic *MI, const Use &U,
  197. const Value *AllocaPtr,
  198. uint64_t AllocaSize) {
  199. // All MemIntrinsics have destination address in Arg0 and size in Arg2.
  200. if (MI->getRawDest() != U) return true;
  201. const auto *Len = dyn_cast<ConstantInt>(MI->getLength());
  202. // Non-constant size => unsafe. FIXME: try SCEV getRange.
  203. if (!Len) return false;
  204. return IsAccessSafe(U, Len->getZExtValue(), AllocaPtr, AllocaSize);
  205. }
  206. /// Check whether a given allocation must be put on the safe
  207. /// stack or not. The function analyzes all uses of AI and checks whether it is
  208. /// only accessed in a memory safe way (as decided statically).
  209. bool SafeStack::IsSafeStackAlloca(const Value *AllocaPtr, uint64_t AllocaSize) {
  210. // Go through all uses of this alloca and check whether all accesses to the
  211. // allocated object are statically known to be memory safe and, hence, the
  212. // object can be placed on the safe stack.
  213. SmallPtrSet<const Value *, 16> Visited;
  214. SmallVector<const Value *, 8> WorkList;
  215. WorkList.push_back(AllocaPtr);
  216. // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
  217. while (!WorkList.empty()) {
  218. const Value *V = WorkList.pop_back_val();
  219. for (const Use &UI : V->uses()) {
  220. auto I = cast<const Instruction>(UI.getUser());
  221. assert(V == UI.get());
  222. switch (I->getOpcode()) {
  223. case Instruction::Load: {
  224. if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getType()), AllocaPtr,
  225. AllocaSize))
  226. return false;
  227. break;
  228. }
  229. case Instruction::VAArg:
  230. // "va-arg" from a pointer is safe.
  231. break;
  232. case Instruction::Store: {
  233. if (V == I->getOperand(0)) {
  234. // Stored the pointer - conservatively assume it may be unsafe.
  235. DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
  236. << "\n store of address: " << *I << "\n");
  237. return false;
  238. }
  239. if (!IsAccessSafe(UI, DL.getTypeStoreSize(I->getOperand(0)->getType()),
  240. AllocaPtr, AllocaSize))
  241. return false;
  242. break;
  243. }
  244. case Instruction::Ret: {
  245. // Information leak.
  246. return false;
  247. }
  248. case Instruction::Call:
  249. case Instruction::Invoke: {
  250. ImmutableCallSite CS(I);
  251. if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  252. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  253. II->getIntrinsicID() == Intrinsic::lifetime_end)
  254. continue;
  255. }
  256. if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
  257. if (!IsMemIntrinsicSafe(MI, UI, AllocaPtr, AllocaSize)) {
  258. DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
  259. << "\n unsafe memintrinsic: " << *I
  260. << "\n");
  261. return false;
  262. }
  263. continue;
  264. }
  265. // LLVM 'nocapture' attribute is only set for arguments whose address
  266. // is not stored, passed around, or used in any other non-trivial way.
  267. // We assume that passing a pointer to an object as a 'nocapture
  268. // readnone' argument is safe.
  269. // FIXME: a more precise solution would require an interprocedural
  270. // analysis here, which would look at all uses of an argument inside
  271. // the function being called.
  272. ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
  273. for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
  274. if (A->get() == V)
  275. if (!(CS.doesNotCapture(A - B) && (CS.doesNotAccessMemory(A - B) ||
  276. CS.doesNotAccessMemory()))) {
  277. DEBUG(dbgs() << "[SafeStack] Unsafe alloca: " << *AllocaPtr
  278. << "\n unsafe call: " << *I << "\n");
  279. return false;
  280. }
  281. continue;
  282. }
  283. default:
  284. if (Visited.insert(I).second)
  285. WorkList.push_back(cast<const Instruction>(I));
  286. }
  287. }
  288. }
  289. // All uses of the alloca are safe, we can place it on the safe stack.
  290. return true;
  291. }
  292. Value *SafeStack::getStackGuard(IRBuilder<> &IRB, Function &F) {
  293. Value *StackGuardVar = TL.getIRStackGuard(IRB);
  294. if (!StackGuardVar)
  295. StackGuardVar =
  296. F.getParent()->getOrInsertGlobal("__stack_chk_guard", StackPtrTy);
  297. return IRB.CreateLoad(StackGuardVar, "StackGuard");
  298. }
  299. void SafeStack::findInsts(Function &F,
  300. SmallVectorImpl<AllocaInst *> &StaticAllocas,
  301. SmallVectorImpl<AllocaInst *> &DynamicAllocas,
  302. SmallVectorImpl<Argument *> &ByValArguments,
  303. SmallVectorImpl<ReturnInst *> &Returns,
  304. SmallVectorImpl<Instruction *> &StackRestorePoints) {
  305. for (Instruction &I : instructions(&F)) {
  306. if (auto AI = dyn_cast<AllocaInst>(&I)) {
  307. ++NumAllocas;
  308. uint64_t Size = getStaticAllocaAllocationSize(AI);
  309. if (IsSafeStackAlloca(AI, Size))
  310. continue;
  311. if (AI->isStaticAlloca()) {
  312. ++NumUnsafeStaticAllocas;
  313. StaticAllocas.push_back(AI);
  314. } else {
  315. ++NumUnsafeDynamicAllocas;
  316. DynamicAllocas.push_back(AI);
  317. }
  318. } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
  319. Returns.push_back(RI);
  320. } else if (auto CI = dyn_cast<CallInst>(&I)) {
  321. // setjmps require stack restore.
  322. if (CI->getCalledFunction() && CI->canReturnTwice())
  323. StackRestorePoints.push_back(CI);
  324. } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
  325. // Exception landing pads require stack restore.
  326. StackRestorePoints.push_back(LP);
  327. } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
  328. if (II->getIntrinsicID() == Intrinsic::gcroot)
  329. llvm::report_fatal_error(
  330. "gcroot intrinsic not compatible with safestack attribute");
  331. }
  332. }
  333. for (Argument &Arg : F.args()) {
  334. if (!Arg.hasByValAttr())
  335. continue;
  336. uint64_t Size =
  337. DL.getTypeStoreSize(Arg.getType()->getPointerElementType());
  338. if (IsSafeStackAlloca(&Arg, Size))
  339. continue;
  340. ++NumUnsafeByValArguments;
  341. ByValArguments.push_back(&Arg);
  342. }
  343. }
  344. AllocaInst *
  345. SafeStack::createStackRestorePoints(IRBuilder<> &IRB, Function &F,
  346. ArrayRef<Instruction *> StackRestorePoints,
  347. Value *StaticTop, bool NeedDynamicTop) {
  348. assert(StaticTop && "The stack top isn't set.");
  349. if (StackRestorePoints.empty())
  350. return nullptr;
  351. // We need the current value of the shadow stack pointer to restore
  352. // after longjmp or exception catching.
  353. // FIXME: On some platforms this could be handled by the longjmp/exception
  354. // runtime itself.
  355. AllocaInst *DynamicTop = nullptr;
  356. if (NeedDynamicTop) {
  357. // If we also have dynamic alloca's, the stack pointer value changes
  358. // throughout the function. For now we store it in an alloca.
  359. DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
  360. "unsafe_stack_dynamic_ptr");
  361. IRB.CreateStore(StaticTop, DynamicTop);
  362. }
  363. // Restore current stack pointer after longjmp/exception catch.
  364. for (Instruction *I : StackRestorePoints) {
  365. ++NumUnsafeStackRestorePoints;
  366. IRB.SetInsertPoint(I->getNextNode());
  367. Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
  368. IRB.CreateStore(CurrentTop, UnsafeStackPtr);
  369. }
  370. return DynamicTop;
  371. }
  372. void SafeStack::checkStackGuard(IRBuilder<> &IRB, Function &F, ReturnInst &RI,
  373. AllocaInst *StackGuardSlot, Value *StackGuard) {
  374. Value *V = IRB.CreateLoad(StackGuardSlot);
  375. Value *Cmp = IRB.CreateICmpNE(StackGuard, V);
  376. auto SuccessProb = BranchProbabilityInfo::getBranchProbStackProtector(true);
  377. auto FailureProb = BranchProbabilityInfo::getBranchProbStackProtector(false);
  378. MDNode *Weights = MDBuilder(F.getContext())
  379. .createBranchWeights(SuccessProb.getNumerator(),
  380. FailureProb.getNumerator());
  381. Instruction *CheckTerm =
  382. SplitBlockAndInsertIfThen(Cmp, &RI,
  383. /* Unreachable */ true, Weights);
  384. IRBuilder<> IRBFail(CheckTerm);
  385. // FIXME: respect -fsanitize-trap / -ftrap-function here?
  386. Constant *StackChkFail = F.getParent()->getOrInsertFunction(
  387. "__stack_chk_fail", IRB.getVoidTy());
  388. IRBFail.CreateCall(StackChkFail, {});
  389. }
  390. /// We explicitly compute and set the unsafe stack layout for all unsafe
  391. /// static alloca instructions. We save the unsafe "base pointer" in the
  392. /// prologue into a local variable and restore it in the epilogue.
  393. Value *SafeStack::moveStaticAllocasToUnsafeStack(
  394. IRBuilder<> &IRB, Function &F, ArrayRef<AllocaInst *> StaticAllocas,
  395. ArrayRef<Argument *> ByValArguments, ArrayRef<ReturnInst *> Returns,
  396. Instruction *BasePointer, AllocaInst *StackGuardSlot) {
  397. if (StaticAllocas.empty() && ByValArguments.empty())
  398. return BasePointer;
  399. DIBuilder DIB(*F.getParent());
  400. StackColoring SSC(F, StaticAllocas);
  401. SSC.run();
  402. SSC.removeAllMarkers();
  403. // Unsafe stack always grows down.
  404. StackLayout SSL(StackAlignment);
  405. if (StackGuardSlot) {
  406. Type *Ty = StackGuardSlot->getAllocatedType();
  407. unsigned Align =
  408. std::max(DL.getPrefTypeAlignment(Ty), StackGuardSlot->getAlignment());
  409. SSL.addObject(StackGuardSlot, getStaticAllocaAllocationSize(StackGuardSlot),
  410. Align, SSC.getFullLiveRange());
  411. }
  412. for (Argument *Arg : ByValArguments) {
  413. Type *Ty = Arg->getType()->getPointerElementType();
  414. uint64_t Size = DL.getTypeStoreSize(Ty);
  415. if (Size == 0)
  416. Size = 1; // Don't create zero-sized stack objects.
  417. // Ensure the object is properly aligned.
  418. unsigned Align = std::max((unsigned)DL.getPrefTypeAlignment(Ty),
  419. Arg->getParamAlignment());
  420. SSL.addObject(Arg, Size, Align, SSC.getFullLiveRange());
  421. }
  422. for (AllocaInst *AI : StaticAllocas) {
  423. Type *Ty = AI->getAllocatedType();
  424. uint64_t Size = getStaticAllocaAllocationSize(AI);
  425. if (Size == 0)
  426. Size = 1; // Don't create zero-sized stack objects.
  427. // Ensure the object is properly aligned.
  428. unsigned Align =
  429. std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment());
  430. SSL.addObject(AI, Size, Align, SSC.getLiveRange(AI));
  431. }
  432. SSL.computeLayout();
  433. unsigned FrameAlignment = SSL.getFrameAlignment();
  434. // FIXME: tell SSL that we start at a less-then-MaxAlignment aligned location
  435. // (AlignmentSkew).
  436. if (FrameAlignment > StackAlignment) {
  437. // Re-align the base pointer according to the max requested alignment.
  438. assert(isPowerOf2_32(FrameAlignment));
  439. IRB.SetInsertPoint(BasePointer->getNextNode());
  440. BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
  441. IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
  442. ConstantInt::get(IntPtrTy, ~uint64_t(FrameAlignment - 1))),
  443. StackPtrTy));
  444. }
  445. IRB.SetInsertPoint(BasePointer->getNextNode());
  446. if (StackGuardSlot) {
  447. unsigned Offset = SSL.getObjectOffset(StackGuardSlot);
  448. Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
  449. ConstantInt::get(Int32Ty, -Offset));
  450. Value *NewAI =
  451. IRB.CreateBitCast(Off, StackGuardSlot->getType(), "StackGuardSlot");
  452. // Replace alloc with the new location.
  453. StackGuardSlot->replaceAllUsesWith(NewAI);
  454. StackGuardSlot->eraseFromParent();
  455. }
  456. for (Argument *Arg : ByValArguments) {
  457. unsigned Offset = SSL.getObjectOffset(Arg);
  458. Type *Ty = Arg->getType()->getPointerElementType();
  459. uint64_t Size = DL.getTypeStoreSize(Ty);
  460. if (Size == 0)
  461. Size = 1; // Don't create zero-sized stack objects.
  462. Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
  463. ConstantInt::get(Int32Ty, -Offset));
  464. Value *NewArg = IRB.CreateBitCast(Off, Arg->getType(),
  465. Arg->getName() + ".unsafe-byval");
  466. // Replace alloc with the new location.
  467. replaceDbgDeclare(Arg, BasePointer, BasePointer->getNextNode(), DIB,
  468. /*Deref=*/false, -Offset);
  469. Arg->replaceAllUsesWith(NewArg);
  470. IRB.SetInsertPoint(cast<Instruction>(NewArg)->getNextNode());
  471. IRB.CreateMemCpy(Off, Arg, Size, Arg->getParamAlignment());
  472. }
  473. // Allocate space for every unsafe static AllocaInst on the unsafe stack.
  474. for (AllocaInst *AI : StaticAllocas) {
  475. IRB.SetInsertPoint(AI);
  476. unsigned Offset = SSL.getObjectOffset(AI);
  477. uint64_t Size = getStaticAllocaAllocationSize(AI);
  478. if (Size == 0)
  479. Size = 1; // Don't create zero-sized stack objects.
  480. replaceDbgDeclareForAlloca(AI, BasePointer, DIB, /*Deref=*/false, -Offset);
  481. replaceDbgValueForAlloca(AI, BasePointer, DIB, -Offset);
  482. // Replace uses of the alloca with the new location.
  483. // Insert address calculation close to each use to work around PR27844.
  484. std::string Name = std::string(AI->getName()) + ".unsafe";
  485. while (!AI->use_empty()) {
  486. Use &U = *AI->use_begin();
  487. Instruction *User = cast<Instruction>(U.getUser());
  488. Instruction *InsertBefore;
  489. if (auto *PHI = dyn_cast<PHINode>(User))
  490. InsertBefore = PHI->getIncomingBlock(U)->getTerminator();
  491. else
  492. InsertBefore = User;
  493. IRBuilder<> IRBUser(InsertBefore);
  494. Value *Off = IRBUser.CreateGEP(BasePointer, // BasePointer is i8*
  495. ConstantInt::get(Int32Ty, -Offset));
  496. Value *Replacement = IRBUser.CreateBitCast(Off, AI->getType(), Name);
  497. if (auto *PHI = dyn_cast<PHINode>(User)) {
  498. // PHI nodes may have multiple incoming edges from the same BB (why??),
  499. // all must be updated at once with the same incoming value.
  500. auto *BB = PHI->getIncomingBlock(U);
  501. for (unsigned I = 0; I < PHI->getNumIncomingValues(); ++I)
  502. if (PHI->getIncomingBlock(I) == BB)
  503. PHI->setIncomingValue(I, Replacement);
  504. } else {
  505. U.set(Replacement);
  506. }
  507. }
  508. AI->eraseFromParent();
  509. }
  510. // Re-align BasePointer so that our callees would see it aligned as
  511. // expected.
  512. // FIXME: no need to update BasePointer in leaf functions.
  513. unsigned FrameSize = alignTo(SSL.getFrameSize(), StackAlignment);
  514. // Update shadow stack pointer in the function epilogue.
  515. IRB.SetInsertPoint(BasePointer->getNextNode());
  516. Value *StaticTop =
  517. IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -FrameSize),
  518. "unsafe_stack_static_top");
  519. IRB.CreateStore(StaticTop, UnsafeStackPtr);
  520. return StaticTop;
  521. }
  522. void SafeStack::moveDynamicAllocasToUnsafeStack(
  523. Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
  524. ArrayRef<AllocaInst *> DynamicAllocas) {
  525. DIBuilder DIB(*F.getParent());
  526. for (AllocaInst *AI : DynamicAllocas) {
  527. IRBuilder<> IRB(AI);
  528. // Compute the new SP value (after AI).
  529. Value *ArraySize = AI->getArraySize();
  530. if (ArraySize->getType() != IntPtrTy)
  531. ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
  532. Type *Ty = AI->getAllocatedType();
  533. uint64_t TySize = DL.getTypeAllocSize(Ty);
  534. Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
  535. Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
  536. SP = IRB.CreateSub(SP, Size);
  537. // Align the SP value to satisfy the AllocaInst, type and stack alignments.
  538. unsigned Align = std::max(
  539. std::max((unsigned)DL.getPrefTypeAlignment(Ty), AI->getAlignment()),
  540. (unsigned)StackAlignment);
  541. assert(isPowerOf2_32(Align));
  542. Value *NewTop = IRB.CreateIntToPtr(
  543. IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
  544. StackPtrTy);
  545. // Save the stack pointer.
  546. IRB.CreateStore(NewTop, UnsafeStackPtr);
  547. if (DynamicTop)
  548. IRB.CreateStore(NewTop, DynamicTop);
  549. Value *NewAI = IRB.CreatePointerCast(NewTop, AI->getType());
  550. if (AI->hasName() && isa<Instruction>(NewAI))
  551. NewAI->takeName(AI);
  552. replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/false);
  553. AI->replaceAllUsesWith(NewAI);
  554. AI->eraseFromParent();
  555. }
  556. if (!DynamicAllocas.empty()) {
  557. // Now go through the instructions again, replacing stacksave/stackrestore.
  558. for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
  559. Instruction *I = &*(It++);
  560. auto II = dyn_cast<IntrinsicInst>(I);
  561. if (!II)
  562. continue;
  563. if (II->getIntrinsicID() == Intrinsic::stacksave) {
  564. IRBuilder<> IRB(II);
  565. Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
  566. LI->takeName(II);
  567. II->replaceAllUsesWith(LI);
  568. II->eraseFromParent();
  569. } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
  570. IRBuilder<> IRB(II);
  571. Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
  572. SI->takeName(II);
  573. assert(II->use_empty());
  574. II->eraseFromParent();
  575. }
  576. }
  577. }
  578. }
  579. bool SafeStack::run() {
  580. assert(F.hasFnAttribute(Attribute::SafeStack) &&
  581. "Can't run SafeStack on a function without the attribute");
  582. assert(!F.isDeclaration() && "Can't run SafeStack on a function declaration");
  583. ++NumFunctions;
  584. SmallVector<AllocaInst *, 16> StaticAllocas;
  585. SmallVector<AllocaInst *, 4> DynamicAllocas;
  586. SmallVector<Argument *, 4> ByValArguments;
  587. SmallVector<ReturnInst *, 4> Returns;
  588. // Collect all points where stack gets unwound and needs to be restored
  589. // This is only necessary because the runtime (setjmp and unwind code) is
  590. // not aware of the unsafe stack and won't unwind/restore it properly.
  591. // To work around this problem without changing the runtime, we insert
  592. // instrumentation to restore the unsafe stack pointer when necessary.
  593. SmallVector<Instruction *, 4> StackRestorePoints;
  594. // Find all static and dynamic alloca instructions that must be moved to the
  595. // unsafe stack, all return instructions and stack restore points.
  596. findInsts(F, StaticAllocas, DynamicAllocas, ByValArguments, Returns,
  597. StackRestorePoints);
  598. if (StaticAllocas.empty() && DynamicAllocas.empty() &&
  599. ByValArguments.empty() && StackRestorePoints.empty())
  600. return false; // Nothing to do in this function.
  601. if (!StaticAllocas.empty() || !DynamicAllocas.empty() ||
  602. !ByValArguments.empty())
  603. ++NumUnsafeStackFunctions; // This function has the unsafe stack.
  604. if (!StackRestorePoints.empty())
  605. ++NumUnsafeStackRestorePointsFunctions;
  606. IRBuilder<> IRB(&F.front(), F.begin()->getFirstInsertionPt());
  607. UnsafeStackPtr = TL.getSafeStackPointerLocation(IRB);
  608. // Load the current stack pointer (we'll also use it as a base pointer).
  609. // FIXME: use a dedicated register for it ?
  610. Instruction *BasePointer =
  611. IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
  612. assert(BasePointer->getType() == StackPtrTy);
  613. AllocaInst *StackGuardSlot = nullptr;
  614. // FIXME: implement weaker forms of stack protector.
  615. if (F.hasFnAttribute(Attribute::StackProtect) ||
  616. F.hasFnAttribute(Attribute::StackProtectStrong) ||
  617. F.hasFnAttribute(Attribute::StackProtectReq)) {
  618. Value *StackGuard = getStackGuard(IRB, F);
  619. StackGuardSlot = IRB.CreateAlloca(StackPtrTy, nullptr);
  620. IRB.CreateStore(StackGuard, StackGuardSlot);
  621. for (ReturnInst *RI : Returns) {
  622. IRBuilder<> IRBRet(RI);
  623. checkStackGuard(IRBRet, F, *RI, StackGuardSlot, StackGuard);
  624. }
  625. }
  626. // The top of the unsafe stack after all unsafe static allocas are
  627. // allocated.
  628. Value *StaticTop =
  629. moveStaticAllocasToUnsafeStack(IRB, F, StaticAllocas, ByValArguments,
  630. Returns, BasePointer, StackGuardSlot);
  631. // Safe stack object that stores the current unsafe stack top. It is updated
  632. // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
  633. // This is only needed if we need to restore stack pointer after longjmp
  634. // or exceptions, and we have dynamic allocations.
  635. // FIXME: a better alternative might be to store the unsafe stack pointer
  636. // before setjmp / invoke instructions.
  637. AllocaInst *DynamicTop = createStackRestorePoints(
  638. IRB, F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
  639. // Handle dynamic allocas.
  640. moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
  641. DynamicAllocas);
  642. // Restore the unsafe stack pointer before each return.
  643. for (ReturnInst *RI : Returns) {
  644. IRB.SetInsertPoint(RI);
  645. IRB.CreateStore(BasePointer, UnsafeStackPtr);
  646. }
  647. DEBUG(dbgs() << "[SafeStack] safestack applied\n");
  648. return true;
  649. }
  650. class SafeStackLegacyPass : public FunctionPass {
  651. const TargetMachine *TM;
  652. public:
  653. static char ID; // Pass identification, replacement for typeid..
  654. SafeStackLegacyPass() : FunctionPass(ID), TM(nullptr) {
  655. initializeSafeStackLegacyPassPass(*PassRegistry::getPassRegistry());
  656. }
  657. void getAnalysisUsage(AnalysisUsage &AU) const override {
  658. AU.addRequired<TargetPassConfig>();
  659. AU.addRequired<TargetLibraryInfoWrapperPass>();
  660. AU.addRequired<AssumptionCacheTracker>();
  661. }
  662. bool runOnFunction(Function &F) override {
  663. DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
  664. if (!F.hasFnAttribute(Attribute::SafeStack)) {
  665. DEBUG(dbgs() << "[SafeStack] safestack is not requested"
  666. " for this function\n");
  667. return false;
  668. }
  669. if (F.isDeclaration()) {
  670. DEBUG(dbgs() << "[SafeStack] function definition"
  671. " is not available\n");
  672. return false;
  673. }
  674. TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
  675. auto *TL = TM->getSubtargetImpl(F)->getTargetLowering();
  676. if (!TL)
  677. report_fatal_error("TargetLowering instance is required");
  678. auto *DL = &F.getParent()->getDataLayout();
  679. auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  680. auto &ACT = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  681. // Compute DT and LI only for functions that have the attribute.
  682. // This is only useful because the legacy pass manager doesn't let us
  683. // compute analyzes lazily.
  684. // In the backend pipeline, nothing preserves DT before SafeStack, so we
  685. // would otherwise always compute it wastefully, even if there is no
  686. // function with the safestack attribute.
  687. DominatorTree DT(F);
  688. LoopInfo LI(DT);
  689. ScalarEvolution SE(F, TLI, ACT, DT, LI);
  690. return SafeStack(F, *TL, *DL, SE).run();
  691. }
  692. };
  693. } // anonymous namespace
  694. char SafeStackLegacyPass::ID = 0;
  695. INITIALIZE_PASS_BEGIN(SafeStackLegacyPass, "safe-stack",
  696. "Safe Stack instrumentation pass", false, false)
  697. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  698. INITIALIZE_PASS_END(SafeStackLegacyPass, "safe-stack",
  699. "Safe Stack instrumentation pass", false, false)
  700. FunctionPass *llvm::createSafeStackPass() { return new SafeStackLegacyPass(); }