Index: docs/LangRef.rst =================================================================== --- docs/LangRef.rst +++ docs/LangRef.rst @@ -1307,6 +1307,10 @@ ``setjmp`` is an example of such a function. The compiler disables some optimizations (like tail calls) in the caller of these functions. +``safe_stack`` + This attribute indicates that + `SafeStack `_ + protection is enabled for this function. ``sanitize_address`` This attribute indicates that AddressSanitizer checks (dynamic address safety analysis) are enabled for this function. Index: include/llvm/Bitcode/LLVMBitCodes.h =================================================================== --- include/llvm/Bitcode/LLVMBitCodes.h +++ include/llvm/Bitcode/LLVMBitCodes.h @@ -402,7 +402,8 @@ ATTR_KIND_NON_NULL = 39, ATTR_KIND_JUMP_TABLE = 40, ATTR_KIND_DEREFERENCEABLE = 41, - ATTR_KIND_DEREFERENCEABLE_OR_NULL = 42 + ATTR_KIND_DEREFERENCEABLE_OR_NULL = 42, + ATTR_KIND_SAFESTACK = 43, }; enum ComdatSelectionKindCodes { Index: include/llvm/IR/Attributes.h =================================================================== --- include/llvm/IR/Attributes.h +++ include/llvm/IR/Attributes.h @@ -107,6 +107,7 @@ StackProtect, ///< Stack protection. StackProtectReq, ///< Stack protection required. StackProtectStrong, ///< Strong Stack protection. + SafeStack, ///< Safe Stack protection. StructRet, ///< Hidden pointer to structure to return SanitizeAddress, ///< AddressSanitizer is on. SanitizeThread, ///< ThreadSanitizer is on. Index: include/llvm/InitializePasses.h =================================================================== --- include/llvm/InitializePasses.h +++ include/llvm/InitializePasses.h @@ -241,6 +241,7 @@ void initializeRegionPrinterPass(PassRegistry&); void initializeRegionViewerPass(PassRegistry&); void initializeRewriteStatepointsForGCPass(PassRegistry&); +void initializeSafeStackPass(PassRegistry&); void initializeSCCPPass(PassRegistry&); void initializeSROAPass(PassRegistry&); void initializeSROA_DTPass(PassRegistry&); Index: include/llvm/LinkAllPasses.h =================================================================== --- include/llvm/LinkAllPasses.h +++ include/llvm/LinkAllPasses.h @@ -131,6 +131,7 @@ (void) llvm::createRegionPrinterPass(); (void) llvm::createRegionViewerPass(); (void) llvm::createSCCPPass(); + (void) llvm::createSafeStackPass(); (void) llvm::createScalarReplAggregatesPass(); (void) llvm::createSingleLoopExtractorPass(); (void) llvm::createStripSymbolsPass(); Index: include/llvm/Support/Compiler.h =================================================================== --- include/llvm/Support/Compiler.h +++ include/llvm/Support/Compiler.h @@ -29,6 +29,10 @@ # define __has_attribute(x) 0 #endif +#ifndef __has_cpp_attribute +# define __has_cpp_attribute(x) 0 +#endif + #ifndef __has_builtin # define __has_builtin(x) 0 #endif @@ -401,4 +405,12 @@ #define LLVM_THREAD_LOCAL #endif +/// \macro LLVM_FALLTHROUGH +/// \brief Marks an empty statement preceding a deliberate switch fallthrough. +#if __has_cpp_attribute(clang::fallthrough) +#define LLVM_FALLTHROUGH [[clang::fallthrough]] +#else +#define LLVM_FALLTHROUGH +#endif + #endif Index: include/llvm/Transforms/Instrumentation.h =================================================================== --- include/llvm/Transforms/Instrumentation.h +++ include/llvm/Transforms/Instrumentation.h @@ -132,6 +132,10 @@ // checking on loads, stores, and other memory intrinsics. FunctionPass *createBoundsCheckingPass(); +/// createSafeStackPass - This pass splits the stack into a safe stack and +/// an unsafe stack to protect against stack-based overflow vulnerabilities. +FunctionPass *createSafeStackPass(); + } // End llvm namespace #endif Index: lib/AsmParser/LLLexer.cpp =================================================================== --- lib/AsmParser/LLLexer.cpp +++ lib/AsmParser/LLLexer.cpp @@ -627,6 +627,7 @@ KEYWORD(ssp); KEYWORD(sspreq); KEYWORD(sspstrong); + KEYWORD(safestack); KEYWORD(sanitize_address); KEYWORD(sanitize_thread); KEYWORD(sanitize_memory); Index: lib/AsmParser/LLParser.cpp =================================================================== --- lib/AsmParser/LLParser.cpp +++ lib/AsmParser/LLParser.cpp @@ -960,6 +960,7 @@ case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break; case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break; case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break; + case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break; case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break; case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break; case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break; @@ -1269,6 +1270,7 @@ case lltok::kw_ssp: case lltok::kw_sspreq: case lltok::kw_sspstrong: + case lltok::kw_safestack: case lltok::kw_uwtable: HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute"); break; @@ -1345,6 +1347,7 @@ case lltok::kw_ssp: case lltok::kw_sspreq: case lltok::kw_sspstrong: + case lltok::kw_safestack: case lltok::kw_uwtable: HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute"); break; Index: lib/AsmParser/LLToken.h =================================================================== --- lib/AsmParser/LLToken.h +++ lib/AsmParser/LLToken.h @@ -134,6 +134,7 @@ kw_ssp, kw_sspreq, kw_sspstrong, + kw_safestack, kw_sret, kw_sanitize_thread, kw_sanitize_memory, Index: lib/Bitcode/Reader/BitcodeReader.cpp =================================================================== --- lib/Bitcode/Reader/BitcodeReader.cpp +++ lib/Bitcode/Reader/BitcodeReader.cpp @@ -1149,6 +1149,8 @@ return Attribute::StackProtectReq; case bitc::ATTR_KIND_STACK_PROTECT_STRONG: return Attribute::StackProtectStrong; + case bitc::ATTR_KIND_SAFESTACK: + return Attribute::SafeStack; case bitc::ATTR_KIND_STRUCT_RET: return Attribute::StructRet; case bitc::ATTR_KIND_SANITIZE_ADDRESS: Index: lib/Bitcode/Writer/BitcodeWriter.cpp =================================================================== --- lib/Bitcode/Writer/BitcodeWriter.cpp +++ lib/Bitcode/Writer/BitcodeWriter.cpp @@ -230,6 +230,8 @@ return bitc::ATTR_KIND_STACK_PROTECT_REQ; case Attribute::StackProtectStrong: return bitc::ATTR_KIND_STACK_PROTECT_STRONG; + case Attribute::SafeStack: + return bitc::ATTR_KIND_SAFESTACK; case Attribute::StructRet: return bitc::ATTR_KIND_STRUCT_RET; case Attribute::SanitizeAddress: Index: lib/CodeGen/LLVMBuild.txt =================================================================== --- lib/CodeGen/LLVMBuild.txt +++ lib/CodeGen/LLVMBuild.txt @@ -22,4 +22,4 @@ type = Library name = CodeGen parent = Libraries -required_libraries = Analysis Core MC Scalar Support Target TransformUtils +required_libraries = Analysis Core Instrumentation MC Scalar Support Target TransformUtils Index: lib/CodeGen/Passes.cpp =================================================================== --- lib/CodeGen/Passes.cpp +++ lib/CodeGen/Passes.cpp @@ -24,6 +24,7 @@ #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" +#include "llvm/Transforms/Instrumentation.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/SymbolRewriter.h" @@ -450,6 +451,9 @@ void TargetPassConfig::addISelPrepare() { addPreISel(); + // Add both the safe stack and the stack protection passes: each of them will + // only protect functions that have corresponding attributes. + addPass(createSafeStackPass()); addPass(createStackProtectorPass(TM)); if (PrintISelInput) Index: lib/IR/Attributes.cpp =================================================================== --- lib/IR/Attributes.cpp +++ lib/IR/Attributes.cpp @@ -250,6 +250,8 @@ return "sspreq"; if (hasAttribute(Attribute::StackProtectStrong)) return "sspstrong"; + if (hasAttribute(Attribute::SafeStack)) + return "safestack"; if (hasAttribute(Attribute::StructRet)) return "sret"; if (hasAttribute(Attribute::SanitizeThread)) @@ -434,6 +436,7 @@ case Attribute::InAlloca: return 1ULL << 43; case Attribute::NonNull: return 1ULL << 44; case Attribute::JumpTable: return 1ULL << 45; + case Attribute::SafeStack: return 1ULL << 46; case Attribute::Dereferenceable: llvm_unreachable("dereferenceable attribute not supported in raw format"); break; Index: lib/IR/Verifier.cpp =================================================================== --- lib/IR/Verifier.cpp +++ lib/IR/Verifier.cpp @@ -1251,6 +1251,7 @@ I->getKindAsEnum() == Attribute::StackProtect || I->getKindAsEnum() == Attribute::StackProtectReq || I->getKindAsEnum() == Attribute::StackProtectStrong || + I->getKindAsEnum() == Attribute::SafeStack || I->getKindAsEnum() == Attribute::NoRedZone || I->getKindAsEnum() == Attribute::NoImplicitFloat || I->getKindAsEnum() == Attribute::Naked || Index: lib/Target/CppBackend/CPPBackend.cpp =================================================================== --- lib/Target/CppBackend/CPPBackend.cpp +++ lib/Target/CppBackend/CPPBackend.cpp @@ -513,6 +513,7 @@ HANDLE_ATTR(StackProtect); HANDLE_ATTR(StackProtectReq); HANDLE_ATTR(StackProtectStrong); + HANDLE_ATTR(SafeStack); HANDLE_ATTR(NoCapture); HANDLE_ATTR(NoRedZone); HANDLE_ATTR(NoImplicitFloat); Index: lib/Transforms/IPO/Inliner.cpp =================================================================== --- lib/Transforms/IPO/Inliner.cpp +++ lib/Transforms/IPO/Inliner.cpp @@ -93,19 +93,26 @@ // clutter to the IR. AttrBuilder B; B.addAttribute(Attribute::StackProtect) - .addAttribute(Attribute::StackProtectStrong); + .addAttribute(Attribute::StackProtectStrong) + .addAttribute(Attribute::StackProtectReq); AttributeSet OldSSPAttr = AttributeSet::get(Caller->getContext(), AttributeSet::FunctionIndex, B); - if (Callee->hasFnAttribute(Attribute::StackProtectReq)) { + if (Callee->hasFnAttribute(Attribute::SafeStack)) { + Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr); + Caller->addFnAttr(Attribute::SafeStack); + } else if (Callee->hasFnAttribute(Attribute::StackProtectReq) && + !Caller->hasFnAttribute(Attribute::SafeStack)) { Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr); Caller->addFnAttr(Attribute::StackProtectReq); } else if (Callee->hasFnAttribute(Attribute::StackProtectStrong) && + !Caller->hasFnAttribute(Attribute::SafeStack) && !Caller->hasFnAttribute(Attribute::StackProtectReq)) { Caller->removeAttributes(AttributeSet::FunctionIndex, OldSSPAttr); Caller->addFnAttr(Attribute::StackProtectStrong); } else if (Callee->hasFnAttribute(Attribute::StackProtect) && + !Caller->hasFnAttribute(Attribute::SafeStack) && !Caller->hasFnAttribute(Attribute::StackProtectReq) && !Caller->hasFnAttribute(Attribute::StackProtectStrong)) Caller->addFnAttr(Attribute::StackProtect); Index: lib/Transforms/Instrumentation/CMakeLists.txt =================================================================== --- lib/Transforms/Instrumentation/CMakeLists.txt +++ lib/Transforms/Instrumentation/CMakeLists.txt @@ -6,6 +6,7 @@ MemorySanitizer.cpp Instrumentation.cpp InstrProfiling.cpp + SafeStack.cpp SanitizerCoverage.cpp ThreadSanitizer.cpp Index: lib/Transforms/Instrumentation/Instrumentation.cpp =================================================================== --- lib/Transforms/Instrumentation/Instrumentation.cpp +++ lib/Transforms/Instrumentation/Instrumentation.cpp @@ -30,6 +30,7 @@ initializeThreadSanitizerPass(Registry); initializeSanitizerCoverageModulePass(Registry); initializeDataFlowSanitizerPass(Registry); + initializeSafeStackPass(Registry); } /// LLVMInitializeInstrumentation - C binding for Index: lib/Transforms/Instrumentation/SafeStack.cpp =================================================================== --- /dev/null +++ lib/Transforms/Instrumentation/SafeStack.cpp @@ -0,0 +1,601 @@ +//===-- SafeStack.cpp - Safe Stack Insertion ------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This pass splits the stack into the safe stack (kept as-is for LLVM backend) +// and the unsafe stack (explicitly allocated and managed through the runtime +// support library). +// +//===----------------------------------------------------------------------===// + +#define DEBUG_TYPE "safestack" +#include "llvm/Transforms/Instrumentation.h" +#include "llvm/ADT/Statistic.h" +#include "llvm/ADT/Triple.h" +#include "llvm/Analysis/AliasAnalysis.h" +#include "llvm/Analysis/TargetTransformInfo.h" +#include "llvm/IR/Constants.h" +#include "llvm/IR/DataLayout.h" +#include "llvm/IR/DerivedTypes.h" +#include "llvm/IR/DIBuilder.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/InstIterator.h" +#include "llvm/IR/Instructions.h" +#include "llvm/IR/IntrinsicInst.h" +#include "llvm/IR/Intrinsics.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Module.h" +#include "llvm/Pass.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/Format.h" +#include "llvm/Support/raw_os_ostream.h" +#include "llvm/Transforms/Utils/Local.h" +#include "llvm/Transforms/Utils/ModuleUtils.h" + +using namespace llvm; + +namespace llvm { + +STATISTIC(NumFunctions, "Total number of functions"); +STATISTIC(NumUnsafeStackFunctions, "Number of functions with unsafe stack"); +STATISTIC(NumUnsafeStackRestorePointsFunctions, + "Number of functions that use setjmp or exceptions"); + +STATISTIC(NumAllocas, "Total number of allocas"); +STATISTIC(NumUnsafeStaticAllocas, "Number of unsafe static allocas"); +STATISTIC(NumUnsafeDynamicAllocas, "Number of unsafe dynamic allocas"); +STATISTIC(NumUnsafeStackRestorePoints, "Number of setjmps and landingpads"); + +} // namespace llvm + +namespace { + +/// Check whether a given alloca instruction (AI) should be put on the safe +/// stack or not. The function analyzes all uses of AI and checks whether it is +/// only accessed in a memory safe way (as decided statically). +bool IsSafeStackAlloca(const AllocaInst *AI) { + // Go through all uses of this alloca and check whether all accesses to the + // allocated object are statically known to be memory safe and, hence, the + // object can be placed on the safe stack. + + SmallPtrSet Visited; + SmallVector WorkList; + WorkList.push_back(AI); + + // A DFS search through all uses of the alloca in bitcasts/PHI/GEPs/etc. + while (!WorkList.empty()) { + const Instruction *V = WorkList.pop_back_val(); + for (const Use &UI : V->uses()) { + auto I = cast(UI.getUser()); + assert(V == UI.get()); + + switch (I->getOpcode()) { + case Instruction::Load: + // Loading from a pointer is safe. + break; + case Instruction::VAArg: + // "va-arg" from a pointer is safe. + break; + case Instruction::Store: + if (V == I->getOperand(0)) + // Stored the pointer - conservatively assume it may be unsafe. + return false; + // Storing to the pointee is safe. + break; + + case Instruction::GetElementPtr: + if (!cast(I)->hasAllConstantIndices()) + // GEP with non-constant indices can lead to memory errors. + return false; + + // We assume that GEP on static alloca with constant indices is safe, + // otherwise a compiler would detect it and warn during compilation. + + if (!isa(AI->getArraySize())) + // However, if the array size itself is not constant, the access + // might still be unsafe at runtime. + return false; + + LLVM_FALLTHROUGH; + + case Instruction::BitCast: + case Instruction::IntToPtr: + case Instruction::PHI: + case Instruction::PtrToInt: + case Instruction::Select: + // The object can be safe or not, depending on how the result of the + // instruction is used. + if (Visited.insert(I).second) + WorkList.push_back(cast(I)); + break; + + case Instruction::Call: + case Instruction::Invoke: { + ImmutableCallSite CS(I); + + // Given we don't care about information leak attacks at this point, + // the object is considered safe if a pointer to it is passed to a + // function that only reads memory nor returns any value. This function + // can neither do unsafe writes itself nor capture the pointer (or + // return it) to do unsafe writes to it elsewhere. The function also + // shouldn't unwind (a readonly function can leak bits by throwing an + // exception or not depending on the input value). + if (CS.onlyReadsMemory() && I->getType()->isVoidTy()) + continue; + + // LLVM 'nocapture' attribute is only set for arguments whose address + // is not stored, passed around, or used in any other non-trivial way. + // We assume that passing a pointer to an object as a 'nocapture' + // argument is safe. + // FIXME: a more precise solution would require an interprocedural + // analysis here, which would look at all uses of an argument inside + // the function being called. + ImmutableCallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end(); + for (ImmutableCallSite::arg_iterator A = B; A != E; ++A) + if (A->get() == V && !CS.doesNotCapture(A - B)) + // The parameter is not marked 'nocapture' - unsafe. + return false; + continue; + } + + default: + // The object is unsafe if it is used in any other way. + return false; + } + } + } + + // All uses of the alloca are safe, we can place it on the safe stack. + return true; +} + +/// The SafeStack pass splits the stack of each function into the +/// safe stack, which is only accessed through memory safe dereferences +/// (as determined statically), and the unsafe stack, which contains all +/// local variables that are accessed in unsafe ways. +class SafeStack : public FunctionPass { + const DataLayout *DL; + + Type *StackPtrTy; + Type *IntPtrTy; + Type *Int32Ty; + Type *Int8Ty; + + Constant *UnsafeStackPtr; + + enum { StackAlignment = 16 }; + + /// \brief Build a constant representing a pointer to the unsafe stack + /// pointer. + Constant *getOrCreateUnsafeStackPtr(Module &M); + + /// \brief Find all static allocas, dynamic allocas, return instructions and + /// stack restore points (exception unwind blocks and setjmp calls) in the + /// given function and append them to the respective vectors. + void findInsts(Function &F, SmallVectorImpl &StaticAllocas, + SmallVectorImpl &DynamicAllocas, + SmallVectorImpl &Returns, + SmallVectorImpl &StackRestorePoints); + + /// \brief Allocate space for all static allocas in \p StaticAllocas, + /// replace allocas with pointers into the unsafe stack and generate code to + /// restore the stack pointer before all return instructions in \p Returns. + /// + /// \returns A pointer to the top of the unsafe stack after all unsafe static + /// allocas are allocated. + Value *moveStaticAllocasToUnsafeStack(Function &F, + ArrayRef StaticAllocas, + ArrayRef Returns); + + /// \brief Generate code to restore the stack after all stack restore points + /// in \p StackRestorePoints. + /// + /// \returns A local variable in which to maintain the dynamic top of the + /// unsafe stack if needed. + AllocaInst * + createStackRestorePoints(Function &F, + ArrayRef StackRestorePoints, + Value *StaticTop, bool NeedDynamicTop); + + /// \brief Replace all allocas in \p DynamicAllocas with code to allocate + /// space dynamically on the unsafe stack and store the dynamic unsafe stack + /// top to \p DynamicTop if non-null. + void moveDynamicAllocasToUnsafeStack(Function &F, Value *UnsafeStackPtr, + AllocaInst *DynamicTop, + ArrayRef DynamicAllocas); + +public: + static char ID; // Pass identification, replacement for typeid. + SafeStack(): FunctionPass(ID), DL(nullptr) { + initializeSafeStackPass(*PassRegistry::getPassRegistry()); + } + + virtual void getAnalysisUsage(AnalysisUsage &AU) const { + AU.addRequired(); + } + + virtual bool doInitialization(Module &M) { + DL = &M.getDataLayout(); + + StackPtrTy = Type::getInt8PtrTy(M.getContext()); + IntPtrTy = DL->getIntPtrType(M.getContext()); + Int32Ty = Type::getInt32Ty(M.getContext()); + Int8Ty = Type::getInt8Ty(M.getContext()); + + UnsafeStackPtr = getOrCreateUnsafeStackPtr(M); + + return false; + } + + bool runOnFunction(Function &F); + +}; // class SafeStack + +Constant *SafeStack::getOrCreateUnsafeStackPtr(Module &M) { + // The unsafe stack pointer is stored in a global variable with a magic name. + const char* kUnsafeStackPtrVar = "__safestack_unsafe_stack_ptr"; + + auto UnsafeStackPtr = + dyn_cast_or_null(M.getNamedValue(kUnsafeStackPtrVar)); + + if (!UnsafeStackPtr) { + // The global variable is not defined yet, define it ourselves. + UnsafeStackPtr = new GlobalVariable( + /*Module=*/M, /*Type=*/StackPtrTy, + /*isConstant=*/false, /*Linkage=*/GlobalValue::ExternalLinkage, + /*Initializer=*/0, /*Name=*/kUnsafeStackPtrVar, + /*InsertBefore=*/nullptr, + /*ThreadLocalMode=*/GlobalValue::InitialExecTLSModel); + } else { + // The variable exists, check its type and attributes. + if (UnsafeStackPtr->getValueType() != StackPtrTy) { + report_fatal_error(Twine(kUnsafeStackPtrVar) + + " must have void* type"); + } + + if (!UnsafeStackPtr->isThreadLocal()) { + report_fatal_error(Twine(kUnsafeStackPtrVar) + + " must be thread-local"); + } + } + + return UnsafeStackPtr; +} + +void SafeStack::findInsts(Function &F, + SmallVectorImpl &StaticAllocas, + SmallVectorImpl &DynamicAllocas, + SmallVectorImpl &Returns, + SmallVectorImpl &StackRestorePoints) { + for (Instruction &I : inst_range(&F)) { + if (auto AI = dyn_cast(&I)) { + ++NumAllocas; + + if (IsSafeStackAlloca(AI)) + continue; + + if (AI->isStaticAlloca()) { + ++NumUnsafeStaticAllocas; + StaticAllocas.push_back(AI); + } else { + ++NumUnsafeDynamicAllocas; + DynamicAllocas.push_back(AI); + } + } else if (auto RI = dyn_cast(&I)) { + Returns.push_back(RI); + } else if (auto CI = dyn_cast(&I)) { + // setjmps require stack restore. + if (CI->getCalledFunction() && CI->canReturnTwice()) + StackRestorePoints.push_back(CI); + } else if (auto LP = dyn_cast(&I)) { + // Exception landing pads require stack restore. + StackRestorePoints.push_back(LP); + } + } +} + +AllocaInst * +SafeStack::createStackRestorePoints(Function &F, + ArrayRef StackRestorePoints, + Value *StaticTop, bool NeedDynamicTop) { + if (StackRestorePoints.empty()) + return nullptr; + + AllocaInst *DynamicTop = nullptr; + + IRBuilder<> IRB(StaticTop + ? cast(StaticTop)->getNextNode() + : (Instruction *)F.getEntryBlock().getFirstInsertionPt()); + + // We need the current value of the shadow stack pointer to restore + // after longjmp or exception catching. + + // FIXME: On some platforms this could be handled by the longjmp/exception + // runtime itself. + + if (NeedDynamicTop) + // If we also have dynamic alloca's, the stack pointer value changes + // throughout the function. For now we store it in an alloca. + DynamicTop = IRB.CreateAlloca(StackPtrTy, 0, "unsafe_stack_dynamic_ptr"); + + if (!StaticTop) + // We need the original unsafe stack pointer value, even if there are + // no unsafe static allocas. + StaticTop = IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr"); + + if (NeedDynamicTop) + IRB.CreateStore(StaticTop, DynamicTop); + + // Restore current stack pointer after longjmp/exception catch. + for (Instruction *I : StackRestorePoints) { + ++NumUnsafeStackRestorePoints; + + IRB.SetInsertPoint(cast(I->getNextNode())); + Value *CurrentTop = DynamicTop ? IRB.CreateLoad(DynamicTop) : StaticTop; + IRB.CreateStore(CurrentTop, UnsafeStackPtr); + } + + return DynamicTop; +} + +Value * +SafeStack::moveStaticAllocasToUnsafeStack(Function &F, + ArrayRef StaticAllocas, + ArrayRef Returns) { + if (StaticAllocas.empty()) + return nullptr; + + IRBuilder<> IRB(F.getEntryBlock().getFirstInsertionPt()); + DIBuilder DIB(*F.getParent()); + + // We explicitly compute and set the unsafe stack layout for all unsafe + // static alloca instructions. We save the unsafe "base pointer" in the + // prologue into a local variable and restore it in the epilogue. + + // Load the current stack pointer (we'll also use it as a base pointer). + // FIXME: use a dedicated register for it ? + Instruction *BasePointer = IRB.CreateLoad(UnsafeStackPtr, false, + "unsafe_stack_ptr"); + assert(BasePointer->getType() == StackPtrTy); + + for (ReturnInst *RI : Returns) { + IRB.SetInsertPoint(RI); + IRB.CreateStore(BasePointer, UnsafeStackPtr); + } + + // Compute maximum alignment among static objects on the unsafe stack. + unsigned MaxAlignment = 0; + for (AllocaInst *AI : StaticAllocas) { + Type *Ty = AI->getAllocatedType(); + unsigned Align = + std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()); + if (Align > MaxAlignment) + MaxAlignment = Align; + } + + if (MaxAlignment > StackAlignment) { + // Re-align the base pointer according to the max requested alignment. + assert(isPowerOf2_32(MaxAlignment)); + IRB.SetInsertPoint(cast(BasePointer->getNextNode())); + BasePointer = cast(IRB.CreateIntToPtr( + IRB.CreateAnd(IRB.CreatePtrToInt(BasePointer, IntPtrTy), + ConstantInt::get(IntPtrTy, ~uint64_t(MaxAlignment-1))), + StackPtrTy)); + } + + // Allocate space for every unsafe static AllocaInst on the unsafe stack. + int64_t StaticOffset = 0; // Current stack top. + for (AllocaInst *AI : StaticAllocas) { + IRB.SetInsertPoint(AI); + + auto CArraySize = cast(AI->getArraySize()); + Type *Ty = AI->getAllocatedType(); + + uint64_t Size = DL->getTypeAllocSize(Ty) * CArraySize->getZExtValue(); + if (Size == 0) Size = 1; // Don't create zero-sized stack objects. + + // Ensure the object is properly aligned. + unsigned Align = + std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()); + + // Add alignment. + // NOTE: we ensure that BasePointer itself is aligned to >= Align. + StaticOffset += Size; + StaticOffset = (StaticOffset + Align - 1) / Align * Align; + + Value *Off = IRB.CreateGEP(BasePointer, // BasePointer is i8* + ConstantInt::get(Int32Ty, -StaticOffset)); + Value *NewAI = IRB.CreateBitCast(Off, AI->getType(), AI->getName()); + if (AI->hasName() && isa(NewAI)) + cast(NewAI)->takeName(AI); + + // Replace alloc with the new location. + replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true); + AI->replaceAllUsesWith(NewAI); + AI->eraseFromParent(); + } + + // Re-align BasePointer so that our callees would see it aligned as + // expected. + // FIXME: no need to update BasePointer in leaf functions. + StaticOffset = (StaticOffset + StackAlignment - 1) + / StackAlignment * StackAlignment; + + // Update shadow stack pointer in the function epilogue. + IRB.SetInsertPoint(cast(BasePointer->getNextNode())); + + Value *StaticTop = IRB.CreateGEP(BasePointer, + ConstantInt::get(Int32Ty, -StaticOffset), "unsafe_stack_static_top"); + IRB.CreateStore(StaticTop, UnsafeStackPtr); + return StaticTop; +} + +void SafeStack::moveDynamicAllocasToUnsafeStack( + Function &F, Value *UnsafeStackPtr, AllocaInst *DynamicTop, + ArrayRef DynamicAllocas) { + DIBuilder DIB(*F.getParent()); + + for (AllocaInst *AI : DynamicAllocas) { + IRBuilder<> IRB(AI); + + // Compute the new SP value (after AI). + Value *ArraySize = AI->getArraySize(); + if (ArraySize->getType() != IntPtrTy) + ArraySize = IRB.CreateIntCast(ArraySize, IntPtrTy, false); + + Type *Ty = AI->getAllocatedType(); + uint64_t TySize = DL->getTypeAllocSize(Ty); + Value *Size = IRB.CreateMul(ArraySize, ConstantInt::get(IntPtrTy, TySize)); + + Value *SP = IRB.CreatePtrToInt(IRB.CreateLoad(UnsafeStackPtr), IntPtrTy); + SP = IRB.CreateSub(SP, Size); + + // Align the SP value to satisfy the AllocaInst, type and stack alignments. + unsigned Align = std::max( + std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI->getAlignment()), + (unsigned) StackAlignment); + + assert(isPowerOf2_32(Align)); + Value *NewTop = IRB.CreateIntToPtr( + IRB.CreateAnd(SP, ConstantInt::get(IntPtrTy, ~uint64_t(Align-1))), + StackPtrTy); + + // Save the stack pointer. + IRB.CreateStore(NewTop, UnsafeStackPtr); + if (DynamicTop) + IRB.CreateStore(NewTop, DynamicTop); + + Value *NewAI = IRB.CreateIntToPtr(SP, AI->getType()); + if (AI->hasName() && isa(NewAI)) + NewAI->takeName(AI); + + replaceDbgDeclareForAlloca(AI, NewAI, DIB, /*Deref=*/true); + AI->replaceAllUsesWith(NewAI); + AI->eraseFromParent(); + } + + if (!DynamicAllocas.empty()) { + // Now go through the instructions again, replacing stacksave/stackrestore. + for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie;) { + Instruction *I = &*(It++); + auto II = dyn_cast(I); + if (!II) + continue; + + if (II->getIntrinsicID() == Intrinsic::stacksave) { + IRBuilder<> IRB(II); + Instruction *LI = IRB.CreateLoad(UnsafeStackPtr); + LI->takeName(II); + II->replaceAllUsesWith(LI); + II->eraseFromParent(); + } else if (II->getIntrinsicID() == Intrinsic::stackrestore) { + IRBuilder<> IRB(II); + Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr); + SI->takeName(II); + assert(II->use_empty()); + II->eraseFromParent(); + } + } + } +} + +bool SafeStack::runOnFunction(Function &F) { + auto AA = &getAnalysis(); + + DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n"); + + if (!F.hasFnAttribute(Attribute::SafeStack)) { + DEBUG(dbgs() << "[SafeStack] safestack is not requested" + " for this function\n"); + return false; + } + + if (F.isDeclaration()) { + DEBUG(dbgs() << "[SafeStack] function definition" + " is not available\n"); + return false; + } + + { + // Make sure the regular stack protector won't run on this function + // (safestack attribute takes precedence). + AttrBuilder B; + B.addAttribute(Attribute::StackProtect) + .addAttribute(Attribute::StackProtectReq) + .addAttribute(Attribute::StackProtectStrong); + F.removeAttributes(AttributeSet::FunctionIndex, AttributeSet::get( + F.getContext(), AttributeSet::FunctionIndex, B)); + } + + if (AA->onlyReadsMemory(&F)) { + // XXX: we don't protect against information leak attacks for now. + DEBUG(dbgs() << "[SafeStack] function only reads memory\n"); + return false; + } + + ++NumFunctions; + + SmallVector StaticAllocas; + SmallVector DynamicAllocas; + SmallVector Returns; + + // Collect all points where stack gets unwound and needs to be restored + // This is only necessary because the runtime (setjmp and unwind code) is + // not aware of the unsafe stack and won't unwind/restore it prorerly. + // To work around this problem without changing the runtime, we insert + // instrumentation to restore the unsafe stack pointer when necessary. + SmallVector StackRestorePoints; + + // Find all static and dynamic alloca instructions that must be moved to the + // unsafe stack, all return instructions and stack restore points. + findInsts(F, StaticAllocas, DynamicAllocas, Returns, StackRestorePoints); + + if (StaticAllocas.empty() && DynamicAllocas.empty() && + StackRestorePoints.empty()) + return false; // Nothing to do in this function. + + if (!StaticAllocas.empty() || !DynamicAllocas.empty()) + ++NumUnsafeStackFunctions; // This function has the unsafe stack. + + if (!StackRestorePoints.empty()) + ++NumUnsafeStackRestorePointsFunctions; + + // The top of the unsafe stack after all unsafe static allocas are allocated. + Value *StaticTop = moveStaticAllocasToUnsafeStack(F, StaticAllocas, Returns); + + // Safe stack object that stores the current unsafe stack top. It is updated + // as unsafe dynamic (non-constant-sized) allocas are allocated and freed. + // This is only needed if we need to restore stack pointer after longjmp + // or exceptions, and we have dynamic allocations. + // FIXME: a better alternative might be to store the unsafe stack pointer + // before setjmp / invoke instructions. + AllocaInst *DynamicTop = createStackRestorePoints( + F, StackRestorePoints, StaticTop, !DynamicAllocas.empty()); + + // Handle dynamic allocas. + moveDynamicAllocasToUnsafeStack(F, UnsafeStackPtr, DynamicTop, + DynamicAllocas); + + DEBUG(dbgs() << "[SafeStack] safestack applied\n"); + return true; +} + +} // end anonymous namespace + +char SafeStack::ID = 0; +INITIALIZE_PASS_BEGIN(SafeStack, "safe-stack", + "Safe Stack instrumentation pass", false, false) +INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) +INITIALIZE_PASS_END(SafeStack, "safe-stack", + "Safe Stack instrumentation pass", false, false) + + +FunctionPass *llvm::createSafeStackPass() { + return new SafeStack(); +} Index: test/Transforms/SafeStack/addr-taken.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/addr-taken.ll @@ -0,0 +1,22 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Address-of local taken (j = &a) +; Requires protector. + +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %retval = alloca i32, align 4 + %a = alloca i32, align 4 + %j = alloca i32*, align 8 + store i32 0, i32* %retval + %0 = load i32, i32* %a, align 4 + %add = add nsw i32 %0, 1 + store i32 %add, i32* %a, align 4 + store i32* %a, i32** %j, align 8 + ret void +} + Index: test/Transforms/SafeStack/array-aligned.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/array-aligned.ll @@ -0,0 +1,39 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; array of [16 x i8] + +define void @foo(i8* %a) nounwind uwtable safestack { +entry: + ; CHECK: %[[USP:.*]] = load i8*, i8** @__safestack_unsafe_stack_ptr + + ; CHECK: %[[USST:.*]] = getelementptr i8, i8* %[[USP]], i32 -16 + + ; CHECK: store i8* %[[USST]], i8** @__safestack_unsafe_stack_ptr + + ; CHECK: %[[AADDR:.*]] = alloca i8*, align 8 + %a.addr = alloca i8*, align 8 + + ; CHECK: %[[BUFPTR:.*]] = getelementptr i8, i8* %[[USP]], i32 -16 + ; CHECK: %[[BUFPTR2:.*]] = bitcast i8* %[[BUFPTR]] to [16 x i8]* + %buf = alloca [16 x i8], align 16 + + ; CHECK: store i8* {{.*}}, i8** %[[AADDR]], align 8 + store i8* %a, i8** %a.addr, align 8 + + ; CHECK: %[[GEP:.*]] = getelementptr inbounds [16 x i8], [16 x i8]* %[[BUFPTR2]], i32 0, i32 0 + %gep = getelementptr inbounds [16 x i8], [16 x i8]* %buf, i32 0, i32 0 + + ; CHECK: %[[A2:.*]] = load i8*, i8** %[[AADDR]], align 8 + %a2 = load i8*, i8** %a.addr, align 8 + + ; CHECK: call i8* @strcpy(i8* %[[GEP]], i8* %[[A2]]) + %call = call i8* @strcpy(i8* %gep, i8* %a2) + + ; CHECK: store i8* %[[USP]], i8** @__safestack_unsafe_stack_ptr + ret void +} + +declare i8* @strcpy(i8*, i8*) Index: test/Transforms/SafeStack/array.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/array.ll @@ -0,0 +1,38 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +; array [4 x i8] +; Requires protector. + +define void @foo(i8* %a) nounwind uwtable safestack { +entry: + ; CHECK: %[[USP:.*]] = load i8*, i8** @__safestack_unsafe_stack_ptr + + ; CHECK: %[[USST:.*]] = getelementptr i8, i8* %[[USP]], i32 -16 + + ; CHECK: store i8* %[[USST]], i8** @__safestack_unsafe_stack_ptr + + ; CHECK: %[[AADDR:.*]] = alloca i8*, align 8 + %a.addr = alloca i8*, align 8 + + ; CHECK: %[[BUFPTR:.*]] = getelementptr i8, i8* %[[USP]], i32 -4 + ; CHECK: %[[BUFPTR2:.*]] = bitcast i8* %[[BUFPTR]] to [4 x i8]* + %buf = alloca [4 x i8], align 1 + + ; CHECK: store i8* {{.*}}, i8** %[[AADDR]], align 8 + store i8* %a, i8** %a.addr, align 8 + + ; CHECK: %[[GEP:.*]] = getelementptr inbounds [4 x i8], [4 x i8]* %[[BUFPTR2]], i32 0, i32 0 + %gep = getelementptr inbounds [4 x i8], [4 x i8]* %buf, i32 0, i32 0 + + ; CHECK: %[[A2:.*]] = load i8*, i8** %[[AADDR]], align 8 + %a2 = load i8*, i8** %a.addr, align 8 + + ; CHECK: call i8* @strcpy(i8* %[[GEP]], i8* %[[A2]]) + %call = call i8* @strcpy(i8* %gep, i8* %a2) + + ; CHECK: store i8* %[[USP]], i8** @__safestack_unsafe_stack_ptr + ret void +} + +declare i8* @strcpy(i8*, i8*) Index: test/Transforms/SafeStack/call.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/call.ll @@ -0,0 +1,20 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; no arrays / no nested arrays +; Requires no protector. + +; CHECK-LABEL: @foo( +define void @foo(i8* %a) nounwind uwtable safestack { +entry: + ; CHECK-NOT: __safestack_unsafe_stack_ptr + %a.addr = alloca i8*, align 8 + store i8* %a, i8** %a.addr, align 8 + %0 = load i8*, i8** %a.addr, align 8 + %call = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), i8* %0) + ret void +} + +declare i32 @printf(i8*, ...) Index: test/Transforms/SafeStack/cast.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/cast.ll @@ -0,0 +1,17 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; PtrToInt/IntToPtr Cast +; Requires no protector. + +; CHECK-LABEL: @foo( +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK-NOT: __safestack_unsafe_stack_ptr + %a = alloca i32, align 4 + %0 = ptrtoint i32* %a to i64 + %1 = inttoptr i64 %0 to i32* + ret void +} Index: test/Transforms/SafeStack/constant-gep-call.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/constant-gep-call.ll @@ -0,0 +1,26 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +%struct.nest = type { %struct.pair, %struct.pair } +%struct.pair = type { i32, i32 } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Nested structure, no arrays, no address-of expressions. +; Verify that the resulting gep-of-gep does not incorrectly trigger +; a safe stack protector. +; safestack attribute +; Requires no protector. +; CHECK-LABEL: @foo( +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK-NOT: __safestack_unsafe_stack_ptr + %c = alloca %struct.nest, align 4 + %b = getelementptr inbounds %struct.nest, %struct.nest* %c, i32 0, i32 1 + %_a = getelementptr inbounds %struct.pair, %struct.pair* %b, i32 0, i32 0 + %0 = load i32, i32* %_a, align 4 + %call = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), i32 %0) + ret void +} + +declare i32 @printf(i8*, ...) Index: test/Transforms/SafeStack/constant-gep.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/constant-gep.ll @@ -0,0 +1,20 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +%class.A = type { [2 x i8] } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; [2 x i8] in a class +; safestack attribute +; Requires no protector. +; CHECK-LABEL: @foo( +define signext i8 @foo() nounwind uwtable safestack { +entry: + ; CHECK-NOT: __safestack_unsafe_stack_ptr + %a = alloca %class.A, align 1 + %array = getelementptr inbounds %class.A, %class.A* %a, i32 0, i32 0 + %arrayidx = getelementptr inbounds [2 x i8], [2 x i8]* %array, i32 0, i64 0 + %0 = load i8, i8* %arrayidx, align 1 + ret i8 %0 +} Index: test/Transforms/SafeStack/constant-geps.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/constant-geps.ll @@ -0,0 +1,28 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +%struct.deep = type { %union.anon } +%union.anon = type { %struct.anon } +%struct.anon = type { %struct.anon.0 } +%struct.anon.0 = type { %union.anon.1 } +%union.anon.1 = type { [2 x i8] } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; [2 x i8] nested in several layers of structs and unions +; safestack attribute +; Requires no protector. +; CHECK-LABEL: @foo( +define signext i8 @foo() nounwind uwtable safestack { +entry: + ; CHECK-NOT: __safestack_unsafe_stack_ptr + %x = alloca %struct.deep, align 1 + %b = getelementptr inbounds %struct.deep, %struct.deep* %x, i32 0, i32 0 + %c = bitcast %union.anon* %b to %struct.anon* + %d = getelementptr inbounds %struct.anon, %struct.anon* %c, i32 0, i32 0 + %e = getelementptr inbounds %struct.anon.0, %struct.anon.0* %d, i32 0, i32 0 + %array = bitcast %union.anon.1* %e to [2 x i8]* + %arrayidx = getelementptr inbounds [2 x i8], [2 x i8]* %array, i32 0, i64 0 + %0 = load i8, i8* %arrayidx, align 1 + ret i8 %0 +} Index: test/Transforms/SafeStack/dynamic-alloca.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/dynamic-alloca.ll @@ -0,0 +1,21 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Variable sized alloca +; safestack attribute +; Requires protector. +define void @foo(i32 %n) nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %n.addr = alloca i32, align 4 + %a = alloca i32*, align 8 + store i32 %n, i32* %n.addr, align 4 + %0 = load i32, i32* %n.addr, align 4 + %conv = sext i32 %0 to i64 + %1 = alloca i8, i64 %conv + %2 = bitcast i8* %1 to i32* + store i32* %2, i32** %a, align 8 + ret void +} Index: test/Transforms/SafeStack/escape-addr-pointer.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-addr-pointer.ll @@ -0,0 +1,23 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of a pointer +; safestack attribute +; Requires protector. +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %a = alloca i32*, align 8 + %b = alloca i32**, align 8 + %call = call i32* @getp() + store i32* %call, i32** %a, align 8 + store i32** %a, i32*** %b, align 8 + %0 = load i32**, i32*** %b, align 8 + call void @funcall2(i32** %0) + ret void +} + +declare void @funcall2(i32**) +declare i32* @getp() Index: test/Transforms/SafeStack/escape-bitcast-store.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-bitcast-store.ll @@ -0,0 +1,23 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of a local cast to a ptr of a different type +; (e.g., int a; ... ; float *b = &a;) +; safestack attribute +; Requires protector. +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %a = alloca i32, align 4 + %b = alloca float*, align 8 + store i32 0, i32* %a, align 4 + %0 = bitcast i32* %a to float* + store float* %0, float** %b, align 8 + %1 = load float*, float** %b, align 8 + %call = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), float* %1) + ret void +} + +declare i32 @printf(i8*, ...) Index: test/Transforms/SafeStack/escape-bitcast-store2.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-bitcast-store2.ll @@ -0,0 +1,20 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of a local cast to a ptr of a different type (optimized) +; (e.g., int a; ... ; float *b = &a;) +; safestack attribute +; Requires protector. +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %a = alloca i32, align 4 + store i32 0, i32* %a, align 4 + %0 = bitcast i32* %a to float* + call void @funfloat(float* %0) nounwind + ret void +} + +declare void @funfloat(float*) Index: test/Transforms/SafeStack/escape-call.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-call.ll @@ -0,0 +1,16 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Passing addr-of to function call +; Requires protector. +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %b = alloca i32, align 4 + call void @funcall(i32* %b) nounwind + ret void +} + +declare void @funcall(i32*) Index: test/Transforms/SafeStack/escape-casted-pointer.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-casted-pointer.ll @@ -0,0 +1,24 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of a casted pointer +; safestack attribute +; Requires protector. +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %a = alloca i32*, align 8 + %b = alloca float**, align 8 + %call = call i32* @getp() + store i32* %call, i32** %a, align 8 + %0 = bitcast i32** %a to float** + store float** %0, float*** %b, align 8 + %1 = load float**, float*** %b, align 8 + call void @funfloat2(float** %1) + ret void +} + +declare void @funfloat2(float**) +declare i32* @getp() Index: test/Transforms/SafeStack/escape-gep-call.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-gep-call.ll @@ -0,0 +1,20 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +%struct.pair = type { i32, i32 } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of struct element, GEP followed by callinst. +; safestack attribute +; Requires protector. +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %c = alloca %struct.pair, align 4 + %y = getelementptr inbounds %struct.pair, %struct.pair* %c, i64 0, i32 1 + %call = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i64 0, i64 0), i32* %y) nounwind + ret void +} + +declare i32 @printf(i8*, ...) Index: test/Transforms/SafeStack/escape-gep-invoke.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-gep-invoke.ll @@ -0,0 +1,34 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +%struct.pair = type { i32, i32 } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of a struct element passed into an invoke instruction. +; (GEP followed by an invoke) +; safestack attribute +; Requires protector. +define i32 @foo() uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %c = alloca %struct.pair, align 4 + %exn.slot = alloca i8* + %ehselector.slot = alloca i32 + %a = getelementptr inbounds %struct.pair, %struct.pair* %c, i32 0, i32 0 + store i32 0, i32* %a, align 4 + %a1 = getelementptr inbounds %struct.pair, %struct.pair* %c, i32 0, i32 0 + invoke void @_Z3exceptPi(i32* %a1) + to label %invoke.cont unwind label %lpad + +invoke.cont: + ret i32 0 + +lpad: + %0 = landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*) + catch i8* null + ret i32 0 +} + +declare void @_Z3exceptPi(i32*) +declare i32 @__gxx_personality_v0(...) Index: test/Transforms/SafeStack/escape-gep-negative.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-gep-negative.ll @@ -0,0 +1,18 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of a local, optimized into a GEP (e.g., &a - 12) +; safestack attribute +; Requires protector. +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %a = alloca i32, align 4 + %add.ptr5 = getelementptr inbounds i32, i32* %a, i64 -12 + %call = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i64 0, i64 0), i32* %add.ptr5) nounwind + ret void +} + +declare i32 @printf(i8*, ...) Index: test/Transforms/SafeStack/escape-gep-ptrtoint.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-gep-ptrtoint.ll @@ -0,0 +1,22 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +%struct.pair = type { i32, i32 } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of struct element, GEP followed by ptrtoint. +; safestack attribute +; Requires protector. +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %c = alloca %struct.pair, align 4 + %b = alloca i32*, align 8 + %y = getelementptr inbounds %struct.pair, %struct.pair* %c, i32 0, i32 1 + %0 = ptrtoint i32* %y to i64 + %call = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), i64 %0) + ret void +} + +declare i32 @printf(i8*, ...) Index: test/Transforms/SafeStack/escape-gep-store.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-gep-store.ll @@ -0,0 +1,23 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +%struct.pair = type { i32, i32 } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of struct element. (GEP followed by store). +; safestack attribute +; Requires protector. +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %c = alloca %struct.pair, align 4 + %b = alloca i32*, align 8 + %y = getelementptr inbounds %struct.pair, %struct.pair* %c, i32 0, i32 1 + store i32* %y, i32** %b, align 8 + %0 = load i32*, i32** %b, align 8 + %call = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), i32* %0) + ret void +} + +declare i32 @printf(i8*, ...) Index: test/Transforms/SafeStack/escape-phi-call.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-phi-call.ll @@ -0,0 +1,36 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of in phi instruction +; Requires protector. +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %x = alloca double, align 8 + %call = call double @testi_aux() nounwind + store double %call, double* %x, align 8 + %cmp = fcmp ogt double %call, 3.140000e+00 + br i1 %cmp, label %if.then, label %if.else + +if.then: ; preds = %entry + %call1 = call double @testi_aux() nounwind + store double %call1, double* %x, align 8 + br label %if.end4 + +if.else: ; preds = %entry + %cmp2 = fcmp ogt double %call, 1.000000e+00 + br i1 %cmp2, label %if.then3, label %if.end4 + +if.then3: ; preds = %if.else + br label %if.end4 + +if.end4: ; preds = %if.else, %if.then3, %if.then + %y.0 = phi double* [ null, %if.then ], [ %x, %if.then3 ], [ null, %if.else ] + %call5 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i64 0, i64 0), double* %y.0) nounwind + ret void +} + +declare double @testi_aux() +declare i32 @printf(i8*, ...) Index: test/Transforms/SafeStack/escape-select-call.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-select-call.ll @@ -0,0 +1,22 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of in select instruction +; safestack attribute +; Requires protector. +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %x = alloca double, align 8 + %call = call double @testi_aux() nounwind + store double %call, double* %x, align 8 + %cmp2 = fcmp ogt double %call, 0.000000e+00 + %y.1 = select i1 %cmp2, double* %x, double* null + %call2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), double* %y.1) + ret void +} + +declare double @testi_aux() +declare i32 @printf(i8*, ...) Index: test/Transforms/SafeStack/escape-vector.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/escape-vector.ll @@ -0,0 +1,21 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +%struct.vec = type { <4 x i32> } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of a vector nested in a struct +; safestack attribute +; Requires protector. +define void @foo() nounwind uwtable safestack { +entry: + ; CHECK: __safestack_unsafe_stack_ptr + %c = alloca %struct.vec, align 16 + %y = getelementptr inbounds %struct.vec, %struct.vec* %c, i64 0, i32 0 + %add.ptr = getelementptr inbounds <4 x i32>, <4 x i32>* %y, i64 -12 + %call = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i64 0, i64 0), <4 x i32>* %add.ptr) nounwind + ret void +} + +declare i32 @printf(i8*, ...) Index: test/Transforms/SafeStack/invoke.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/invoke.ll @@ -0,0 +1,33 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Addr-of a variable passed into an invoke instruction. +; safestack attribute +; Requires protector and stack restore after landing pad. +define i32 @foo() uwtable safestack { +entry: + ; CHECK: %[[SP:.*]] = load i8*, i8** @__safestack_unsafe_stack_ptr + ; CHECK: %[[STATICTOP:.*]] = getelementptr i8, i8* %[[SP]], i32 -16 + %a = alloca i32, align 4 + %exn.slot = alloca i8* + %ehselector.slot = alloca i32 + store i32 0, i32* %a, align 4 + invoke void @_Z3exceptPi(i32* %a) + to label %invoke.cont unwind label %lpad + +invoke.cont: + ret i32 0 + +lpad: + ; CHECK: landingpad + ; CHECK-NEXT: catch + %0 = landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*) + catch i8* null + ; CHECK-NEXT: store i8* %[[STATICTOP]], i8** @__safestack_unsafe_stack_ptr + ret i32 0 +} + +declare void @_Z3exceptPi(i32*) +declare i32 @__gxx_personality_v0(...) Index: test/Transforms/SafeStack/no-attr.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/no-attr.ll @@ -0,0 +1,25 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; no safestack attribute +; Requires no protector. + +; CHECK: @foo +define void @foo(i8* %a) nounwind uwtable { +entry: + ; CHECK-NOT: __safestack_unsafe_stack_ptr + %a.addr = alloca i8*, align 8 + %buf = alloca [16 x i8], align 16 + store i8* %a, i8** %a.addr, align 8 + %arraydecay = getelementptr inbounds [16 x i8], [16 x i8]* %buf, i32 0, i32 0 + %0 = load i8*, i8** %a.addr, align 8 + %call = call i8* @strcpy(i8* %arraydecay, i8* %0) + %arraydecay1 = getelementptr inbounds [16 x i8], [16 x i8]* %buf, i32 0, i32 0 + %call2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), i8* %arraydecay1) + ret void +} + +declare i8* @strcpy(i8*, i8*) +declare i32 @printf(i8*, ...) Index: test/Transforms/SafeStack/phi-cycle.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/phi-cycle.ll @@ -0,0 +1,50 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +%struct.small = type { i8 } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; Address-of a structure taken in a function with a loop where +; the alloca is an incoming value to a PHI node and a use of that PHI +; node is also an incoming value. +; Verify that the address-of analysis does not get stuck in infinite +; recursion when chasing the alloca through the PHI nodes. +; Requires protector. +define i32 @foo(i32 %arg) nounwind uwtable safestack { +bb: + ; CHECK: __safestack_unsafe_stack_ptr + %tmp = alloca %struct.small*, align 8 + %tmp1 = call i32 (...) @dummy(%struct.small** %tmp) nounwind + %tmp2 = load %struct.small*, %struct.small** %tmp, align 8 + %tmp3 = ptrtoint %struct.small* %tmp2 to i64 + %tmp4 = trunc i64 %tmp3 to i32 + %tmp5 = icmp sgt i32 %tmp4, 0 + br i1 %tmp5, label %bb6, label %bb21 + +bb6: ; preds = %bb17, %bb + %tmp7 = phi %struct.small* [ %tmp19, %bb17 ], [ %tmp2, %bb ] + %tmp8 = phi i64 [ %tmp20, %bb17 ], [ 1, %bb ] + %tmp9 = phi i32 [ %tmp14, %bb17 ], [ %tmp1, %bb ] + %tmp10 = getelementptr inbounds %struct.small, %struct.small* %tmp7, i64 0, i32 0 + %tmp11 = load i8, i8* %tmp10, align 1 + %tmp12 = icmp eq i8 %tmp11, 1 + %tmp13 = add nsw i32 %tmp9, 8 + %tmp14 = select i1 %tmp12, i32 %tmp13, i32 %tmp9 + %tmp15 = trunc i64 %tmp8 to i32 + %tmp16 = icmp eq i32 %tmp15, %tmp4 + br i1 %tmp16, label %bb21, label %bb17 + +bb17: ; preds = %bb6 + %tmp18 = getelementptr inbounds %struct.small*, %struct.small** %tmp, i64 %tmp8 + %tmp19 = load %struct.small*, %struct.small** %tmp18, align 8 + %tmp20 = add i64 %tmp8, 1 + br label %bb6 + +bb21: ; preds = %bb6, %bb + %tmp22 = phi i32 [ %tmp1, %bb ], [ %tmp14, %bb6 ] + %tmp23 = call i32 (...) @dummy(i32 %tmp22) nounwind + ret i32 undef +} + +declare i32 @dummy(...) Index: test/Transforms/SafeStack/setjmp.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/setjmp.ll @@ -0,0 +1,37 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +%struct.__jmp_buf_tag = type { [8 x i64], i32, %struct.__sigset_t } +%struct.__sigset_t = type { [16 x i64] } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 +@buf = internal global [1 x %struct.__jmp_buf_tag] zeroinitializer, align 16 + +; setjmp/longjmp test. +; Requires protector. +define i32 @foo() nounwind uwtable safestack { +entry: + ; CHECK: %[[SP:.*]] = load i8*, i8** @__safestack_unsafe_stack_ptr + ; CHECK: %[[STATICTOP:.*]] = getelementptr i8, i8* %[[SP]], i32 -16 + %retval = alloca i32, align 4 + %x = alloca i32, align 4 + store i32 0, i32* %retval + store i32 42, i32* %x, align 4 + %call = call i32 @_setjmp(%struct.__jmp_buf_tag* getelementptr inbounds ([1 x %struct.__jmp_buf_tag], [1 x %struct.__jmp_buf_tag]* @buf, i32 0, i32 0)) returns_twice + ; CHECK: setjmp + ; CHECK-NEXT: store i8* %[[STATICTOP]], i8** @__safestack_unsafe_stack_ptr + %tobool = icmp ne i32 %call, 0 + br i1 %tobool, label %if.else, label %if.then +if.then: ; preds = %entry + call void @funcall(i32* %x) + br label %if.end +if.else: ; preds = %entry + call i32 (...) @dummy() + br label %if.end +if.end: ; preds = %if.else, %if.then + ret i32 0 +} + +declare i32 @_setjmp(%struct.__jmp_buf_tag*) +declare void @funcall(i32*) +declare i32 @dummy(...) Index: test/Transforms/SafeStack/setjmp2.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/setjmp2.ll @@ -0,0 +1,42 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +%struct.__jmp_buf_tag = type { [8 x i64], i32, %struct.__sigset_t } +%struct.__sigset_t = type { [16 x i64] } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 +@buf = internal global [1 x %struct.__jmp_buf_tag] zeroinitializer, align 16 + +; setjmp/longjmp test with dynamically sized array. +; Requires protector. +; CHECK: @foo(i32 %[[ARG:.*]]) +define i32 @foo(i32 %size) nounwind uwtable safestack { +entry: + ; CHECK: %[[DYNPTR:.*]] = alloca i8* + ; CHECK-NEXT: %[[SP:.*]] = load i8*, i8** @__safestack_unsafe_stack_ptr + ; CHECK-NEXT: store i8* %[[SP]], i8** %[[DYNPTR]] + + ; CHECK-NEXT: %[[ZEXT:.*]] = zext i32 %[[ARG]] to i64 + ; CHECK-NEXT: %[[MUL:.*]] = mul i64 %[[ZEXT]], 4 + ; CHECK-NEXT: %[[SP2:.*]] = load i8*, i8** @__safestack_unsafe_stack_ptr + ; CHECK-NEXT: %[[PTRTOINT:.*]] = ptrtoint i8* %[[SP2]] to i64 + ; CHECK-NEXT: %[[SUB:.*]] = sub i64 %[[PTRTOINT]], %[[MUL]] + ; CHECK-NEXT: %[[AND:.*]] = and i64 %[[SUB]], -16 + ; CHECK-NEXT: %[[INTTOPTR:.*]] = inttoptr i64 %[[AND]] to i8* + ; CHECK-NEXT: store i8* %[[INTTOPTR]], i8** @__safestack_unsafe_stack_ptr + ; CHECK-NEXT: store i8* %[[INTTOPTR]], i8** %unsafe_stack_dynamic_ptr + ; CHECK-NEXT: %[[ALLOCA:.*]] = inttoptr i64 %[[SUB]] to i32* + %a = alloca i32, i32 %size + + ; CHECK: setjmp + ; CHECK-NEXT: %[[LOAD:.*]] = load i8*, i8** %[[DYNPTR]] + ; CHECK-NEXT: store i8* %[[LOAD]], i8** @__safestack_unsafe_stack_ptr + %call = call i32 @_setjmp(%struct.__jmp_buf_tag* getelementptr inbounds ([1 x %struct.__jmp_buf_tag], [1 x %struct.__jmp_buf_tag]* @buf, i32 0, i32 0)) returns_twice + + ; CHECK: call void @funcall(i32* %[[ALLOCA]]) + call void @funcall(i32* %a) + ret i32 0 +} + +declare i32 @_setjmp(%struct.__jmp_buf_tag*) +declare void @funcall(i32*) Index: test/Transforms/SafeStack/struct.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/struct.ll @@ -0,0 +1,41 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck %s + +%struct.foo = type { [16 x i8] } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; struct { [16 x i8] } + +define void @foo(i8* %a) nounwind uwtable safestack { +entry: + ; CHECK: %[[USP:.*]] = load i8*, i8** @__safestack_unsafe_stack_ptr + + ; CHECK: %[[USST:.*]] = getelementptr i8, i8* %[[USP]], i32 -16 + + ; CHECK: store i8* %[[USST]], i8** @__safestack_unsafe_stack_ptr + + ; CHECK: %[[AADDR:.*]] = alloca i8*, align 8 + %a.addr = alloca i8*, align 8 + + ; CHECK: %[[BUFPTR:.*]] = getelementptr i8, i8* %[[USP]], i32 -16 + ; CHECK: %[[BUFPTR2:.*]] = bitcast i8* %[[BUFPTR]] to %struct.foo* + %buf = alloca %struct.foo, align 1 + + ; CHECK: store i8* {{.*}}, i8** %[[AADDR]], align 8 + store i8* %a, i8** %a.addr, align 8 + + ; CHECK: %[[GEP:.*]] = getelementptr inbounds %struct.foo, %struct.foo* %[[BUFPTR2]], i32 0, i32 0, i32 0 + %gep = getelementptr inbounds %struct.foo, %struct.foo* %buf, i32 0, i32 0, i32 0 + + ; CHECK: %[[A:.*]] = load i8*, i8** %[[AADDR]], align 8 + %a2 = load i8*, i8** %a.addr, align 8 + + ; CHECK: call i8* @strcpy(i8* %[[GEP]], i8* %[[A]]) + %call = call i8* @strcpy(i8* %gep, i8* %a2) + + ; CHECK: store i8* %[[USP]], i8** @__safestack_unsafe_stack_ptr + ret void +} + +declare i8* @strcpy(i8*, i8*)