SafeStack.cpp 35 KB

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