SafeStack.cpp 31 KB

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