SafeStack.cpp 34 KB

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