SafeStack.cpp 35 KB

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