SafeStack.cpp 30 KB

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