SafeStack.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. //===-- SafeStack.cpp - Safe Stack Insertion ------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass splits the stack into the safe stack (kept as-is for LLVM backend)
  11. // and the unsafe stack (explicitly allocated and managed through the runtime
  12. // support library).
  13. //
  14. // http://clang.llvm.org/docs/SafeStack.html
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Transforms/Instrumentation.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/ADT/Triple.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/Analysis/TargetTransformInfo.h"
  22. #include "llvm/IR/Constants.h"
  23. #include "llvm/IR/DataLayout.h"
  24. #include "llvm/IR/DerivedTypes.h"
  25. #include "llvm/IR/DIBuilder.h"
  26. #include "llvm/IR/Function.h"
  27. #include "llvm/IR/InstIterator.h"
  28. #include "llvm/IR/Instructions.h"
  29. #include "llvm/IR/IntrinsicInst.h"
  30. #include "llvm/IR/Intrinsics.h"
  31. #include "llvm/IR/IRBuilder.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/Pass.h"
  34. #include "llvm/Support/CommandLine.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/Format.h"
  37. #include "llvm/Support/MathExtras.h"
  38. #include "llvm/Support/raw_os_ostream.h"
  39. #include "llvm/Transforms/Utils/Local.h"
  40. #include "llvm/Transforms/Utils/ModuleUtils.h"
  41. using namespace llvm;
  42. #define DEBUG_TYPE "safestack"
  43. namespace llvm {
  44. STATISTIC(NumFunctions, "Total number of functions");
  45. STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack");
  46. STATISTIC(NumUnsafeStackRestorePointsFunctions,
  47. "Number of functions that use setjmp or exceptions");
  48. STATISTIC(NumAllocas, "Total number of allocas");
  49. STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas");
  50. STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas");
  51. STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads");
  52. } // namespace llvm
  53. namespace {
  54. /// Check whether a given alloca instruction (AI) should be put on the safe
  55. /// stack or not. The function analyzes all uses of AI and checks whether it is
  56. /// only accessed in a memory safe way (as decided statically).
  57. bool IsSafeStackAlloca(const AllocaInst *AI) {
  58. // Go through all uses of this alloca and check whether all accesses to the
  59. // allocated object are statically known to be memory safe and, hence, the
  60. // object can be placed on the safe stack.
  61. SmallPtrSet<const Value *, 16> Visited;
  62. SmallVector<const Instruction *, 8> WorkList;
  63. WorkList.push_back(AI);
  64. // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc.
  65. while (!WorkList.empty()) {
  66. const Instruction *V = WorkList.pop_back_val();
  67. for (const Use &UI : V->uses()) {
  68. auto I = cast<const Instruction>(UI.getUser());
  69. assert(V == UI.get());
  70. switch (I->getOpcode()) {
  71. case Instruction::Load:
  72. // Loading from a pointer is safe.
  73. break;
  74. case Instruction::VAArg:
  75. // "va-arg" from a pointer is safe.
  76. break;
  77. case Instruction::Store:
  78. if (V == I->getOperand(0))
  79. // Stored the pointer - conservatively assume it may be unsafe.
  80. return false;
  81. // Storing to the pointee is safe.
  82. break;
  83. case Instruction::GetElementPtr:
  84. if (!cast<const GetElementPtrInst>(I)->hasAllConstantIndices())
  85. // GEP with non-constant indices can lead to memory errors.
  86. // This also applies to inbounds GEPs, as the inbounds attribute
  87. // represents an assumption that the address is in bounds, rather than
  88. // an assertion that it is.
  89. return false;
  90. // We assume that GEP on static alloca with constant indices is safe,
  91. // otherwise a compiler would detect it and warn during compilation.
  92. if (!isa<const ConstantInt>(AI->getArraySize()))
  93. // However, if the array size itself is not constant, the access
  94. // might still be unsafe at runtime.
  95. return false;
  96. /* fallthrough */
  97. case Instruction::BitCast:
  98. case Instruction::IntToPtr:
  99. case Instruction::PHI:
  100. case Instruction::PtrToInt:
  101. case Instruction::Select:
  102. // The object can be safe or not, depending on how the result of the
  103. // instruction is used.
  104. if (Visited.insert(I).second)
  105. WorkList.push_back(cast<const Instruction>(I));
  106. break;
  107. case Instruction::Call:
  108. case Instruction::Invoke: {
  109. // FIXME: add support for memset and memcpy intrinsics.
  110. ImmutableCallSite CS(I);
  111. // LLVM 'nocapture' attribute is only set for arguments whose address
  112. // is not stored, passed around, or used in any other non-trivial way.
  113. // We assume that passing a pointer to an object as a 'nocapture'
  114. // argument is safe.
  115. // FIXME: a more precise solution would require an interprocedural
  116. // analysis here, which would look at all uses of an argument inside
  117. // the function being called.
  118. ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
  119. for (ImmutableCallSite::arg_iterator A = B; A != E; ++A)
  120. if (A->get() == V && !CS.doesNotCapture(A - B))
  121. // The parameter is not marked 'nocapture' - unsafe.
  122. return false;
  123. continue;
  124. }
  125. default:
  126. // The object is unsafe if it is used in any other way.
  127. return false;
  128. }
  129. }
  130. }
  131. // All uses of the alloca are safe, we can place it on the safe stack.
  132. return true;
  133. }
  134. /// The SafeStack pass splits the stack of each function into the
  135. /// safe stack, which is only accessed through memory safe dereferences
  136. /// (as determined statically), and the unsafe stack, which contains all
  137. /// local variables that are accessed in unsafe ways.
  138. class SafeStack : public FunctionPass {
  139. const DataLayout *DL;
  140. Type *StackPtrTy;
  141. Type *IntPtrTy;
  142. Type *Int32Ty;
  143. Type *Int8Ty;
  144. Constant *UnsafeStackPtr = nullptr;
  145. /// Unsafe stack alignment. Each stack frame must ensure that the stack is
  146. /// aligned to this value. We need to re-align the unsafe stack if the
  147. /// alignment of any object on the stack exceeds this value.
  148. ///
  149. /// 16 seems like a reasonable upper bound on the alignment of objects that we
  150. /// might expect to appear on the stack on most common targets.
  151. enum { StackAlignment = 16 };
  152. /// \brief Build a constant representing a pointer to the unsafe stack
  153. /// pointer.
  154. Constant *getOrCreateUnsafeStackPtr(Module &M);
  155. /// \brief Find all static allocas, dynamic allocas, return instructions and
  156. /// stack restore points (exception unwind blocks and setjmp calls) in the
  157. /// given function and append them to the respective vectors.
  158. void findInsts(Function &F, SmallVectorImpl<AllocaInst *> &StaticAllocas,
  159. SmallVectorImpl<AllocaInst *> &DynamicAllocas,
  160. SmallVectorImpl<ReturnInst *> &Returns,
  161. SmallVectorImpl<Instruction *> &StackRestorePoints);
  162. /// \brief Allocate space for all static allocas in \p StaticAllocas,
  163. /// replace allocas with pointers into the unsafe stack and generate code to
  164. /// restore the stack pointer before all return instructions in \p Returns.
  165. ///
  166. /// \returns A pointer to the top of the unsafe stack after all unsafe static
  167. /// allocas are allocated.
  168. Value *moveStaticAllocasToUnsafeStack(Function &F,
  169. ArrayRef<AllocaInst *> StaticAllocas,
  170. ArrayRef<ReturnInst *> Returns);
  171. /// \brief Generate code to restore the stack after all stack restore points
  172. /// in \p StackRestorePoints.
  173. ///
  174. /// \returns A local variable in which to maintain the dynamic top of the
  175. /// unsafe stack if needed.
  176. AllocaInst *
  177. createStackRestorePoints(Function &F,
  178. ArrayRef<Instruction *> StackRestorePoints,
  179. Value *StaticTop, bool NeedDynamicTop);
  180. /// \brief Replace all allocas in \p DynamicAllocas with code to allocate
  181. /// space dynamically on the unsafe stack and store the dynamic unsafe stack
  182. /// top to \p DynamicTop if non-null.
  183. void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr,
  184. AllocaInst *DynamicTop,
  185. ArrayRef<AllocaInst *> DynamicAllocas);
  186. public:
  187. static char ID; // Pass identification, replacement for typeid.
  188. SafeStack() : FunctionPass(ID), DL(nullptr) {
  189. initializeSafeStackPass(*PassRegistry::getPassRegistry());
  190. }
  191. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  192. AU.addRequired<AliasAnalysis>();
  193. }
  194. virtual bool doInitialization(Module &M) {
  195. DL = &M.getDataLayout();
  196. StackPtrTy = Type::getInt8PtrTy(M.getContext());
  197. IntPtrTy = DL->getIntPtrType(M.getContext());
  198. Int32Ty = Type::getInt32Ty(M.getContext());
  199. Int8Ty = Type::getInt8Ty(M.getContext());
  200. return false;
  201. }
  202. bool runOnFunction(Function &F);
  203. }; // class SafeStack
  204. Constant *SafeStack::getOrCreateUnsafeStackPtr(Module &M) {
  205. // The unsafe stack pointer is stored in a global variable with a magic name.
  206. const char *kUnsafeStackPtrVar = "__safestack_unsafe_stack_ptr";
  207. auto UnsafeStackPtr =
  208. dyn_cast_or_null<GlobalVariable>(M.getNamedValue(kUnsafeStackPtrVar));
  209. if (!UnsafeStackPtr) {
  210. // The global variable is not defined yet, define it ourselves.
  211. // We use the initial-exec TLS model because we do not support the variable
  212. // living anywhere other than in the main executable.
  213. UnsafeStackPtr = new GlobalVariable(
  214. /*Module=*/M, /*Type=*/StackPtrTy,
  215. /*isConstant=*/false, /*Linkage=*/GlobalValue::ExternalLinkage,
  216. /*Initializer=*/0, /*Name=*/kUnsafeStackPtrVar,
  217. /*InsertBefore=*/nullptr,
  218. /*ThreadLocalMode=*/GlobalValue::InitialExecTLSModel);
  219. } else {
  220. // The variable exists, check its type and attributes.
  221. if (UnsafeStackPtr->getValueType() != StackPtrTy) {
  222. report_fatal_error(Twine(kUnsafeStackPtrVar) + " must have void* type");
  223. }
  224. if (!UnsafeStackPtr->isThreadLocal()) {
  225. report_fatal_error(Twine(kUnsafeStackPtrVar) + " must be thread-local");
  226. }
  227. }
  228. return UnsafeStackPtr;
  229. }
  230. void SafeStack::findInsts(Function &F,
  231. SmallVectorImpl<AllocaInst *> &StaticAllocas,
  232. SmallVectorImpl<AllocaInst *> &DynamicAllocas,
  233. SmallVectorImpl<ReturnInst *> &Returns,
  234. SmallVectorImpl<Instruction *> &StackRestorePoints) {
  235. for (Instruction &I : inst_range(&F)) {
  236. if (auto AI = dyn_cast<AllocaInst>(&I)) {
  237. ++NumAllocas;
  238. if (IsSafeStackAlloca(AI))
  239. continue;
  240. if (AI->isStaticAlloca()) {
  241. ++NumUnsafeStaticAllocas;
  242. StaticAllocas.push_back(AI);
  243. } else {
  244. ++NumUnsafeDynamicAllocas;
  245. DynamicAllocas.push_back(AI);
  246. }
  247. } else if (auto RI = dyn_cast<ReturnInst>(&I)) {
  248. Returns.push_back(RI);
  249. } else if (auto CI = dyn_cast<CallInst>(&I)) {
  250. // setjmps require stack restore.
  251. if (CI->getCalledFunction() && CI->canReturnTwice())
  252. StackRestorePoints.push_back(CI);
  253. } else if (auto LP = dyn_cast<LandingPadInst>(&I)) {
  254. // Exception landing pads require stack restore.
  255. StackRestorePoints.push_back(LP);
  256. } else if (auto II = dyn_cast<IntrinsicInst>(&I)) {
  257. if (II->getIntrinsicID() == Intrinsic::gcroot)
  258. llvm::report_fatal_error(
  259. "gcroot intrinsic not compatible with safestack attribute");
  260. }
  261. }
  262. }
  263. AllocaInst *
  264. SafeStack::createStackRestorePoints(Function &F,
  265. ArrayRef<Instruction *> StackRestorePoints,
  266. Value *StaticTop, bool NeedDynamicTop) {
  267. if (StackRestorePoints.empty())
  268. return nullptr;
  269. IRBuilder<> IRB(StaticTop
  270. ? cast<Instruction>(StaticTop)->getNextNode()
  271. : (Instruction *)F.getEntryBlock().getFirstInsertionPt());
  272. // We need the current value of the shadow stack pointer to restore
  273. // after longjmp or exception catching.
  274. // FIXME: On some platforms this could be handled by the longjmp/exception
  275. // runtime itself.
  276. AllocaInst *DynamicTop = nullptr;
  277. if (NeedDynamicTop)
  278. // If we also have dynamic alloca's, the stack pointer value changes
  279. // throughout the function. For now we store it in an alloca.
  280. DynamicTop = IRB.CreateAlloca(StackPtrTy, /*ArraySize=*/nullptr,
  281. "unsafe_stack_dynamic_ptr");
  282. if (!StaticTop)
  283. // We need the original unsafe stack pointer value, even if there are
  284. // no unsafe static allocas.
  285. StaticTop = IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
  286. if (NeedDynamicTop)
  287. IRB.CreateStore(StaticTop, DynamicTop);
  288. // Restore current stack pointer after longjmp/exception catch.
  289. for (Instruction *I : StackRestorePoints) {
  290. ++NumUnsafeStackRestorePoints;
  291. IRB.SetInsertPoint(cast<Instruction>(I->getNextNode()));
  292. Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop;
  293. IRB.CreateStore(CurrentTop, UnsafeStackPtr);
  294. }
  295. return DynamicTop;
  296. }
  297. Value *
  298. SafeStack::moveStaticAllocasToUnsafeStack(Function &F,
  299. ArrayRef<AllocaInst *> StaticAllocas,
  300. ArrayRef<ReturnInst *> Returns) {
  301. if (StaticAllocas.empty())
  302. return nullptr;
  303. IRBuilder<> IRB(F.getEntryBlock().getFirstInsertionPt());
  304. DIBuilder DIB(*F.getParent());
  305. // We explicitly compute and set the unsafe stack layout for all unsafe
  306. // static alloca instructions. We save the unsafe "base pointer" in the
  307. // prologue into a local variable and restore it in the epilogue.
  308. // Load the current stack pointer (we'll also use it as a base pointer).
  309. // FIXME: use a dedicated register for it ?
  310. Instruction *BasePointer =
  311. IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr");
  312. assert(BasePointer->getType() == StackPtrTy);
  313. for (ReturnInst *RI : Returns) {
  314. IRB.SetInsertPoint(RI);
  315. IRB.CreateStore(BasePointer, UnsafeStackPtr);
  316. }
  317. // Compute maximum alignment among static objects on the unsafe stack.
  318. unsigned MaxAlignment = 0;
  319. for (AllocaInst *AI : StaticAllocas) {
  320. Type *Ty = AI->getAllocatedType();
  321. unsigned Align =
  322. std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
  323. if (Align > MaxAlignment)
  324. MaxAlignment = Align;
  325. }
  326. if (MaxAlignment > StackAlignment) {
  327. // Re-align the base pointer according to the max requested alignment.
  328. assert(isPowerOf2_32(MaxAlignment));
  329. IRB.SetInsertPoint(cast<Instruction>(BasePointer->getNextNode()));
  330. BasePointer = cast<Instruction>(IRB.CreateIntToPtr(
  331. IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy),
  332. ConstantInt::get(IntPtrTy, ~uint64_t(MaxAlignment - 1))),
  333. StackPtrTy));
  334. }
  335. // Allocate space for every unsafe static AllocaInst on the unsafe stack.
  336. int64_t StaticOffset = 0; // Current stack top.
  337. for (AllocaInst *AI : StaticAllocas) {
  338. IRB.SetInsertPoint(AI);
  339. auto CArraySize = cast<ConstantInt>(AI->getArraySize());
  340. Type *Ty = AI->getAllocatedType();
  341. uint64_t Size = DL->getTypeAllocSize(Ty) * CArraySize->getZExtValue();
  342. if (Size == 0)
  343. Size = 1; // Don't create zero-sized stack objects.
  344. // Ensure the object is properly aligned.
  345. unsigned Align =
  346. std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment());
  347. // Add alignment.
  348. // NOTE: we ensure that BasePointer itself is aligned to >= Align.
  349. StaticOffset += Size;
  350. StaticOffset = RoundUpToAlignment(StaticOffset, Align);
  351. Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8*
  352. ConstantInt::get(Int32Ty, -StaticOffset));
  353. Value *NewAI = IRB.CreateBitCast(Off, AI->getType(), AI->getName());
  354. if (AI->hasName() && isa<Instruction>(NewAI))
  355. cast<Instruction>(NewAI)->takeName(AI);
  356. // Replace alloc with the new location.
  357. replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
  358. AI->replaceAllUsesWith(NewAI);
  359. AI->eraseFromParent();
  360. }
  361. // Re-align BasePointer so that our callees would see it aligned as
  362. // expected.
  363. // FIXME: no need to update BasePointer in leaf functions.
  364. StaticOffset = RoundUpToAlignment(StaticOffset, StackAlignment);
  365. // Update shadow stack pointer in the function epilogue.
  366. IRB.SetInsertPoint(cast<Instruction>(BasePointer->getNextNode()));
  367. Value *StaticTop =
  368. IRB.CreateGEP(BasePointer, ConstantInt::get(Int32Ty, -StaticOffset),
  369. "unsafe_stack_static_top");
  370. IRB.CreateStore(StaticTop, UnsafeStackPtr);
  371. return StaticTop;
  372. }
  373. void SafeStack::moveDynamicAllocasToUnsafeStack(
  374. Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop,
  375. ArrayRef<AllocaInst *> DynamicAllocas) {
  376. DIBuilder DIB(*F.getParent());
  377. for (AllocaInst *AI : DynamicAllocas) {
  378. IRBuilder<> IRB(AI);
  379. // Compute the new SP value (after AI).
  380. Value *ArraySize = AI->getArraySize();
  381. if (ArraySize->getType() != IntPtrTy)
  382. ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false);
  383. Type *Ty = AI->getAllocatedType();
  384. uint64_t TySize = DL->getTypeAllocSize(Ty);
  385. Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize));
  386. Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy);
  387. SP = IRB.CreateSub(SP, Size);
  388. // Align the SP value to satisfy the AllocaInst, type and stack alignments.
  389. unsigned Align = std::max(
  390. std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()),
  391. (unsigned)StackAlignment);
  392. assert(isPowerOf2_32(Align));
  393. Value *NewTop = IRB.CreateIntToPtr(
  394. IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align - 1))),
  395. StackPtrTy);
  396. // Save the stack pointer.
  397. IRB.CreateStore(NewTop, UnsafeStackPtr);
  398. if (DynamicTop)
  399. IRB.CreateStore(NewTop, DynamicTop);
  400. Value *NewAI = IRB.CreateIntToPtr(SP, AI->getType());
  401. if (AI->hasName() && isa<Instruction>(NewAI))
  402. NewAI->takeName(AI);
  403. replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true);
  404. AI->replaceAllUsesWith(NewAI);
  405. AI->eraseFromParent();
  406. }
  407. if (!DynamicAllocas.empty()) {
  408. // Now go through the instructions again, replacing stacksave/stackrestore.
  409. for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) {
  410. Instruction *I = &*(It++);
  411. auto II = dyn_cast<IntrinsicInst>(I);
  412. if (!II)
  413. continue;
  414. if (II->getIntrinsicID() == Intrinsic::stacksave) {
  415. IRBuilder<> IRB(II);
  416. Instruction *LI = IRB.CreateLoad(UnsafeStackPtr);
  417. LI->takeName(II);
  418. II->replaceAllUsesWith(LI);
  419. II->eraseFromParent();
  420. } else if (II->getIntrinsicID() == Intrinsic::stackrestore) {
  421. IRBuilder<> IRB(II);
  422. Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr);
  423. SI->takeName(II);
  424. assert(II->use_empty());
  425. II->eraseFromParent();
  426. }
  427. }
  428. }
  429. }
  430. bool SafeStack::runOnFunction(Function &F) {
  431. auto AA = &getAnalysis<AliasAnalysis>();
  432. DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n");
  433. if (!F.hasFnAttribute(Attribute::SafeStack)) {
  434. DEBUG(dbgs() << "[SafeStack] safestack is not requested"
  435. " for this function\n");
  436. return false;
  437. }
  438. if (F.isDeclaration()) {
  439. DEBUG(dbgs() << "[SafeStack] function definition"
  440. " is not available\n");
  441. return false;
  442. }
  443. {
  444. // Make sure the regular stack protector won't run on this function
  445. // (safestack attribute takes precedence).
  446. AttrBuilder B;
  447. B.addAttribute(Attribute::StackProtect)
  448. .addAttribute(Attribute::StackProtectReq)
  449. .addAttribute(Attribute::StackProtectStrong);
  450. F.removeAttributes(
  451. AttributeSet::FunctionIndex,
  452. AttributeSet::get(F.getContext(), AttributeSet::FunctionIndex, B));
  453. }
  454. if (AA->onlyReadsMemory(&F)) {
  455. // XXX: we don't protect against information leak attacks for now.
  456. DEBUG(dbgs() << "[SafeStack] function only reads memory\n");
  457. return false;
  458. }
  459. ++NumFunctions;
  460. SmallVector<AllocaInst *, 16> StaticAllocas;
  461. SmallVector<AllocaInst *, 4> DynamicAllocas;
  462. SmallVector<ReturnInst *, 4> Returns;
  463. // Collect all points where stack gets unwound and needs to be restored
  464. // This is only necessary because the runtime (setjmp and unwind code) is
  465. // not aware of the unsafe stack and won't unwind/restore it prorerly.
  466. // To work around this problem without changing the runtime, we insert
  467. // instrumentation to restore the unsafe stack pointer when necessary.
  468. SmallVector<Instruction *, 4> StackRestorePoints;
  469. // Find all static and dynamic alloca instructions that must be moved to the
  470. // unsafe stack, all return instructions and stack restore points.
  471. findInsts(F, StaticAllocas, DynamicAllocas, Returns, StackRestorePoints);
  472. if (StaticAllocas.empty() && DynamicAllocas.empty() &&
  473. StackRestorePoints.empty())
  474. return false; // Nothing to do in this function.
  475. if (!StaticAllocas.empty() || !DynamicAllocas.empty())
  476. ++NumUnsafeStackFunctions; // This function has the unsafe stack.
  477. if (!StackRestorePoints.empty())
  478. ++NumUnsafeStackRestorePointsFunctions;
  479. if (!UnsafeStackPtr)
  480. UnsafeStackPtr = getOrCreateUnsafeStackPtr(*F.getParent());
  481. // The top of the unsafe stack after all unsafe static allocas are allocated.
  482. Value *StaticTop = moveStaticAllocasToUnsafeStack(F, StaticAllocas, Returns);
  483. // Safe stack object that stores the current unsafe stack top. It is updated
  484. // as unsafe dynamic (non-constant-sized) allocas are allocated and freed.
  485. // This is only needed if we need to restore stack pointer after longjmp
  486. // or exceptions, and we have dynamic allocations.
  487. // FIXME: a better alternative might be to store the unsafe stack pointer
  488. // before setjmp / invoke instructions.
  489. AllocaInst *DynamicTop = createStackRestorePoints(
  490. F, StackRestorePoints, StaticTop, !DynamicAllocas.empty());
  491. // Handle dynamic allocas.
  492. moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop,
  493. DynamicAllocas);
  494. DEBUG(dbgs() << "[SafeStack] safestack applied\n");
  495. return true;
  496. }
  497. } // end anonymous namespace
  498. char SafeStack::ID = 0;
  499. INITIALIZE_PASS_BEGIN(SafeStack, "safe-stack",
  500. "Safe Stack instrumentation pass", false, false)
  501. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  502. INITIALIZE_PASS_END(SafeStack, "safe-stack", "Safe Stack instrumentation pass",
  503. false, false)
  504. FunctionPass *llvm::createSafeStackPass() { return new SafeStack(); }