SafeStack.cpp 34 KB

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