Index: include/llvm/Analysis/TargetTransformInfo.h =================================================================== --- include/llvm/Analysis/TargetTransformInfo.h +++ include/llvm/Analysis/TargetTransformInfo.h @@ -501,6 +501,12 @@ Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst, Type *ExpectedType) const; + /// \returns True if the target stores the unsafe stack pointer for the safe + /// stack instrumentation at a fixed offset in some non-standard address + /// space, and populates the address space and offset as appropriate. + bool getUnsafeStackPtrLocation(unsigned &AddressSpace, + unsigned &Offset) const; + /// @} private: @@ -595,6 +601,8 @@ MemIntrinsicInfo &Info) = 0; virtual Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst, Type *ExpectedType) = 0; + virtual bool getUnsafeStackPtrLocation(unsigned &AddressSpace, + unsigned &Offset) = 0; }; template @@ -769,6 +777,10 @@ Type *ExpectedType) override { return Impl.getOrCreateResultFromMemIntrinsic(Inst, ExpectedType); } + bool getUnsafeStackPtrLocation(unsigned &AddressSpace, + unsigned &Offset) override { + return Impl.getUnsafeStackPtrLocation(AddressSpace, Offset); + } }; template Index: include/llvm/Analysis/TargetTransformInfoImpl.h =================================================================== --- include/llvm/Analysis/TargetTransformInfoImpl.h +++ include/llvm/Analysis/TargetTransformInfoImpl.h @@ -325,6 +325,10 @@ Type *ExpectedType) { return nullptr; } + + bool getUnsafeStackPtrLocation(unsigned &AddressSpace, unsigned &Offset) { + return false; + } }; /// \brief CRTP base class for use as a mix-in that aids implementing Index: include/llvm/Bitcode/LLVMBitCodes.h =================================================================== --- include/llvm/Bitcode/LLVMBitCodes.h +++ include/llvm/Bitcode/LLVMBitCodes.h @@ -400,7 +400,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/Transforms/Instrumentation.h =================================================================== --- include/llvm/Transforms/Instrumentation.h +++ include/llvm/Transforms/Instrumentation.h @@ -110,6 +110,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. +ModulePass *createSafeStackPass(); + } // End llvm namespace #endif Index: lib/Analysis/TargetTransformInfo.cpp =================================================================== --- lib/Analysis/TargetTransformInfo.cpp +++ lib/Analysis/TargetTransformInfo.cpp @@ -275,6 +275,11 @@ return TTIImpl->getOrCreateResultFromMemIntrinsic(Inst, ExpectedType); } +bool TargetTransformInfo::getUnsafeStackPtrLocation(unsigned &AddressSpace, + unsigned &Offset) const { + return TTIImpl->getUnsafeStackPtrLocation(AddressSpace, Offset); +} + TargetTransformInfo::Concept::~Concept() {} TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI) {} 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 @@ -961,6 +961,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; @@ -1270,6 +1271,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; @@ -1346,6 +1348,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 @@ -1143,6 +1143,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" @@ -447,6 +448,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 @@ -1249,6 +1249,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/Target/X86/X86TargetTransformInfo.h =================================================================== --- lib/Target/X86/X86TargetTransformInfo.h +++ lib/Target/X86/X86TargetTransformInfo.h @@ -103,6 +103,8 @@ Type *Ty); bool isLegalMaskedLoad(Type *DataType, int Consecutive); bool isLegalMaskedStore(Type *DataType, int Consecutive); + bool getUnsafeStackPtrLocation(unsigned &AddressSpace, + unsigned &Offset); /// @} }; Index: lib/Target/X86/X86TargetTransformInfo.cpp =================================================================== --- lib/Target/X86/X86TargetTransformInfo.cpp +++ lib/Target/X86/X86TargetTransformInfo.cpp @@ -1124,3 +1124,33 @@ return isLegalMaskedLoad(DataType, Consecutive); } +bool X86TTIImpl::getUnsafeStackPtrLocation(unsigned &AddressSpace, + unsigned &Offset) { + if (ST->isTargetDarwin() && + TLI->getTargetMachine().getCodeModel() != CodeModel::Kernel) { + /* On Darwin, we store the unsafe stack pointer in one of the + * thread-specific data slots that are reserved for system libraries. + * Such data slots are directly accessible through the %gs segment, and + * are described in detail in pthreads/pthread_machdep.h in Darwin Libc. + * As of Libc-825, slots 0 - 255 are reserved, but only slots 0 - 119 + * are actually used. We use slot 192, which is accessible as + * %gs:(192 * sizeof(void*)) + */ + AddressSpace = 256; + Offset = 192 * (ST->is64Bit() ? 8 : 4); + return true; + } + + /* TODO: To make accessing the unsafe stack pointer faster, we plan to + * eventually store it directly in the thread control block data structure on + * platforms where this structure is pointed to by %fs or %gs. This is exactly + * the same mechanism as currently being used by the traditional stack + * protector pass to store the stack guard (see getStackCookieLocation() + * function above). Doing so requires changing the tcbhead_t struct in glibc + * on Linux and tcb struct in libc on FreeBSD. + */ + + // By default, the unsafe stack pointer will be stored in a thread-local + // variable with a predefined name. + return false; +} 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,559 @@ +//===-- 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 instructino (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()) { + const Instruction *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; + + /* fallthough */ + + 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 + // BitCast/PHI/Select/GEP/etc. 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() /* && CS.doesNotThrow()*/ && + 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 ModulePass { + const DataLayout *DL; + + AliasAnalysis *AA; + + Type *StackPtrTy; + Type *IntPtrTy; + Type *Int32Ty; + Type *Int8Ty; + + bool runOnFunction(Function &F); + Constant *getOrCreateUnsafeStackPtr(Function &F); + +public: + static char ID; // Pass identification, replacement for typeid. + SafeStack(): ModulePass(ID), DL(nullptr) { + initializeSafeStackPass(*PassRegistry::getPassRegistry()); + } + + virtual void getAnalysisUsage(AnalysisUsage &AU) const { + AU.addRequired(); + AU.addRequired(); + } + + virtual bool runOnModule(Module &M) { + DEBUG(dbgs() << "[SafeStack] Module: " + << M.getModuleIdentifier() << "\n"); + + AA = &getAnalysis(); + DL = &M.getDataLayout(); + + StackPtrTy = Type::getInt8PtrTy(M.getContext()); + IntPtrTy = DL->getIntPtrType(M.getContext()); + Int32Ty = Type::getInt32Ty(M.getContext()); + Int8Ty = Type::getInt8Ty(M.getContext()); + + // Add safe stack instrumentation to all functions that need it + for (Function &F : M) { + DEBUG(dbgs() << "[SafeStack] Function: " << F.getName() << "\n"); + + if (!F.hasFnAttribute(Attribute::SafeStack)) { + DEBUG(dbgs() << "[SafeStack] safestack is not requested" + " for this function\n"); + continue; + } + + if (F.isDeclaration()) { + DEBUG(dbgs() << "[SafeStack] function definition" + " is not available\n"); + continue; + } + + { + // 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"); + continue; + } + + runOnFunction(F); + DEBUG(dbgs() << "[SafeStack] safestack applied\n"); + } + + return true; + } +}; // class SafeStack + +Constant *SafeStack::getOrCreateUnsafeStackPtr(Function &F) { + const TargetTransformInfo *TTI = + &getAnalysis().getTTI(F); + + // Check where the unsafe stack pointer is stored on this architecture + unsigned AddressSpace, Offset; + if (TTI->getUnsafeStackPtrLocation(AddressSpace, Offset)) { + // The unsafe stack pointer is stored at a fixed location + // (usually in the thread control block) + Constant *OffsetVal = ConstantInt::get(Int32Ty, Offset); + return ConstantExpr::getIntToPtr( + OffsetVal, Int8Ty->getPointerTo()->getPointerTo(AddressSpace)); + } else { + // The unsafe stack pointer is stored in a global variable with a magic name + // FIXME: share this constant between LLVM and compiler-rt + // FIXME: make the name start with "llvm." + static const char* unsafe_stack_ptr_var = "__safestack_unsafe_stack_ptr"; + + auto UnsafeStackPtr = dyn_cast_or_null( + F.getParent()->getNamedValue(unsafe_stack_ptr_var)); + + if (!UnsafeStackPtr) { + // The global variable is not defined yet, define it ourselves + UnsafeStackPtr = new GlobalVariable( + /*Module=*/*F.getParent(), /*Type=*/Int8Ty->getPointerTo(), + /*isConstant=*/false, /*Linkage=*/GlobalValue::ExternalLinkage, + /*Initializer=*/0, /*Name=*/unsafe_stack_ptr_var, + /*InsertBefore=*/nullptr, + /*ThreadLocalMode=*/GlobalValue::InitialExecTLSModel); + } else { + // The variable exists, check its type and attributes + if (UnsafeStackPtr->getValueType() != Int8Ty->getPointerTo()) { + report_fatal_error(Twine(unsafe_stack_ptr_var) + + " must have void* type"); + } + + if (!UnsafeStackPtr->isThreadLocal()) { + report_fatal_error(Twine(unsafe_stack_ptr_var) + + " must be thread-local"); + } + } + + return UnsafeStackPtr; + } +} + +bool SafeStack::runOnFunction(Function &F) { + ++NumFunctions; + + unsigned StackAlignment = 16; + Constant *UnsafeStackPtr = getOrCreateUnsafeStackPtr(F); + + 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 + for (inst_iterator It = inst_begin(&F), Ie = inst_end(&F); It != Ie; ++It) { + Instruction *I = &*It; + + if (AllocaInst *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 (ReturnInst *RI = dyn_cast(I)) { + Returns.push_back(RI); + + } else if (CallInst *CI = dyn_cast(I)) { + // setjmps require stack restore + if (CI->getCalledFunction() && CI->canReturnTwice()) + //CI->getCalledFunction()->getName() == "_setjmp") + StackRestorePoints.push_back(CI); + + } else if (LandingPadInst *LP = dyn_cast(I)) { + // Excpetion landing pads require stack restore + StackRestorePoints.push_back(LP); + } + } + + 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; + + DIBuilder DIB(*F.getParent()); + IRBuilder<> IRB(F.getEntryBlock().getFirstInsertionPt()); + + // The top of the unsafe stack after all unsafe static allocas are allocated + Value *StaticTop = NULL; + + if (!StaticAllocas.empty()) { + // 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); + + ConstantInt *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())); + + StaticTop = IRB.CreateGEP(BasePointer, + ConstantInt::get(Int32Ty, -StaticOffset), "unsafe_stack_static_top"); + IRB.CreateStore(StaticTop, UnsafeStackPtr); + } + + IRB.SetInsertPoint( + StaticTop ? cast(StaticTop)->getNextNode() + : (Instruction*) F.getEntryBlock().getFirstInsertionPt()); + + // 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. + // FIXME: a better alternative might be to store the unsafe stack pointer + // before setjmp / invoke instructions. + AllocaInst *DynamicTop = NULL; + + if (!StackRestorePoints.empty()) { + // We need the current value of the shadow stack pointer to restore + // after longjmp or exception catching. + + // FIXME: in the future, this should be handled by the longjmp/exception + // runtime itself + + if (!DynamicAllocas.empty()) { + // If we also have dynamic alloca's, the stack pointer value changes + // throughout the function. For now we store it in an allca. + DynamicTop = IRB.CreateAlloca(StackPtrTy, 0, "unsafe_stack_dynamic_ptr"); + } + + if (!StaticTop) { + // We need to original unsafe stack pointer value, even if there are + // no unsafe static allocas + StaticTop = IRB.CreateLoad(UnsafeStackPtr, false, "unsafe_stack_ptr"); + } + + if (!DynamicAllocas.empty()) { + IRB.CreateStore(StaticTop, DynamicTop); + } + } + + // Handle dynamic alloca now + for (AllocaInst *AI : DynamicAllocas) { + IRB.SetInsertPoint(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++); + IntrinsicInst *II = dyn_cast(I); + if (!II) + continue; + + if (II->getIntrinsicID() == Intrinsic::stacksave) { + IRB.SetInsertPoint(II); + Instruction *LI = IRB.CreateLoad(UnsafeStackPtr); + LI->takeName(II); + II->replaceAllUsesWith(LI); + II->eraseFromParent(); + } else if (II->getIntrinsicID() == Intrinsic::stackrestore) { + IRB.SetInsertPoint(II); + Instruction *SI = IRB.CreateStore(II->getArgOperand(0), UnsafeStackPtr); + SI->takeName(II); + assert(II->use_empty()); + II->eraseFromParent(); + } + } + } + + // 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 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) + + +ModulePass *llvm::createSafeStackPass() { + return new SafeStack(); +} Index: test/Transforms/SafeStack/safestack.ll =================================================================== --- /dev/null +++ test/Transforms/SafeStack/safestack.ll @@ -0,0 +1,627 @@ +; RUN: opt -safe-stack -S -mtriple=i386-pc-linux-gnu < %s -o - | FileCheck --check-prefix=CHECK --check-prefix=LINUX --check-prefix=LINUX-I386 %s +; RUN: opt -safe-stack -S -mtriple=x86_64-pc-linux-gnu < %s -o - | FileCheck --check-prefix=CHECK --check-prefix=LINUX --check-prefix=LINUX-X64 %s +; RUN: opt -safe-stack -S -mtriple=x86_64-apple-darwin < %s -o - | FileCheck --check-prefix=CHECK --check-prefix=DARWIN-X64 %s + +%struct.foo = type { [16 x i8] } +%struct.foo.0 = type { [4 x i8] } +%struct.pair = type { i32, i32 } +%struct.nest = type { %struct.pair, %struct.pair } +%struct.vec = type { <4 x i32> } +%class.A = type { [2 x i8] } +%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] } +%struct.small = type { i8 } + +@.str = private unnamed_addr constant [4 x i8] c"%s\0A\00", align 1 + +; test0: no safestack attribute +; Requires no protector. + +; CHECK-LABEL: @test0( +define void @test0(i8* %a) nounwind uwtable { +entry: + ; CHECK-NOT: __safestack_unsafe_stack_ptr + ; CHECK-NOT: addrspace + %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 +} + +; array of [16 x i8] + +; CHECK-LABEL: @test1( +define void @test1(i8* %a) nounwind uwtable safestack { +entry: + ; LINUX: %[[USP:.*]] = load i8*, i8** @__safestack_unsafe_stack_ptr + ; DARWIN-X64: %[[USP:.*]] = load i8*, i8* addrspace(256)* inttoptr (i32 1536 to i8* addrspace(256)*) + + ; CHECK: %[[USST:.*]] = getelementptr i8, i8* %[[USP]], i32 -16 + + ; LINUX: store i8* %[[USST]], i8** @__safestack_unsafe_stack_ptr + ; DARWIN-X64: store i8* %[[USST]], i8* addrspace(256)* inttoptr (i32 1536 to i8* addrspace(256)*) + + ; 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) + + ; LINUX: store i8* %[[USP]], i8** @__safestack_unsafe_stack_ptr + ; DARWIN-X64: store i8* %[[USP]], i8* addrspace(256)* inttoptr (i32 1536 to i8* addrspace(256)*) + ret void +} + +; struct { [16 x i8] } + +; CHECK-LABEL: @test2( +define void @test2(i8* %a) nounwind uwtable safestack { +entry: + ; LINUX: %[[USP:.*]] = load i8*, i8** @__safestack_unsafe_stack_ptr + ; DARWIN-X64: %[[USP:.*]] = load i8*, i8* addrspace(256)* inttoptr (i32 1536 to i8* addrspace(256)*) + + ; CHECK: %[[USST:.*]] = getelementptr i8, i8* %[[USP]], i32 -16 + + ; LINUX: store i8* %[[USST]], i8** @__safestack_unsafe_stack_ptr + ; DARWIN-X64: store i8* %[[USST]], i8* addrspace(256)* inttoptr (i32 1536 to i8* addrspace(256)*) + + ; 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* %[[A2]]) + %call = call i8* @strcpy(i8* %gep, i8* %a2) + + ; LINUX: store i8* %[[USP]], i8** @__safestack_unsafe_stack_ptr + ; DARWIN-X64: store i8* %[[USP]], i8* addrspace(256)* inttoptr (i32 1536 to i8* addrspace(256)*) + ret void +} + +; array [4 x i8] +; Requires protector. + +; CHECK-LABEL: @test3( +define void @test3(i8* %a) nounwind uwtable safestack { +entry: + ; LINUX: %[[USP:.*]] = load i8*, i8** @__safestack_unsafe_stack_ptr + ; DARWIN-X64: %[[USP:.*]] = load i8*, i8* addrspace(256)* inttoptr (i32 1536 to i8* addrspace(256)*) + + ; CHECK: %[[USST:.*]] = getelementptr i8, i8* %[[USP]], i32 -16 + + ; LINUX: store i8* %[[USST]], i8** @__safestack_unsafe_stack_ptr + ; DARWIN-X64: store i8* %[[USST]], i8* addrspace(256)* inttoptr (i32 1536 to i8* addrspace(256)*) + + ; 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) + + ; LINUX: store i8* %[[USP]], i8** @__safestack_unsafe_stack_ptr + ; DARWIN-X64: store i8* %[[USP]], i8* addrspace(256)* inttoptr (i32 1536 to i8* addrspace(256)*) + ret void +} + +; no arrays / no nested arrays +; Requires no protector. + +; CHECK-LABEL: @test4( +define void @test4(i8* %a) nounwind uwtable safestack { +entry: + ; CHECK-NOT: __safestack_unsafe_stack_ptr + ; CHECK-NOT: addrspace + %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 +} + +; Address-of local taken (j = &a) +; Requires protector. + +; CHECK-LABEL: @test5( +define void @test5() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; PtrToInt/IntToPtr Cast +; Requires no protector. + +; CHECK-LABEL: @test6( +define void @test6() nounwind uwtable safestack { +entry: + ; LINUX-NOT: __safestack_unsafe_stack_ptr + ; DARWIN-X64-NOT: addrspace + %a = alloca i32, align 4 + %0 = ptrtoint i32* %a to i64 + %1 = inttoptr i64 %0 to i32* + ret void +} + +; Passing addr-of to function call +; Requires protector. +; CHECK-LABEL: @test7( +define void @test7() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %b = alloca i32, align 4 + call void @funcall(i32* %b) nounwind + ret void +} + +; test8: Addr-of in select instruction +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test8( +define void @test8() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test9: Addr-of in phi instruction +; Requires protector. +; CHECK-LABEL: @test9( +define void @test9() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test10: Addr-of struct element. (GEP followed by store). +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test10( +define void @test10() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test11: Addr-of struct element, GEP followed by ptrtoint. +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test11( +define void @test11() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test12: Addr-of struct element, GEP followed by callinst. +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test12( +define void @test12() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test13: Addr-of a local, optimized into a GEP (e.g., &a - 12) +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test13( +define void @test13() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test14: Addr-of a local cast to a ptr of a different type +; (e.g., int a; ... ; float *b = &a;) +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test14( +define void @test14() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test15: Addr-of a local cast to a ptr of a different type (optimized) +; (e.g., int a; ... ; float *b = &a;) +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test15( +define void @test15() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test16: Addr-of a vector nested in a struct +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test16( +define void @test16() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test17: Addr-of a variable passed into an invoke instruction. +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test17( +define i32 @test17() uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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: + %0 = landingpad { i8*, i32 } personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*) + catch i8* null + ret i32 0 +} + +; test18: Addr-of a struct element passed into an invoke instruction. +; (GEP followed by an invoke) +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test18( +define i32 @test18() uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test19: Addr-of a pointer +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test19( +define void @test19() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test20: Addr-of a casted pointer +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test20( +define void @test20() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test21: [2 x i8] in a class +; safestack attribute +; Requires no protector. +; CHECK-LABEL: @test21( +define signext i8 @test21() nounwind uwtable safestack { +entry: + ; LINUX-NOT: __safestack_unsafe_stack_ptr + ; DARWIN-X64-NOT: addrspace + %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 +} + +; test22: [2 x i8] nested in several layers of structs and unions +; safestack attribute +; Requires no protector. +; CHECK-LABEL: @test22( +define signext i8 @test22() nounwind uwtable safestack { +entry: + ; LINUX-NOT: __safestack_unsafe_stack_ptr + ; DARWIN-X64-NOT: addrspace + %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 +} + +; test23: Variable sized alloca +; safestack attribute +; Requires protector. +; CHECK-LABEL: @test23( +define void @test23(i32 %n) nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +; test24: array of [4 x i32] +; safestack attribute +; Requires no protector, constant index. +; CHECK-LABEL: @test24( +define i32 @test24() nounwind uwtable safestack { +entry: + ; LINUX-NOT: __safestack_unsafe_stack_ptr + ; DARWIN-X64-NOT: addrspace + %a = alloca [4 x i32], align 16 + %arrayidx = getelementptr inbounds [4 x i32], [4 x i32]* %a, i32 0, i64 0 + %0 = load i32, i32* %arrayidx, align 4 + ret i32 %0 +} + +; test26: 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: @test25( +define void @test25() nounwind uwtable safestack { +entry: + ; LINUX-NOT: __safestack_unsafe_stack_ptr + ; DARWIN-X64-NOT: addrspace + %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 +} + +; test27: 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. +; CHECK-LABEL: @test26( +define i32 @test26(i32 %arg) nounwind uwtable safestack { +bb: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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 +} + +%struct.__jmp_buf_tag = type { [8 x i64], i32, %struct.__sigset_t } +%struct.__sigset_t = type { [16 x i64] } +@buf = internal global [1 x %struct.__jmp_buf_tag] zeroinitializer, align 16 + +; test28: setjmp/longjmp test. +; Requires protector. +; CHECK-LABEL: @test27( +define i32 @test27() nounwind uwtable safestack { +entry: + ; LINUX: __safestack_unsafe_stack_ptr + ; DARWIN-X64: addrspace + %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)) #3 + %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 double @testi_aux() +declare i8* @strcpy(i8*, i8*) +declare i32 @printf(i8*, ...) +declare void @funcall(i32*) +declare void @funcall2(i32**) +declare void @funfloat(float*) +declare void @funfloat2(float**) +declare void @_Z3exceptPi(i32*) +declare i32 @__gxx_personality_v0(...) +declare i32* @getp() +declare i32 @dummy(...)